accountant_cn
This commit is contained in:
8
accountant_cn/__init__.py
Normal file
8
accountant_cn/__init__.py
Normal file
@@ -0,0 +1,8 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Accountant CN — the full accounting workspace as ONE module."""
|
||||
from . import models
|
||||
from . import controllers
|
||||
from . import wizard
|
||||
from . import lib
|
||||
# `tests/` is discovered by Odoo's test runner, not imported at normal load.
|
||||
from .hooks import post_init_hook # noqa: F401
|
||||
105
accountant_cn/__manifest__.py
Normal file
105
accountant_cn/__manifest__.py
Normal file
@@ -0,0 +1,105 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
{
|
||||
'name': 'Accountant CN',
|
||||
'version': '20.0.1.0.0',
|
||||
'summary': 'Full accounting workspace for Odoo Community — enterprise-shaped menus, reports, closing, loans, bank reconciliation and audit working files (LGPL-3)',
|
||||
'description': """
|
||||
Accountant CN
|
||||
=============
|
||||
|
||||
A single, native Odoo module that brings the full accounting workspace to
|
||||
Odoo 20 Community: the Enterprise-shaped menu tree, 20 financial reports with
|
||||
an Odoo ControlPanel, fiscal-year closing and period locking, bank
|
||||
reconciliation, loans management and period-review working files.
|
||||
|
||||
This is a true merge of seven earlier LGPL-3 modules into ONE module: models,
|
||||
views, data, security, assets and translations all live in a single flat
|
||||
module tree. No menu, view, action, model or translation was changed. Every
|
||||
XML ID now belongs to the ``accountant_cn`` namespace, and all 1020 zh_CN
|
||||
translation entries (including deliberately different translations of the
|
||||
same English term in different models) were preserved.
|
||||
|
||||
License: LGPL-3. No Odoo Enterprise source code is used, copied or derived.
|
||||
""",
|
||||
'category': 'Accounting/Accounting',
|
||||
'license': 'LGPL-3',
|
||||
'author': 'DN Community',
|
||||
'website': '',
|
||||
'depends': [
|
||||
'account',
|
||||
'mail',
|
||||
'base_import',
|
||||
],
|
||||
'data': [
|
||||
# ---- security first
|
||||
'security/account_groups.xml',
|
||||
# Odoo derives the target model from the CSV basename before '-':
|
||||
# every file below must start with `ir.access` to load into ir.access.
|
||||
'security/ir.access-reports_core.csv',
|
||||
'security/ir.access-fr.csv',
|
||||
'security/ir.access-accounting.csv',
|
||||
'security/ir.access-bank_rec.csv',
|
||||
'security/ir.access-loans.csv',
|
||||
'security/ir.access-audit.csv',
|
||||
|
||||
# ---- report engines: actions/views/data/menus before the menu tree
|
||||
'views/views__dn_report_actions.xml',
|
||||
'views/views__dn_report_views.xml',
|
||||
'data/data__dn_reports_data.xml',
|
||||
'views/views__dn_fr_views.xml',
|
||||
'views/views__dn_fr_actions.xml',
|
||||
'data/data__dn_fr_reports.xml',
|
||||
'views/views__dn_fr_menus.xml',
|
||||
'views/views__dn_report_menuitems.xml',
|
||||
|
||||
# ---- accounting essentials + their menus
|
||||
'views/views__dn_accounting_views.xml',
|
||||
'views/views__dn_bank_rec_views.xml',
|
||||
|
||||
# ---- Enterprise-shaped menu tree: re-parents the menus above and
|
||||
# defines menu_action_working_files + account_assets_liabilities_menu
|
||||
'views/views__menu.xml',
|
||||
|
||||
# ---- loans (parent menu defined by the menu tree above)
|
||||
'views/wizard__dn_loan_compute_wizard_views.xml',
|
||||
'views/wizard__dn_loan_close_wizard_views.xml',
|
||||
'views/views__dn_loan_views.xml',
|
||||
'views/views__dn_loan_line_views.xml',
|
||||
'views/views__dn_loan_move_views.xml',
|
||||
|
||||
# ---- audit working files (update of menu_action_working_files last)
|
||||
'data/data__dn_audit_cycle_data.xml',
|
||||
'views/views__dn_audit_return_views.xml',
|
||||
'views/views__dn_audit_check_views.xml',
|
||||
'views/views__dn_audit_menus.xml',
|
||||
],
|
||||
'assets': {
|
||||
'web.assets_backend': [
|
||||
# Odoo only serves assets from <module>/static/; all JS/XML/SCSS
|
||||
# from the seven sources are collected here under dn_* filenames.
|
||||
'accountant_cn/static/src/js/dn_report_view.js',
|
||||
'accountant_cn/static/src/js/dn_report_view.xml',
|
||||
'accountant_cn/static/src/js/dn_report_view.scss',
|
||||
'accountant_cn/static/src/js/dn_fr_model.js',
|
||||
'accountant_cn/static/src/js/dn_fr_line_cell.js',
|
||||
'accountant_cn/static/src/js/dn_fr_line_cell.xml',
|
||||
'accountant_cn/static/src/js/dn_fr_line.js',
|
||||
'accountant_cn/static/src/js/dn_fr_line.xml',
|
||||
'accountant_cn/static/src/js/dn_fr_header.js',
|
||||
'accountant_cn/static/src/js/dn_fr_header.xml',
|
||||
'accountant_cn/static/src/js/dn_fr_filter_date.js',
|
||||
'accountant_cn/static/src/js/dn_fr_filter_date.xml',
|
||||
'accountant_cn/static/src/js/dn_fr_filter_comparison.js',
|
||||
'accountant_cn/static/src/js/dn_fr_filter_comparison.xml',
|
||||
'accountant_cn/static/src/js/dn_fr_view.js',
|
||||
'accountant_cn/static/src/js/dn_fr_view.xml',
|
||||
'accountant_cn/static/src/js/dn_fr_view.scss',
|
||||
'accountant_cn/static/src/scss/dn_lock_date.scss',
|
||||
'accountant_cn/static/src/scss/dn_loan.scss',
|
||||
],
|
||||
},
|
||||
'post_init_hook': 'post_init_hook',
|
||||
'installable': True,
|
||||
'application': True,
|
||||
'auto_install': False,
|
||||
}
|
||||
2
accountant_cn/controllers/__init__.py
Normal file
2
accountant_cn/controllers/__init__.py
Normal file
@@ -0,0 +1,2 @@
|
||||
from . import dn_report_controller
|
||||
from . import dn_fr_controller
|
||||
26
accountant_cn/controllers/dn_fr_controller.py
Normal file
26
accountant_cn/controllers/dn_fr_controller.py
Normal file
@@ -0,0 +1,26 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""JSON endpoint feeding the report client action (Odoo 20 uses type=jsonrpc)."""
|
||||
import logging
|
||||
from odoo import http
|
||||
from odoo.http import request, route
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class DnFrController(http.Controller):
|
||||
|
||||
@route("/dn/fr/data", type="jsonrpc", auth="user")
|
||||
def get_report_data(self, report_id=None, options=None, **kwargs):
|
||||
try:
|
||||
report = request.env["dn.fr"].browse(int(report_id or 0)).exists()
|
||||
except (TypeError, ValueError):
|
||||
report = request.env["dn.fr"]
|
||||
if not report:
|
||||
return {"ok": False, "error": "Report not found."}
|
||||
options = dict(options or {})
|
||||
options.setdefault("company_ids", request.env.company.ids)
|
||||
try:
|
||||
return {"ok": True, "data": report.get_report_data(options)}
|
||||
except Exception as exc:
|
||||
_logger.exception("DN report %s failed", report.code)
|
||||
return {"ok": False, "error": str(exc)}
|
||||
37
accountant_cn/controllers/dn_report_controller.py
Normal file
37
accountant_cn/controllers/dn_report_controller.py
Normal file
@@ -0,0 +1,37 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""JSON endpoint feeding the report client action.
|
||||
|
||||
Odoo 20 renamed the JSON-RPC route type from ``json`` to ``jsonrpc``; such a
|
||||
route receives the ``params`` object of the JSON-RPC envelope as keyword
|
||||
arguments and its return value is wrapped back into ``{"result": ...}``. The
|
||||
web client's ``rpc()`` helper does exactly that, so the payload returned here
|
||||
is what the Owl component sees as the resolved value.
|
||||
"""
|
||||
import logging
|
||||
|
||||
from odoo import http
|
||||
from odoo.http import request, route
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class DnReportController(http.Controller):
|
||||
|
||||
@route("/dn/report/data", type="jsonrpc", auth="user")
|
||||
def get_report_data(self, report_id=None, options=None, **kwargs):
|
||||
try:
|
||||
report = request.env["dn.report"].browse(int(report_id or 0)).exists()
|
||||
except (TypeError, ValueError):
|
||||
report = request.env["dn.report"]
|
||||
if not report:
|
||||
return {"ok": False, "error": "Report not found."}
|
||||
|
||||
options = dict(options or {})
|
||||
options.setdefault("company_ids", request.env.company.ids)
|
||||
|
||||
try:
|
||||
data = report.get_report_data(options)
|
||||
except Exception as exc: # noqa: BLE001 - surface the message in the UI
|
||||
_logger.exception("DN report %s failed", report.code)
|
||||
return {"ok": False, "error": str(exc)}
|
||||
return {"ok": True, "data": data}
|
||||
72
accountant_cn/data/data__dn_audit_cycle_data.xml
Normal file
72
accountant_cn/data/data__dn_audit_cycle_data.xml
Normal file
@@ -0,0 +1,72 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<odoo>
|
||||
<!-- The standard audit cycles. Not exhaustive on purpose: these are the
|
||||
areas almost every close touches, and the list is editable so a
|
||||
company can add its own. -->
|
||||
<record id="cycle_bank" model="dn.audit.cycle">
|
||||
<field name="name">Bank</field>
|
||||
<field name="code">BANK</field>
|
||||
<field name="sequence">10</field>
|
||||
<field name="description">Bank reconciliations and cash cut-off.</field>
|
||||
</record>
|
||||
<record id="cycle_payroll" model="dn.audit.cycle">
|
||||
<field name="name">Payroll</field>
|
||||
<field name="code">PAYROLL</field>
|
||||
<field name="sequence">20</field>
|
||||
<field name="description">Payroll accruals, social charges and withholdings.</field>
|
||||
</record>
|
||||
<record id="cycle_cutoff" model="dn.audit.cycle">
|
||||
<field name="name">Cut-off</field>
|
||||
<field name="code">CUTOFF</field>
|
||||
<field name="sequence">30</field>
|
||||
<field name="description">Revenue and expense accruals, goods in transit.</field>
|
||||
</record>
|
||||
<record id="cycle_tax" model="dn.audit.cycle">
|
||||
<field name="name">Tax</field>
|
||||
<field name="code">TAX</field>
|
||||
<field name="sequence">40</field>
|
||||
<field name="description">VAT and other tax balances and returns.</field>
|
||||
</record>
|
||||
<record id="cycle_fixed_assets" model="dn.audit.cycle">
|
||||
<field name="name">Fixed Assets</field>
|
||||
<field name="code">ASSETS</field>
|
||||
<field name="sequence">50</field>
|
||||
<field name="description">Depreciation, disposals and impairment.</field>
|
||||
</record>
|
||||
<record id="cycle_inventory" model="dn.audit.cycle">
|
||||
<field name="name">Inventory</field>
|
||||
<field name="code">STOCK</field>
|
||||
<field name="sequence">60</field>
|
||||
<field name="description">Stock valuation, provisions and cost of goods sold.</field>
|
||||
</record>
|
||||
<record id="cycle_intercompany" model="dn.audit.cycle">
|
||||
<field name="name">Intercompany</field>
|
||||
<field name="code">INTERCO</field>
|
||||
<field name="sequence">70</field>
|
||||
<field name="description">Intercompany balances and reconciliations.</field>
|
||||
</record>
|
||||
|
||||
<!-- Two checks that make the feature usable out of the box. Kept minimal:
|
||||
anything more specific would be presuming how a given company closes
|
||||
its books. -->
|
||||
<record id="template_bank_reconciled" model="dn.audit.check.template">
|
||||
<field name="name">All bank accounts reconciled</field>
|
||||
<field name="sequence">10</field>
|
||||
<field name="check_type">check</field>
|
||||
<field name="cycle_id" ref="cycle_bank"/>
|
||||
<field name="description"><![CDATA[
|
||||
<p>Every bank journal shows a zero unreconciled balance at the end
|
||||
of the period, and the bank statements have been imported up to the
|
||||
period end.</p>
|
||||
]]></field>
|
||||
</record>
|
||||
<record id="template_bank_statement" model="dn.audit.check.template">
|
||||
<field name="name">Bank statements uploaded</field>
|
||||
<field name="sequence">20</field>
|
||||
<field name="check_type">file</field>
|
||||
<field name="cycle_id" ref="cycle_bank"/>
|
||||
<field name="description"><![CDATA[
|
||||
<p>Attach the period-end bank statements for every bank account.</p>
|
||||
]]></field>
|
||||
</record>
|
||||
</odoo>
|
||||
1342
accountant_cn/data/data__dn_fr_reports.xml
Normal file
1342
accountant_cn/data/data__dn_fr_reports.xml
Normal file
File diff suppressed because it is too large
Load Diff
213
accountant_cn/data/data__dn_reports_data.xml
Normal file
213
accountant_cn/data/data__dn_reports_data.xml
Normal file
@@ -0,0 +1,213 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<odoo noupdate="1">
|
||||
|
||||
<!--
|
||||
Reports are pure data. Sign convention follows the ledger: debit is
|
||||
positive, credit is negative. Income therefore shows as negative and
|
||||
a "Net Profit" line flips its sign for readability.
|
||||
|
||||
The strings below are the English source. Chinese is shipped as a
|
||||
translation in i18n/zh_CN.po, so the same data record renders in both
|
||||
languages without duplicating the report definitions.
|
||||
-->
|
||||
|
||||
<!-- ==================== Trial Balance ==================== -->
|
||||
<record id="dn_report_trial_balance" model="dn.report">
|
||||
<field name="name">Trial Balance</field>
|
||||
<field name="code">DN_TB</field>
|
||||
<field name="sequence">10</field>
|
||||
<field name="group_by_account" eval="True"/>
|
||||
<field name="description">Debit and credit balances grouped by account type, expandable to individual accounts.</field>
|
||||
</record>
|
||||
|
||||
<record id="dn_tb_line_assets" model="dn.report.line">
|
||||
<field name="report_id" ref="dn_report_trial_balance"/>
|
||||
<field name="name">Assets</field>
|
||||
<field name="code">ASSETS</field>
|
||||
<field name="sequence">10</field>
|
||||
</record>
|
||||
<record id="dn_tb_exp_assets" model="dn.report.expression">
|
||||
<field name="report_line_id" ref="dn_tb_line_assets"/>
|
||||
<field name="label">ASSETS</field>
|
||||
<field name="engine">domain</field>
|
||||
<field name="formula">[('account_id.account_type', 'in', ['asset_receivable', 'asset_cash', 'asset_current', 'asset_non_current', 'asset_prepayments', 'asset_fixed'])]</field>
|
||||
</record>
|
||||
|
||||
<record id="dn_tb_line_liabilities" model="dn.report.line">
|
||||
<field name="report_id" ref="dn_report_trial_balance"/>
|
||||
<field name="name">Liabilities</field>
|
||||
<field name="code">LIAB</field>
|
||||
<field name="sequence">20</field>
|
||||
</record>
|
||||
<record id="dn_tb_exp_liab" model="dn.report.expression">
|
||||
<field name="report_line_id" ref="dn_tb_line_liabilities"/>
|
||||
<field name="label">LIAB</field>
|
||||
<field name="engine">domain</field>
|
||||
<field name="formula">[('account_id.account_type', 'in', ['liability_payable', 'liability_credit_card', 'liability_current', 'liability_non_current'])]</field>
|
||||
</record>
|
||||
|
||||
<record id="dn_tb_line_equity" model="dn.report.line">
|
||||
<field name="report_id" ref="dn_report_trial_balance"/>
|
||||
<field name="name">Equity</field>
|
||||
<field name="code">EQUITY</field>
|
||||
<field name="sequence">30</field>
|
||||
</record>
|
||||
<record id="dn_tb_exp_equity" model="dn.report.expression">
|
||||
<field name="report_line_id" ref="dn_tb_line_equity"/>
|
||||
<field name="label">EQUITY</field>
|
||||
<field name="engine">domain</field>
|
||||
<field name="formula">[('account_id.account_type', 'in', ['equity', 'equity_unaffected', 'equity_retained'])]</field>
|
||||
</record>
|
||||
|
||||
<record id="dn_tb_line_income" model="dn.report.line">
|
||||
<field name="report_id" ref="dn_report_trial_balance"/>
|
||||
<field name="name">Income</field>
|
||||
<field name="code">INCOME</field>
|
||||
<field name="sequence">40</field>
|
||||
</record>
|
||||
<record id="dn_tb_exp_income" model="dn.report.expression">
|
||||
<field name="report_line_id" ref="dn_tb_line_income"/>
|
||||
<field name="label">INCOME</field>
|
||||
<field name="engine">domain</field>
|
||||
<field name="formula">[('account_id.account_type', 'in', ['income', 'income_other'])]</field>
|
||||
</record>
|
||||
|
||||
<record id="dn_tb_line_expenses" model="dn.report.line">
|
||||
<field name="report_id" ref="dn_report_trial_balance"/>
|
||||
<field name="name">Expenses</field>
|
||||
<field name="code">EXPENSES</field>
|
||||
<field name="sequence">50</field>
|
||||
</record>
|
||||
<record id="dn_tb_exp_expenses" model="dn.report.expression">
|
||||
<field name="report_line_id" ref="dn_tb_line_expenses"/>
|
||||
<field name="label">EXPENSES</field>
|
||||
<field name="engine">domain</field>
|
||||
<field name="formula">[('account_id.account_type', 'in', ['expense', 'expense_other', 'expense_depreciation', 'expense_direct_cost'])]</field>
|
||||
</record>
|
||||
|
||||
<record id="dn_tb_line_total" model="dn.report.line">
|
||||
<field name="report_id" ref="dn_report_trial_balance"/>
|
||||
<field name="name">Total (must be zero)</field>
|
||||
<field name="code">TOTAL</field>
|
||||
<field name="sequence">60</field>
|
||||
<field name="is_total" eval="True"/>
|
||||
</record>
|
||||
<record id="dn_tb_exp_total" model="dn.report.expression">
|
||||
<field name="report_line_id" ref="dn_tb_line_total"/>
|
||||
<field name="label">TOTAL</field>
|
||||
<field name="engine">aggregation</field>
|
||||
<field name="formula">ASSETS + LIAB + EQUITY + INCOME + EXPENSES</field>
|
||||
</record>
|
||||
|
||||
<!-- ==================== Profit & Loss ==================== -->
|
||||
<record id="dn_report_profit_loss" model="dn.report">
|
||||
<field name="name">Profit and Loss</field>
|
||||
<field name="code">DN_PL</field>
|
||||
<field name="sequence">20</field>
|
||||
<field name="group_by_account" eval="True"/>
|
||||
<field name="description">Income and expenses of the period. Net profit = -(income + expenses).</field>
|
||||
</record>
|
||||
|
||||
<record id="dn_pl_line_income" model="dn.report.line">
|
||||
<field name="report_id" ref="dn_report_profit_loss"/>
|
||||
<field name="name">Operating Income</field>
|
||||
<field name="code">INCOME</field>
|
||||
<field name="sequence">10</field>
|
||||
</record>
|
||||
<record id="dn_pl_exp_income" model="dn.report.expression">
|
||||
<field name="report_line_id" ref="dn_pl_line_income"/>
|
||||
<field name="label">PL_INCOME</field>
|
||||
<field name="engine">domain</field>
|
||||
<field name="formula">[('account_id.account_type', 'in', ['income', 'income_other'])]</field>
|
||||
</record>
|
||||
|
||||
<record id="dn_pl_line_expenses" model="dn.report.line">
|
||||
<field name="report_id" ref="dn_report_profit_loss"/>
|
||||
<field name="name">Cost of Sales and Expenses</field>
|
||||
<field name="code">EXPENSES</field>
|
||||
<field name="sequence">20</field>
|
||||
</record>
|
||||
<record id="dn_pl_exp_expenses" model="dn.report.expression">
|
||||
<field name="report_line_id" ref="dn_pl_line_expenses"/>
|
||||
<field name="label">PL_EXPENSES</field>
|
||||
<field name="engine">domain</field>
|
||||
<field name="formula">[('account_id.account_type', 'in', ['expense', 'expense_other', 'expense_depreciation', 'expense_direct_cost'])]</field>
|
||||
</record>
|
||||
|
||||
<record id="dn_pl_line_net" model="dn.report.line">
|
||||
<field name="report_id" ref="dn_report_profit_loss"/>
|
||||
<field name="name">Net Profit</field>
|
||||
<field name="code">NET</field>
|
||||
<field name="sequence">30</field>
|
||||
<field name="is_total" eval="True"/>
|
||||
</record>
|
||||
<record id="dn_pl_exp_net" model="dn.report.expression">
|
||||
<field name="report_line_id" ref="dn_pl_line_net"/>
|
||||
<field name="label">PL_NET</field>
|
||||
<field name="engine">aggregation</field>
|
||||
<field name="formula">-(PL_INCOME + PL_EXPENSES)</field>
|
||||
</record>
|
||||
|
||||
<!-- ==================== Balance Sheet ==================== -->
|
||||
<record id="dn_report_balance_sheet" model="dn.report">
|
||||
<field name="name">Balance Sheet</field>
|
||||
<field name="code">DN_BS</field>
|
||||
<field name="sequence">30</field>
|
||||
<field name="group_by_account" eval="True"/>
|
||||
<field name="description">Assets = Liabilities + Equity, expandable to individual accounts.</field>
|
||||
</record>
|
||||
|
||||
<record id="dn_bs_line_assets" model="dn.report.line">
|
||||
<field name="report_id" ref="dn_report_balance_sheet"/>
|
||||
<field name="name">Total Assets</field>
|
||||
<field name="code">BS_ASSETS</field>
|
||||
<field name="sequence">10</field>
|
||||
</record>
|
||||
<record id="dn_bs_exp_assets" model="dn.report.expression">
|
||||
<field name="report_line_id" ref="dn_bs_line_assets"/>
|
||||
<field name="label">BS_ASSETS</field>
|
||||
<field name="engine">domain</field>
|
||||
<field name="formula">[('account_id.account_type', 'in', ['asset_receivable', 'asset_cash', 'asset_current', 'asset_non_current', 'asset_prepayments', 'asset_fixed'])]</field>
|
||||
</record>
|
||||
|
||||
<record id="dn_bs_line_liab" model="dn.report.line">
|
||||
<field name="report_id" ref="dn_report_balance_sheet"/>
|
||||
<field name="name">Total Liabilities</field>
|
||||
<field name="code">BS_LIAB</field>
|
||||
<field name="sequence">20</field>
|
||||
</record>
|
||||
<record id="dn_bs_exp_liab" model="dn.report.expression">
|
||||
<field name="report_line_id" ref="dn_bs_line_liab"/>
|
||||
<field name="label">BS_LIAB</field>
|
||||
<field name="engine">domain</field>
|
||||
<field name="formula">[('account_id.account_type', 'in', ['liability_payable', 'liability_credit_card', 'liability_current', 'liability_non_current'])]</field>
|
||||
</record>
|
||||
|
||||
<record id="dn_bs_line_equity" model="dn.report.line">
|
||||
<field name="report_id" ref="dn_report_balance_sheet"/>
|
||||
<field name="name">Total Equity (including current year profit)</field>
|
||||
<field name="code">BS_EQUITY</field>
|
||||
<field name="sequence">30</field>
|
||||
</record>
|
||||
<record id="dn_bs_exp_equity" model="dn.report.expression">
|
||||
<field name="report_line_id" ref="dn_bs_line_equity"/>
|
||||
<field name="label">BS_EQUITY</field>
|
||||
<field name="engine">aggregation</field>
|
||||
<field name="formula">-(BS_ASSETS + BS_LIAB)</field>
|
||||
</record>
|
||||
|
||||
<record id="dn_bs_line_check" model="dn.report.line">
|
||||
<field name="report_id" ref="dn_report_balance_sheet"/>
|
||||
<field name="name">Balance Check (assets + liabilities + equity, must be zero)</field>
|
||||
<field name="code">BS_CHECK</field>
|
||||
<field name="sequence">40</field>
|
||||
<field name="is_total" eval="True"/>
|
||||
</record>
|
||||
<record id="dn_bs_exp_check" model="dn.report.expression">
|
||||
<field name="report_line_id" ref="dn_bs_line_check"/>
|
||||
<field name="label">BS_CHECK</field>
|
||||
<field name="engine">aggregation</field>
|
||||
<field name="formula">BS_ASSETS + BS_LIAB + BS_EQUITY</field>
|
||||
</record>
|
||||
|
||||
</odoo>
|
||||
13
accountant_cn/hooks.py
Normal file
13
accountant_cn/hooks.py
Normal file
@@ -0,0 +1,13 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Post-install hook: give existing accounting administrators the full
|
||||
accounting feature set (see models/account_groups.py for why Community needs
|
||||
this)."""
|
||||
|
||||
import logging
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def post_init_hook(env):
|
||||
env["res.groups"]._dn_ensure_accounting_feature_groups()
|
||||
_logger.info("DN Accounting Menu: accounting group chain repaired.")
|
||||
6123
accountant_cn/i18n/zh_CN.po
Normal file
6123
accountant_cn/i18n/zh_CN.po
Normal file
File diff suppressed because it is too large
Load Diff
16
accountant_cn/models/__init__.py
Normal file
16
accountant_cn/models/__init__.py
Normal file
@@ -0,0 +1,16 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from . import account_groups
|
||||
# report engines
|
||||
from . import dn_report
|
||||
from . import dn_fr
|
||||
# accounting essentials
|
||||
from . import dn_fiscal_year
|
||||
from . import dn_bank_rec
|
||||
# loans (journal first: dn_loan imports from it)
|
||||
from . import dn_loan_journal
|
||||
from . import dn_loan
|
||||
from . import dn_loan_line
|
||||
from . import dn_loan_move
|
||||
# audit working files
|
||||
from . import dn_audit_return
|
||||
from . import dn_audit_check
|
||||
57
accountant_cn/models/account_groups.py
Normal file
57
accountant_cn/models/account_groups.py
Normal file
@@ -0,0 +1,57 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Group wiring for the Accounting application.
|
||||
|
||||
Odoo 20 Community stops the accounting group chain early:
|
||||
|
||||
group_account_manager -> group_account_invoice
|
||||
|
||||
which leaves a full accounting *administrator* without
|
||||
``group_account_readonly`` (needed by every report action and most Accounting
|
||||
menu entries) and without ``group_account_basic`` (needed by the dashboard).
|
||||
|
||||
Enterprise repairs it across `accountant` and `account_accountant`. We do the
|
||||
same in one place below, so the reports installed by this suite are actually
|
||||
reachable by the person who installed them.
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
from odoo import api, models
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ResGroups(models.Model):
|
||||
_inherit = "res.groups"
|
||||
|
||||
@api.model
|
||||
def _dn_ensure_accounting_feature_groups(self):
|
||||
"""Make every accounting administrator a full accounting user.
|
||||
|
||||
``implied_ids`` is normally enough: Odoo resolves group membership
|
||||
transitively through ``all_implied_ids``, so a user in
|
||||
``group_account_manager`` automatically benefits from the groups it now
|
||||
implies. This method additionally *materialises* the membership for
|
||||
users who already existed before the upgrade, which keeps
|
||||
``res_groups_users_rel`` consistent for anything that reads it directly
|
||||
(ACLs, record rules, some reports) instead of going through the ORM
|
||||
cache.
|
||||
"""
|
||||
manager = self.env.ref("account.group_account_manager", raise_if_not_found=False)
|
||||
user_group = self.env.ref("account.group_account_user", raise_if_not_found=False)
|
||||
if not manager or not user_group:
|
||||
return
|
||||
|
||||
# Repair the chain if a later module re-broke it.
|
||||
if user_group not in manager.implied_ids:
|
||||
manager.write({"implied_ids": [(4, user_group.id)]})
|
||||
|
||||
users = manager.user_ids
|
||||
missing = users - user_group.user_ids
|
||||
if missing:
|
||||
user_group.write({"user_ids": [(4, uid) for uid in missing.ids]})
|
||||
_logger.info(
|
||||
"DN Accounting Menu: granted full accounting features to %s user(s): %s",
|
||||
len(missing),
|
||||
", ".join(missing.mapped("login")),
|
||||
)
|
||||
131
accountant_cn/models/dn_audit_check.py
Normal file
131
accountant_cn/models/dn_audit_check.py
Normal file
@@ -0,0 +1,131 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Checks: the individual items an accountant works through.
|
||||
|
||||
A check is deliberately small. It records *what* has to be looked at, *how* it
|
||||
is recorded (cleared, not applicable, or with a comment), and who touched it.
|
||||
It does not try to evaluate anything by itself - an automated check that
|
||||
silently decides the books are fine is worse than no check at all, because it
|
||||
hides the judgement the reviewer was supposed to make.
|
||||
"""
|
||||
|
||||
from odoo import api, fields, models, _
|
||||
|
||||
|
||||
class DnAuditCheck(models.Model):
|
||||
_name = "dn.audit.check"
|
||||
_description = "Audit Check"
|
||||
# mail.thread so `tracking` on `result` is meaningful: the trail of who
|
||||
# cleared which check, and when, is the audit evidence this model exists to
|
||||
# produce. Without it `tracking=True` is silently ignored.
|
||||
_inherit = ["mail.thread"]
|
||||
_order = "return_id, sequence, id"
|
||||
|
||||
return_id = fields.Many2one(
|
||||
comodel_name="dn.audit.return",
|
||||
string="Working File",
|
||||
required=True,
|
||||
ondelete="cascade",
|
||||
index=True,
|
||||
)
|
||||
company_id = fields.Many2one(related="return_id.company_id", store=True, index=True)
|
||||
currency_id = fields.Many2one(related="return_id.currency_id", readonly=True)
|
||||
|
||||
name = fields.Char(string="Name", required=True, translate=True)
|
||||
sequence = fields.Integer(default=10)
|
||||
check_type = fields.Selection(
|
||||
selection=[
|
||||
("check", "Check"),
|
||||
("file", "Upload Document"),
|
||||
],
|
||||
string="Type",
|
||||
default="check",
|
||||
required=True,
|
||||
)
|
||||
description = fields.Html(string="Description", translate=True)
|
||||
template_id = fields.Many2one(
|
||||
comodel_name="dn.audit.check.template",
|
||||
string="Template",
|
||||
ondelete="set null",
|
||||
)
|
||||
cycle_id = fields.Many2one(
|
||||
comodel_name="dn.audit.cycle",
|
||||
string="Cycle",
|
||||
ondelete="set null",
|
||||
)
|
||||
|
||||
result = fields.Selection(
|
||||
selection=[
|
||||
("todo", "To Do"),
|
||||
("done", "Done"),
|
||||
("na", "Not Applicable"),
|
||||
("comment", "Commented"),
|
||||
],
|
||||
string="Result",
|
||||
default="todo",
|
||||
required=True,
|
||||
tracking=True,
|
||||
)
|
||||
comment = fields.Text(string="Comment")
|
||||
|
||||
user_id = fields.Many2one(
|
||||
comodel_name="res.users",
|
||||
string="Reviewed By",
|
||||
default=lambda self: self.env.user,
|
||||
)
|
||||
date_review = fields.Datetime(string="Reviewed On")
|
||||
|
||||
attachment_ids = fields.Many2many(
|
||||
comodel_name="ir.attachment",
|
||||
relation="dn_audit_check_attachment_rel",
|
||||
column1="check_id",
|
||||
column2="attachment_id",
|
||||
string="Documents",
|
||||
)
|
||||
attachment_count = fields.Integer(
|
||||
string="Documents Uploaded", compute="_compute_attachment_count")
|
||||
|
||||
# Surfaced on the check so the reviewer does not have to open the file to
|
||||
# know which period the check belongs to.
|
||||
date_from = fields.Date(related="return_id.date_from")
|
||||
date_to = fields.Date(related="return_id.date_to")
|
||||
|
||||
@api.depends("attachment_ids")
|
||||
def _compute_attachment_count(self):
|
||||
for record in self:
|
||||
record.attachment_count = len(record.attachment_ids)
|
||||
|
||||
@api.onchange("result")
|
||||
def _onchange_result(self):
|
||||
"""Stamp the reviewer and the moment the result changes.
|
||||
|
||||
Done in an onchange rather than in ``write`` so a bulk write from the
|
||||
kanban drag does not overwrite the timestamp with "whenever this was
|
||||
last saved"; the value only trails an explicit result change.
|
||||
"""
|
||||
if self.result != "todo":
|
||||
self.user_id = self.env.user
|
||||
self.date_review = fields.Datetime.now()
|
||||
|
||||
def action_set_result(self, result):
|
||||
self.write({
|
||||
"result": result,
|
||||
"user_id": self.env.user.id,
|
||||
"date_review": fields.Datetime.now(),
|
||||
})
|
||||
|
||||
def action_mark_done(self):
|
||||
self.action_set_result("done")
|
||||
|
||||
def action_mark_na(self):
|
||||
self.action_set_result("na")
|
||||
|
||||
def action_open(self):
|
||||
self.ensure_one()
|
||||
return {
|
||||
"type": "ir.actions.act_window",
|
||||
"name": self.name,
|
||||
"res_model": "dn.audit.check",
|
||||
"res_id": self.id,
|
||||
"view_mode": "form",
|
||||
"target": "current",
|
||||
}
|
||||
348
accountant_cn/models/dn_audit_return.py
Normal file
348
accountant_cn/models/dn_audit_return.py
Normal file
@@ -0,0 +1,348 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Working files: one period of review work.
|
||||
|
||||
Deliberately independent of the enterprise ``account.return`` model. The shape
|
||||
below is driven by what the Review > Audit > Working Files screen has to do,
|
||||
not by any enterprise implementation:
|
||||
|
||||
* a working file covers a date range and belongs to one company;
|
||||
* it is filed under one or more *cycles* (bank, payroll, cut-off, ...), which
|
||||
are just labelled buckets used to slice the review;
|
||||
* it carries *checks* - the things an accountant has to look at - and a
|
||||
check has its own result independent of the file's status;
|
||||
* the file has a review status (ongoing / paused / done) that is *not*
|
||||
derived from the checks, because "I am still working on this" and "the
|
||||
checks pass" are two different facts and an accountant needs to record
|
||||
both.
|
||||
|
||||
The completion rule is the one place the two meet: a file cannot be marked
|
||||
done while checks are still on to-do.
|
||||
"""
|
||||
|
||||
from odoo import api, fields, models, _
|
||||
from odoo.exceptions import UserError
|
||||
|
||||
|
||||
class DnAuditCycle(models.Model):
|
||||
"""A labelled bucket a working file can be filed under.
|
||||
|
||||
Cycles exist so a review can be split the way an audit is actually split:
|
||||
by area rather than by account. They carry nothing but a name and a code,
|
||||
because anything richer would be knowledge the module cannot verify.
|
||||
"""
|
||||
|
||||
_name = "dn.audit.cycle"
|
||||
_description = "Audit Cycle"
|
||||
_order = "sequence, name, id"
|
||||
|
||||
name = fields.Char(string="Name", required=True, translate=True)
|
||||
code = fields.Char(string="Code", required=True)
|
||||
sequence = fields.Integer(default=10)
|
||||
active = fields.Boolean(default=True)
|
||||
description = fields.Text(string="Description", translate=True)
|
||||
|
||||
_code_uniq = models.Constraint(
|
||||
"unique (code)",
|
||||
"Audit cycle codes must be unique.",
|
||||
)
|
||||
|
||||
|
||||
class DnAuditCheckTemplate(models.Model):
|
||||
"""A reusable check definition.
|
||||
|
||||
A month-end close runs the same checks every month. Keeping them as
|
||||
templates means the checks are written once and stamped onto each new
|
||||
working file, instead of being retyped (and quietly dropped) every period.
|
||||
"""
|
||||
|
||||
_name = "dn.audit.check.template"
|
||||
_description = "Audit Check Template"
|
||||
_order = "cycle_id, sequence, name, id"
|
||||
|
||||
name = fields.Char(string="Name", required=True, translate=True)
|
||||
sequence = fields.Integer(default=10)
|
||||
check_type = fields.Selection(
|
||||
selection=[
|
||||
("check", "Check"),
|
||||
("file", "Upload Document"),
|
||||
],
|
||||
string="Type",
|
||||
default="check",
|
||||
required=True,
|
||||
help="A check is something to be reviewed and cleared; a document is "
|
||||
"an attachment that has to be provided.",
|
||||
)
|
||||
cycle_id = fields.Many2one(
|
||||
comodel_name="dn.audit.cycle",
|
||||
string="Cycle",
|
||||
ondelete="set null",
|
||||
)
|
||||
description = fields.Html(string="Instructions", translate=True)
|
||||
active = fields.Boolean(default=True)
|
||||
|
||||
def _prepare_check_values(self):
|
||||
"""Values to stamp onto a working file's checks.
|
||||
|
||||
Kept on the template so the copy lives in one place: a change to what a
|
||||
check means should not have to be made in the template *and* in every
|
||||
place that instantiates it.
|
||||
"""
|
||||
self.ensure_one()
|
||||
return {
|
||||
"name": self.name,
|
||||
"check_type": self.check_type,
|
||||
"cycle_id": self.cycle_id.id,
|
||||
"description": self.description,
|
||||
"template_id": self.id,
|
||||
}
|
||||
|
||||
|
||||
class DnAuditReturn(models.Model):
|
||||
"""One period of review work (a "working file")."""
|
||||
|
||||
_name = "dn.audit.return"
|
||||
_description = "Audit Working File"
|
||||
_inherit = ["mail.thread", "mail.activity.mixin"]
|
||||
_order = "is_completed, date_deadline, date_from desc, id desc"
|
||||
|
||||
name = fields.Char(
|
||||
string="Name",
|
||||
required=True,
|
||||
translate=True,
|
||||
tracking=True,
|
||||
help="Usually the period, e.g. \"2026-10 Close\".",
|
||||
)
|
||||
active = fields.Boolean(default=True, tracking=True)
|
||||
company_id = fields.Many2one(
|
||||
comodel_name="res.company",
|
||||
string="Company",
|
||||
required=True,
|
||||
default=lambda self: self.env.company,
|
||||
index=True,
|
||||
)
|
||||
currency_id = fields.Many2one(
|
||||
related="company_id.currency_id",
|
||||
string="Currency",
|
||||
readonly=True,
|
||||
)
|
||||
|
||||
date_from = fields.Date(string="Start Date", required=True, tracking=True)
|
||||
date_to = fields.Date(string="End Date", required=True, tracking=True)
|
||||
date_deadline = fields.Date(string="Deadline", tracking=True)
|
||||
|
||||
cycle_ids = fields.Many2many(
|
||||
comodel_name="dn.audit.cycle",
|
||||
relation="dn_audit_return_cycle_rel",
|
||||
column1="return_id",
|
||||
column2="cycle_id",
|
||||
string="Cycles",
|
||||
tracking=True,
|
||||
)
|
||||
|
||||
# ---- review status -------------------------------------------------
|
||||
# Not derived from the checks on purpose: "paused" is a statement about the
|
||||
# reviewer's intent, not about the data. A file whose checks all pass can
|
||||
# still be paused because the reviewer is waiting for an explanation.
|
||||
review_state = fields.Selection(
|
||||
selection=[
|
||||
("ongoing", "Ongoing"),
|
||||
("paused", "Paused"),
|
||||
("done", "Done"),
|
||||
],
|
||||
string="Review Status",
|
||||
default="ongoing",
|
||||
required=True,
|
||||
tracking=True,
|
||||
)
|
||||
is_completed = fields.Boolean(
|
||||
string="Completed",
|
||||
default=False,
|
||||
tracking=True,
|
||||
help="Set when the period has been signed off. Completing a file is "
|
||||
"what removes it from the default Ongoing filter.",
|
||||
)
|
||||
notes = fields.Html(string="Notes", translate=True)
|
||||
|
||||
# ---- checks --------------------------------------------------------
|
||||
check_ids = fields.One2many(
|
||||
comodel_name="dn.audit.check",
|
||||
inverse_name="return_id",
|
||||
string="Checks",
|
||||
)
|
||||
check_count = fields.Integer(
|
||||
string="Checks Total", compute="_compute_check_counts")
|
||||
resolved_check_count = fields.Integer(
|
||||
string="Checks Passed", compute="_compute_check_counts")
|
||||
unresolved_check_count = fields.Integer(
|
||||
string="Issues", compute="_compute_check_counts")
|
||||
progress = fields.Float(
|
||||
string="Progress (%)",
|
||||
compute="_compute_check_counts",
|
||||
help="Share of the checks that are no longer on to-do.",
|
||||
)
|
||||
|
||||
# ---- helpers used by the kanban card -------------------------------
|
||||
days_to_deadline = fields.Integer(
|
||||
string="Days to Deadline", compute="_compute_days_to_deadline")
|
||||
is_late = fields.Boolean(string="Late", compute="_compute_days_to_deadline")
|
||||
|
||||
_date_range_check = models.Constraint(
|
||||
"CHECK (date_to >= date_from)",
|
||||
"The end date must not be before the start date.",
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Compute
|
||||
# ------------------------------------------------------------------
|
||||
@api.depends("check_ids", "check_ids.result")
|
||||
def _compute_check_counts(self):
|
||||
for record in self:
|
||||
total = len(record.check_ids)
|
||||
# `na` counts as resolved: a check that does not apply to this
|
||||
# period has been dealt with, and leaving it in the "issues" count
|
||||
# would keep the file permanently red.
|
||||
resolved = len(record.check_ids.filtered(
|
||||
lambda c: c.result in ("done", "na")))
|
||||
record.check_count = total
|
||||
record.resolved_check_count = resolved
|
||||
record.unresolved_check_count = total - resolved
|
||||
record.progress = (resolved / total * 100.0) if total else 0.0
|
||||
|
||||
@api.depends("date_deadline", "is_completed")
|
||||
def _compute_days_to_deadline(self):
|
||||
today = fields.Date.context_today(self)
|
||||
for record in self:
|
||||
if not record.date_deadline:
|
||||
record.days_to_deadline = 0
|
||||
record.is_late = False
|
||||
continue
|
||||
delta = (record.date_deadline - today).days
|
||||
record.days_to_deadline = delta
|
||||
record.is_late = bool(delta < 0 and not record.is_completed)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Constraints / onchange
|
||||
# ------------------------------------------------------------------
|
||||
@api.constrains("date_from", "date_to")
|
||||
def _check_dates(self):
|
||||
for record in self:
|
||||
if record.date_from and record.date_to and record.date_to < record.date_from:
|
||||
raise UserError(_(
|
||||
"The end date (%(end)s) cannot be before the start date "
|
||||
"(%(start)s).",
|
||||
end=record.date_to,
|
||||
start=record.date_from,
|
||||
))
|
||||
|
||||
@api.onchange("date_from")
|
||||
def _onchange_date_from(self):
|
||||
# Filling the start date suggests a name, so a new file does not have to
|
||||
# be named by hand and end up as "New" in the kanban.
|
||||
if self.date_from and not self.name:
|
||||
self.name = _("%(period)s Close", period=self.date_from.strftime("%Y-%m"))
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Actions
|
||||
# ------------------------------------------------------------------
|
||||
def action_pause(self):
|
||||
self.write({"review_state": "paused"})
|
||||
|
||||
def action_resume(self):
|
||||
self.write({"review_state": "ongoing"})
|
||||
|
||||
def action_mark_done(self):
|
||||
"""Sign the period off.
|
||||
|
||||
Refuses while checks are unresolved. This is the only place the review
|
||||
status and the check results are allowed to constrain each other, and
|
||||
it is a guard rather than a computation: an accountant *can* still set
|
||||
a check to n/a to get past a check that genuinely does not apply.
|
||||
"""
|
||||
for record in self:
|
||||
blocking = record.check_ids.filtered(lambda c: c.result == "todo")
|
||||
if blocking:
|
||||
raise UserError(_(
|
||||
"%(name)s still has %(count)s unresolved check(s). "
|
||||
"Resolve them, or mark them as not applicable, before "
|
||||
"completing the file.",
|
||||
name=record.name,
|
||||
count=len(blocking),
|
||||
))
|
||||
self.write({"review_state": "done", "is_completed": True})
|
||||
|
||||
def action_reset_to_ongoing(self):
|
||||
self.write({"review_state": "ongoing", "is_completed": False})
|
||||
|
||||
def action_load_templates(self):
|
||||
"""Stamp the active templates onto this file.
|
||||
|
||||
Only templates whose cycle is already on the file are added when the
|
||||
file has cycles; a file with no cycles gets every active template. This
|
||||
keeps "I filed this under Bank" from silently pulling in the payroll
|
||||
checks as well.
|
||||
|
||||
Loading twice is a no-op rather than a duplicate: a template already
|
||||
present on the file is skipped by ``template_id``. The button therefore
|
||||
stays safe to press again after adding a cycle.
|
||||
|
||||
A button that can legitimately do nothing has to say so - otherwise the
|
||||
reviewer presses it, sees no change, and concludes the feature is
|
||||
broken (or worse, that the checks were already there).
|
||||
"""
|
||||
Check = self.env["dn.audit.check"]
|
||||
added = 0
|
||||
for record in self:
|
||||
templates = self.env["dn.audit.check.template"].search([])
|
||||
if record.cycle_ids:
|
||||
templates = templates.filtered(
|
||||
lambda t: not t.cycle_id or t.cycle_id in record.cycle_ids)
|
||||
existing = record.check_ids.mapped("template_id")
|
||||
values = []
|
||||
for template in templates - existing:
|
||||
vals = template._prepare_check_values()
|
||||
vals["return_id"] = record.id
|
||||
values.append(vals)
|
||||
if values:
|
||||
Check.create(values)
|
||||
added += len(values)
|
||||
|
||||
if not added:
|
||||
return self._notify(_(
|
||||
"Nothing to load: every check template matching this file's "
|
||||
"cycles has already been added. Add more templates, or put the "
|
||||
"file under another cycle first.",
|
||||
))
|
||||
return self._notify(_(
|
||||
"%(count)s check(s) added to the working file.",
|
||||
count=added,
|
||||
))
|
||||
|
||||
def _notify(self, message):
|
||||
"""A ``display_notification`` action carrying ``message``.
|
||||
|
||||
The button has to answer. Loading templates either adds checks (the
|
||||
form has to re-read them, hence ``soft_reload``) or adds nothing
|
||||
(nothing changes, so only the message is needed) - and in both cases
|
||||
silence reads as a broken button.
|
||||
"""
|
||||
return {
|
||||
"type": "ir.actions.client",
|
||||
"tag": "display_notification",
|
||||
"params": {
|
||||
"type": "info",
|
||||
"message": message,
|
||||
"sticky": False,
|
||||
"next": {"type": "ir.actions.client", "tag": "soft_reload"},
|
||||
},
|
||||
}
|
||||
|
||||
def action_view_checks(self):
|
||||
self.ensure_one()
|
||||
return {
|
||||
"type": "ir.actions.act_window",
|
||||
"name": _("Checks"),
|
||||
"res_model": "dn.audit.check",
|
||||
"view_mode": "kanban,list,form",
|
||||
"domain": [("return_id", "=", self.id)],
|
||||
"context": {"default_return_id": self.id},
|
||||
}
|
||||
415
accountant_cn/models/dn_bank_rec.py
Normal file
415
accountant_cn/models/dn_bank_rec.py
Normal file
@@ -0,0 +1,415 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""DN Bank Reconciliation — statement line matching workspace.
|
||||
|
||||
Independent implementation for Odoo 20 Community, LGPL-3. It reuses only
|
||||
community APIs from ``account`` (``account.bank.statement.line`` and
|
||||
``account.reconcile.model``); no enterprise file is used or derived.
|
||||
|
||||
The workflow implemented here mirrors what an accountant expects:
|
||||
|
||||
1. Pick a bank journal. Unreconciled statement lines are listed.
|
||||
2. For the selected line the engine proposes candidate journal items,
|
||||
ranked by amount, partner and label similarity.
|
||||
3. The user either
|
||||
* matches one or more candidates (partial or full), or
|
||||
* creates a new entry on a chosen counterpart account (with tax).
|
||||
4. The result is written as a balanced journal entry and reconciled.
|
||||
"""
|
||||
import logging
|
||||
import re
|
||||
from difflib import SequenceMatcher
|
||||
|
||||
from odoo import _, api, fields, models
|
||||
from odoo.exceptions import UserError, ValidationError
|
||||
from odoo.tools import float_compare, float_is_zero
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
# How strongly each signal weighs when suggesting a candidate.
|
||||
WEIGHT_AMOUNT_EXACT = 100
|
||||
WEIGHT_AMOUNT_CLOSE = 40
|
||||
WEIGHT_PARTNER = 60
|
||||
WEIGHT_LABEL = 30
|
||||
MAX_SUGGESTIONS = 20
|
||||
|
||||
|
||||
def _normalise(text):
|
||||
"""Lowercase, strip digits and punctuation, so labels can be compared."""
|
||||
text = (text or "").lower()
|
||||
text = re.sub(r"[^a-z0-9\u4e00-\u9fff ]+", " ", text)
|
||||
return " ".join(text.split())
|
||||
|
||||
|
||||
def _similarity(left, right):
|
||||
left, right = _normalise(left), _normalise(right)
|
||||
if not left or not right:
|
||||
return 0.0
|
||||
return SequenceMatcher(None, left, right).ratio()
|
||||
|
||||
|
||||
class DnBankRecWizard(models.TransientModel):
|
||||
"""Holds the state of one reconciliation session for a statement line."""
|
||||
|
||||
_name = "dn.bank.rec.wizard"
|
||||
_description = "DN Bank Reconciliation Session"
|
||||
|
||||
statement_line_id = fields.Many2one(
|
||||
"account.bank.statement.line", required=True, ondelete="cascade",
|
||||
string="Bank Transaction",
|
||||
)
|
||||
journal_id = fields.Many2one(related="statement_line_id.journal_id", string="Journal")
|
||||
company_id = fields.Many2one(related="statement_line_id.company_id", string="Company")
|
||||
currency_id = fields.Many2one(related="statement_line_id.currency_id", string="Currency")
|
||||
amount = fields.Monetary(related="statement_line_id.amount", string="Statement Amount")
|
||||
partner_id = fields.Many2one(related="statement_line_id.partner_id", string="Partner")
|
||||
payment_ref = fields.Char(related="statement_line_id.payment_ref", string="Label")
|
||||
date = fields.Date(related="statement_line_id.date", string="Date")
|
||||
|
||||
candidate_ids = fields.One2many(
|
||||
"dn.bank.rec.candidate", "wizard_id", string="Candidates",
|
||||
)
|
||||
selected_aml_ids = fields.Many2many(
|
||||
"account.move.line", string="Selected Journal Items",
|
||||
help="Journal items the user chose to reconcile against the statement line.",
|
||||
)
|
||||
remaining_amount = fields.Monetary(
|
||||
compute="_compute_remaining", string="Amount Left to Match",
|
||||
)
|
||||
suggestion_count = fields.Integer(compute="_compute_remaining",
|
||||
string="Suggestions")
|
||||
|
||||
# Manual entry fallback
|
||||
counterpart_account_id = fields.Many2one(
|
||||
"account.account", string="Counterpart Account",
|
||||
domain="[('account_type', 'not in', ['asset_receivable', 'liability_payable', 'off_balance']), ('company_ids', 'in', company_id)]",
|
||||
)
|
||||
manual_amount = fields.Monetary(string="Amount")
|
||||
# These two mirror statement_line's `payment_ref` / `partner_id` but are
|
||||
# editable, so they must not reuse the same label: Odoo warns on duplicate
|
||||
# field labels and the user cannot tell the two apart in the UI.
|
||||
manual_label = fields.Char(string="Counterpart Label")
|
||||
manual_partner_id = fields.Many2one("res.partner", string="Counterpart Partner")
|
||||
manual_tax_id = fields.Many2one(
|
||||
"account.tax", string="Tax",
|
||||
domain="[('type_tax_use', 'in', ['sale', 'purchase']), ('company_id', '=', company_id)]",
|
||||
)
|
||||
|
||||
@api.model
|
||||
def create_from_statement_line(self, statement_line_id):
|
||||
"""Open a reconciliation session for the given statement line.
|
||||
|
||||
Called from the statement line's button; the caller always receives the
|
||||
wizard record so it can act on the suggestions.
|
||||
"""
|
||||
wizard = self.create({"statement_line_id": statement_line_id})
|
||||
wizard._refresh_candidates()
|
||||
return wizard
|
||||
|
||||
# ------------------------------------------------------------ compute
|
||||
@api.depends("selected_aml_ids", "statement_line_id")
|
||||
def _compute_remaining(self):
|
||||
for wizard in self:
|
||||
total = 0.0
|
||||
for aml in wizard.selected_aml_ids:
|
||||
total += aml.balance
|
||||
wizard.remaining_amount = wizard.amount + total
|
||||
wizard.suggestion_count = len(wizard.candidate_ids)
|
||||
|
||||
# ----------------------------------------------------------- candidates
|
||||
def _refresh_candidates(self):
|
||||
"""Rebuild the ranked candidate list for the statement line."""
|
||||
self.ensure_one()
|
||||
self.candidate_ids.unlink()
|
||||
candidates = self._collect_candidates()
|
||||
vals_list = []
|
||||
for aml, score, reason in candidates[:MAX_SUGGESTIONS]:
|
||||
vals_list.append({
|
||||
"wizard_id": self.id,
|
||||
"move_line_id": aml.id,
|
||||
"score": score,
|
||||
"reason": reason,
|
||||
})
|
||||
if vals_list:
|
||||
self.env["dn.bank.rec.candidate"].create(vals_list)
|
||||
return True
|
||||
|
||||
def action_refresh_candidates(self):
|
||||
"""Recompute suggestions, e.g. after new entries were posted."""
|
||||
self.ensure_one()
|
||||
self._refresh_candidates()
|
||||
return {
|
||||
"type": "ir.actions.client",
|
||||
"tag": "display_notification",
|
||||
"params": {
|
||||
"title": _("Candidates"),
|
||||
"message": _("%s candidates recomputed.", len(self.candidate_ids)),
|
||||
"type": "success",
|
||||
"sticky": False,
|
||||
},
|
||||
}
|
||||
|
||||
def _collect_candidates(self):
|
||||
"""Score unreconciled journal items against the statement line."""
|
||||
self.ensure_one()
|
||||
st_line = self.statement_line_id
|
||||
domain = st_line._get_default_amls_matching_domain(allow_draft=False)
|
||||
domain += [
|
||||
("company_id", "=", st_line.company_id.id),
|
||||
("date", "<=", st_line.date or fields.Date.context_today(self)),
|
||||
]
|
||||
amls = self.env["account.move.line"].sudo().search(domain, limit=2000)
|
||||
|
||||
scored = []
|
||||
line_amount = abs(st_line.amount or 0.0)
|
||||
company_currency = st_line.company_id.currency_id
|
||||
for aml in amls:
|
||||
score = 0
|
||||
reasons = []
|
||||
|
||||
aml_amount = abs(aml.amount_residual or aml.balance or 0.0)
|
||||
if float_is_zero(aml_amount - line_amount, precision_rounding=0.01):
|
||||
score += WEIGHT_AMOUNT_EXACT
|
||||
reasons.append(_("same amount"))
|
||||
elif line_amount and abs(aml_amount - line_amount) / line_amount < 0.02:
|
||||
score += WEIGHT_AMOUNT_CLOSE
|
||||
reasons.append(_("close amount"))
|
||||
|
||||
if st_line.partner_id and aml.partner_id == st_line.partner_id:
|
||||
score += WEIGHT_PARTNER
|
||||
reasons.append(_("same partner"))
|
||||
|
||||
label_score = _similarity(st_line.payment_ref, aml.name)
|
||||
if label_score > 0.5:
|
||||
score += int(WEIGHT_LABEL * label_score)
|
||||
reasons.append(_("similar label"))
|
||||
|
||||
# A deposit (+amount) is debited to the bank, so its counterpart
|
||||
# carries a credit balance, i.e. a negative one. A withdrawal is
|
||||
# the mirror image. This is what keeps a 4,000 receipt from
|
||||
# matching a 4,000 payment.
|
||||
if st_line.amount and aml.balance:
|
||||
opposite_side = (st_line.amount > 0) == (aml.balance < 0)
|
||||
if opposite_side:
|
||||
score += 10
|
||||
else:
|
||||
score -= 20
|
||||
|
||||
if score > 0:
|
||||
scored.append((aml, score, " / ".join(reasons) or _("automatic match")))
|
||||
|
||||
scored.sort(key=lambda item: item[1], reverse=True)
|
||||
return scored
|
||||
|
||||
# -------------------------------------------------------------- actions
|
||||
def action_match_selected(self):
|
||||
"""Reconcile the statement line against the selected journal items.
|
||||
|
||||
A statement line's own entry holds a liquidity item (on the bank
|
||||
account) and a suspense item. Those two can never be reconciled against
|
||||
a receivable: reconciliation only works between items of the *same*
|
||||
account. So the suspense item is first re-pointed at the account of the
|
||||
selected items, which turns it into a genuine counterpart on, say,
|
||||
receivables. Only then are the two sides reconciled.
|
||||
"""
|
||||
self.ensure_one()
|
||||
if not self.selected_aml_ids:
|
||||
raise UserError(_("Select at least one journal item to match."))
|
||||
|
||||
st_line = self.statement_line_id
|
||||
accounts = self.selected_aml_ids.mapped("account_id")
|
||||
if len(accounts) > 1:
|
||||
raise UserError(
|
||||
_("The selected items belong to different accounts (%s). "
|
||||
"Only items of one account can be reconciled together.",
|
||||
", ".join(accounts.mapped("display_name")))
|
||||
)
|
||||
target_account = accounts[:1]
|
||||
|
||||
_liquidity_lines, suspense_lines, _other = st_line._seek_for_lines()
|
||||
counterpart = suspense_lines[:1]
|
||||
if not counterpart:
|
||||
raise UserError(_("This bank transaction has no journal entry yet, "
|
||||
"so it cannot be reconciled."))
|
||||
|
||||
counterpart.account_id = target_account
|
||||
if st_line.partner_id and not counterpart.partner_id:
|
||||
counterpart.partner_id = st_line.partner_id
|
||||
|
||||
(counterpart | self.selected_aml_ids).reconcile()
|
||||
st_line.modified(['is_reconciled', 'amount_residual'])
|
||||
st_line.invalidate_recordset(['is_reconciled', 'amount_residual'])
|
||||
return {"type": "ir.actions.act_window_close"}
|
||||
|
||||
def action_create_counterpart(self):
|
||||
"""Create a new journal item on the chosen account and reconcile."""
|
||||
self.ensure_one()
|
||||
st_line = self.statement_line_id
|
||||
if not self.counterpart_account_id:
|
||||
raise UserError(_("Choose a counterpart account."))
|
||||
if not self.manual_amount:
|
||||
self.manual_amount = st_line.amount
|
||||
|
||||
move = st_line.move_id
|
||||
if not move:
|
||||
raise UserError(_("This bank transaction has no linked journal entry."))
|
||||
|
||||
vals = {
|
||||
"move_id": move.id,
|
||||
"account_id": self.counterpart_account_id.id,
|
||||
"name": self.manual_label or st_line.payment_ref or _("Bank reconciliation"),
|
||||
"partner_id": (self.manual_partner_id or st_line.partner_id).id,
|
||||
"balance": -self.manual_amount,
|
||||
"currency_id": st_line.currency_id.id,
|
||||
"company_id": st_line.company_id.id,
|
||||
}
|
||||
if self.manual_tax_id:
|
||||
vals["tax_ids"] = [(6, 0, self.manual_tax_id.ids)]
|
||||
|
||||
new_line = self.env["account.move.line"].create(vals)
|
||||
move.action_post()
|
||||
|
||||
liquidity_lines, suspense_lines, _other = st_line._seek_for_lines()
|
||||
to_reconcile = liquidity_lines[:1] | new_line
|
||||
if not float_is_zero(
|
||||
st_line.amount + new_line.balance,
|
||||
precision_rounding=st_line.currency_id.rounding,
|
||||
) and suspense_lines:
|
||||
to_reconcile |= suspense_lines[:1]
|
||||
to_reconcile.reconcile()
|
||||
st_line.modified(['is_reconciled', 'amount_residual'])
|
||||
st_line.invalidate_recordset(['is_reconciled', 'amount_residual'])
|
||||
return {"type": "ir.actions.act_window_close"}
|
||||
|
||||
def action_apply_rules(self):
|
||||
"""Run the configured reconciliation models over open statement lines."""
|
||||
self.ensure_one()
|
||||
models_to_run = self.env["account.reconcile.model"].search([
|
||||
("company_id", "=", self.company_id.id),
|
||||
("rule_type", "=", "writeoff_suggestion"),
|
||||
])
|
||||
applied = 0
|
||||
open_lines = self.env["account.bank.statement.line"].search([
|
||||
("journal_id", "=", self.journal_id.id),
|
||||
("is_reconciled", "=", False),
|
||||
])
|
||||
for st_line in open_lines:
|
||||
for rule in models_to_run:
|
||||
if self._rule_matches(rule, st_line):
|
||||
self._apply_rule(rule, st_line)
|
||||
applied += 1
|
||||
break
|
||||
return {
|
||||
"type": "ir.actions.client",
|
||||
"tag": "display_notification",
|
||||
"params": {
|
||||
"title": _("Reconciliation Rules"),
|
||||
"message": _("%s bank transactions processed.", applied),
|
||||
"type": "success",
|
||||
},
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _rule_matches(rule, st_line):
|
||||
if rule.match_journal_ids and st_line.journal_id not in rule.match_journal_ids:
|
||||
return False
|
||||
amount = abs(st_line.amount or 0.0)
|
||||
if rule.match_amount == "lower" and amount >= rule.match_amount_max:
|
||||
return False
|
||||
if rule.match_amount == "greater" and amount <= rule.match_amount_min:
|
||||
return False
|
||||
if rule.match_amount == "between":
|
||||
if not (rule.match_amount_min <= amount <= rule.match_amount_max):
|
||||
return False
|
||||
if rule.match_label == "contains" and rule.match_label_param:
|
||||
if rule.match_label_param.lower() not in (st_line.payment_ref or "").lower():
|
||||
return False
|
||||
if rule.match_partner_ids and st_line.partner_id not in rule.match_partner_ids:
|
||||
return False
|
||||
return True
|
||||
|
||||
def _apply_rule(self, rule, st_line):
|
||||
"""Write off the statement line following a reconciliation model."""
|
||||
account = rule.line_ids[:1].account_id
|
||||
if not account:
|
||||
return False
|
||||
liquidity_lines, suspense_lines, _other = st_line._seek_for_lines()
|
||||
liquidity = liquidity_lines[:1]
|
||||
if not liquidity:
|
||||
return False
|
||||
move = st_line.move_id
|
||||
new_line = self.env["account.move.line"].create({
|
||||
"move_id": move.id,
|
||||
"account_id": account.id,
|
||||
"name": rule.line_ids[:1].label or st_line.payment_ref,
|
||||
"partner_id": st_line.partner_id.id,
|
||||
"balance": -st_line.amount,
|
||||
"currency_id": st_line.currency_id.id,
|
||||
"company_id": st_line.company_id.id,
|
||||
})
|
||||
move.action_post()
|
||||
(liquidity | new_line).reconcile()
|
||||
st_line.modified(['is_reconciled', 'amount_residual'])
|
||||
st_line.invalidate_recordset(['is_reconciled', 'amount_residual'])
|
||||
return True
|
||||
|
||||
def action_unreconcile(self):
|
||||
"""Undo the reconciliation of the statement line."""
|
||||
self.ensure_one()
|
||||
return self.statement_line_id.action_undo_reconciliation()
|
||||
|
||||
|
||||
class DnBankRecCandidate(models.TransientModel):
|
||||
"""One scored suggestion shown in the matching panel."""
|
||||
|
||||
_name = "dn.bank.rec.candidate"
|
||||
_description = "DN Bank Reconciliation Candidate"
|
||||
_order = "score desc, id"
|
||||
|
||||
wizard_id = fields.Many2one(
|
||||
"dn.bank.rec.wizard", required=True, ondelete="cascade",
|
||||
)
|
||||
move_line_id = fields.Many2one("account.move.line", required=True,
|
||||
string="Journal Item")
|
||||
score = fields.Integer(string="Score", default=0)
|
||||
reason = fields.Char(string="Why")
|
||||
selected = fields.Boolean(string="Selected", default=False)
|
||||
|
||||
date = fields.Date(related="move_line_id.date")
|
||||
move_name = fields.Char(related="move_line_id.move_name", string="Entry")
|
||||
label = fields.Text(related="move_line_id.name", string="Label")
|
||||
partner_id = fields.Many2one(related="move_line_id.partner_id", string="Partner")
|
||||
account_id = fields.Many2one(related="move_line_id.account_id", string="Account")
|
||||
balance = fields.Monetary(related="move_line_id.balance", string="Balance")
|
||||
amount_residual = fields.Monetary(related="move_line_id.amount_residual",
|
||||
string="Amount Due")
|
||||
currency_id = fields.Many2one(related="move_line_id.currency_id")
|
||||
|
||||
def action_toggle(self):
|
||||
self.ensure_one()
|
||||
self.selected = not self.selected
|
||||
wizard = self.wizard_id
|
||||
if self.selected:
|
||||
wizard.selected_aml_ids = [(4, self.move_line_id.id)]
|
||||
else:
|
||||
wizard.selected_aml_ids = [(3, self.move_line_id.id)]
|
||||
return True
|
||||
|
||||
|
||||
class AccountBankStatementLine(models.Model):
|
||||
"""Add a reconciliation entry point on the standard statement line."""
|
||||
|
||||
_inherit = "account.bank.statement.line"
|
||||
|
||||
def action_open_dn_reconciliation(self):
|
||||
"""Open the DN matching workspace for this statement line."""
|
||||
self.ensure_one()
|
||||
wizard = self.env["dn.bank.rec.wizard"].create_from_statement_line(self.id)
|
||||
return {
|
||||
"type": "ir.actions.act_window",
|
||||
"name": _("Bank reconciliation: %s", self.payment_ref or self.move_id.name or ""),
|
||||
"res_model": "dn.bank.rec.wizard",
|
||||
"res_id": wizard.id,
|
||||
"view_mode": "form",
|
||||
"target": "current",
|
||||
"context": {"create": False},
|
||||
}
|
||||
1051
accountant_cn/models/dn_fiscal_year.py
Normal file
1051
accountant_cn/models/dn_fiscal_year.py
Normal file
File diff suppressed because it is too large
Load Diff
1203
accountant_cn/models/dn_fr.py
Normal file
1203
accountant_cn/models/dn_fr.py
Normal file
File diff suppressed because it is too large
Load Diff
688
accountant_cn/models/dn_loan.py
Normal file
688
accountant_cn/models/dn_loan.py
Normal file
@@ -0,0 +1,688 @@
|
||||
from dateutil.relativedelta import relativedelta
|
||||
|
||||
from odoo import _, api, Command, fields, models
|
||||
from odoo.exceptions import UserError, ValidationError
|
||||
from odoo.tools import float_compare, format_date
|
||||
|
||||
|
||||
class DnLoan(models.Model):
|
||||
_name = 'dn.loan'
|
||||
_description = 'Loan'
|
||||
_inherit = ['mail.thread', 'mail.activity.mixin', 'analytic.mixin']
|
||||
_order = 'date desc, id desc'
|
||||
_check_company_auto = True
|
||||
|
||||
# -- identity --------------------------------------------------------
|
||||
|
||||
name = fields.Char(
|
||||
string='Name', required=True, tracking=True, index='trigram',
|
||||
help="Reference of the loan, usually the contract number.",
|
||||
)
|
||||
company_id = fields.Many2one(
|
||||
'res.company', string='Company', required=True, index=True,
|
||||
default=lambda self: self.env.company,
|
||||
)
|
||||
currency_id = fields.Many2one(related='company_id.currency_id', store=True)
|
||||
active = fields.Boolean(default=True)
|
||||
state = fields.Selection(
|
||||
selection=[
|
||||
('draft', 'Draft'),
|
||||
('running', 'Running'),
|
||||
('closed', 'Closed'),
|
||||
('cancelled', 'Cancelled'),
|
||||
],
|
||||
string='Status', default='draft', required=True, tracking=True,
|
||||
copy=False,
|
||||
)
|
||||
|
||||
# -- terms -----------------------------------------------------------
|
||||
|
||||
date = fields.Date(
|
||||
string='Loan Date', index='btree_not_null', tracking=True,
|
||||
help="Date the money was borrowed. Interest starts accruing on this day.",
|
||||
)
|
||||
amount_borrowed = fields.Monetary(string='Amount Borrowed', tracking=True)
|
||||
interest = fields.Monetary(
|
||||
string='Interest', tracking=True,
|
||||
help="Total interest over the whole schedule. Filled in when the "
|
||||
"schedule is computed, and checked against it before confirming.",
|
||||
)
|
||||
duration = fields.Integer(
|
||||
string='Duration',
|
||||
help="Number of installments. Filled in when the schedule is computed.",
|
||||
)
|
||||
method = fields.Selection(
|
||||
selection=[
|
||||
('annuity', 'Annuity'),
|
||||
('linear', 'Linear'),
|
||||
('interest_only', 'Interest Only'),
|
||||
],
|
||||
string='Repayment Method', default='annuity', required=True,
|
||||
help="Annuity: every installment pays the same total. "
|
||||
"Linear: every installment repays the same principal. "
|
||||
"Interest Only: only interest is paid until a balloon payment.",
|
||||
)
|
||||
skip_until_date = fields.Date(
|
||||
string='Skip until',
|
||||
help="Installments due on or before this date are not posted. Use it "
|
||||
"when the first payments were already booked by hand before the "
|
||||
"loan was recorded here.",
|
||||
)
|
||||
|
||||
# -- accounts and journal --------------------------------------------
|
||||
|
||||
long_term_account_id = fields.Many2one(
|
||||
'account.account', string='Long Term Account', tracking=True,
|
||||
check_company=True,
|
||||
help="Liability account for the part of the principal due after "
|
||||
"twelve months.",
|
||||
)
|
||||
short_term_account_id = fields.Many2one(
|
||||
'account.account', string='Short Term Account', tracking=True,
|
||||
check_company=True,
|
||||
help="Liability account for the part of the principal due within "
|
||||
"twelve months. Payments are booked against this account.",
|
||||
)
|
||||
expense_account_id = fields.Many2one(
|
||||
'account.account', string='Expense Account', tracking=True,
|
||||
check_company=True,
|
||||
domain="[('account_type', 'in', ('expense', 'expense_depreciation', "
|
||||
"'expense_other'))]",
|
||||
help="Account the interest is charged to.",
|
||||
)
|
||||
journal_id = fields.Many2one(
|
||||
'account.journal', string='Journal', tracking=True, check_company=True,
|
||||
domain="[('type', '=', 'general')]",
|
||||
)
|
||||
loan_properties = fields.Properties(
|
||||
string='Properties', definition='journal_id.loan_properties_definition',
|
||||
)
|
||||
|
||||
line_ids = fields.One2many(
|
||||
'dn.loan.line', 'loan_id', string='Amortization Schedule',
|
||||
copy=True,
|
||||
)
|
||||
move_ids = fields.One2many(
|
||||
'account.move', 'dn_loan_id', string='Generated Entries', readonly=True,
|
||||
)
|
||||
|
||||
# -- computed --------------------------------------------------------
|
||||
|
||||
display_name = fields.Char(
|
||||
string='Loan name', compute='_compute_display_name', store=True,
|
||||
# Stored because the pivot view groups by it, and a non-stored field
|
||||
# cannot be used as a group-by.
|
||||
)
|
||||
start_date = fields.Date(compute='_compute_start_end_date', store=True)
|
||||
end_date = fields.Date(compute='_compute_start_end_date', store=True)
|
||||
is_wrong_date = fields.Boolean(compute='_compute_is_wrong_date')
|
||||
amount_borrowed_difference = fields.Monetary(
|
||||
compute='_compute_differences',
|
||||
help="Amount borrowed minus the sum of the principals in the schedule.",
|
||||
)
|
||||
interest_difference = fields.Monetary(
|
||||
compute='_compute_differences',
|
||||
help="Interest minus the sum of the interest in the schedule.",
|
||||
)
|
||||
duration_difference = fields.Integer(compute='_compute_differences')
|
||||
outstanding_balance = fields.Monetary(
|
||||
string='Outstanding Balance', compute='_compute_outstanding_balance',
|
||||
help="Principal still owed, according to the entries actually posted.",
|
||||
)
|
||||
nb_posted_entries = fields.Integer(compute='_compute_nb_posted_entries')
|
||||
count_lines = fields.Integer(compute='_compute_count_lines')
|
||||
|
||||
# -- defaults --------------------------------------------------------
|
||||
|
||||
@api.model
|
||||
def default_get(self, field_names):
|
||||
"""Copy the accounts and journal from the previous loan.
|
||||
|
||||
A company borrows repeatedly, and every loan uses the same three
|
||||
accounts. Asking for them again on each record is the kind of friction
|
||||
that makes people stop using the feature.
|
||||
"""
|
||||
values = super().default_get(field_names)
|
||||
if not any(f in field_names for f in (
|
||||
'expense_account_id', 'long_term_account_id',
|
||||
'short_term_account_id', 'journal_id')):
|
||||
return values
|
||||
previous = self.search([
|
||||
('company_id', '=', self.env.company.id),
|
||||
('expense_account_id', '!=', False),
|
||||
('long_term_account_id', '!=', False),
|
||||
('short_term_account_id', '!=', False),
|
||||
('journal_id', '!=', False),
|
||||
], limit=1, order='id desc')
|
||||
if previous:
|
||||
for field_name in ('expense_account_id', 'long_term_account_id',
|
||||
'short_term_account_id', 'journal_id'):
|
||||
values[field_name] = previous[field_name].id
|
||||
return values
|
||||
|
||||
# -- constrains ------------------------------------------------------
|
||||
|
||||
@api.constrains('amount_borrowed', 'interest', 'duration')
|
||||
def _check_positive_values(self):
|
||||
for loan in self:
|
||||
rounding = loan.currency_id.rounding or 0.01
|
||||
if float_compare(loan.amount_borrowed, 0.0, precision_rounding=rounding) < 0:
|
||||
raise ValidationError(_("The amount borrowed cannot be negative."))
|
||||
if float_compare(loan.interest, 0.0, precision_rounding=rounding) < 0:
|
||||
raise ValidationError(_("The interest cannot be negative."))
|
||||
if loan.duration < 0:
|
||||
raise ValidationError(_("The duration cannot be negative."))
|
||||
|
||||
@api.constrains('long_term_account_id', 'short_term_account_id', 'expense_account_id')
|
||||
def _check_accounts(self):
|
||||
"""Long and short term must be different accounts.
|
||||
|
||||
If they are the same, the monthly reclassification moves money from an
|
||||
account to itself: the entry is balanced but meaningless, and the
|
||||
balance sheet shows nothing at all. Catching it here is much cheaper
|
||||
than explaining the empty balance sheet later.
|
||||
"""
|
||||
for loan in self:
|
||||
if (loan.long_term_account_id and loan.short_term_account_id
|
||||
and loan.long_term_account_id == loan.short_term_account_id):
|
||||
raise ValidationError(_(
|
||||
"The long term and short term accounts must be different: "
|
||||
"the monthly reclassification would otherwise move the "
|
||||
"principal from an account to itself."))
|
||||
|
||||
# -- computes --------------------------------------------------------
|
||||
|
||||
@api.depends('name', 'start_date', 'end_date')
|
||||
def _compute_display_name(self):
|
||||
for loan in self:
|
||||
if loan.name and loan.start_date and loan.end_date:
|
||||
loan.display_name = "%s: %s - %s" % (
|
||||
loan.name,
|
||||
format_date(self.env, loan.start_date, date_format='MM y'),
|
||||
format_date(self.env, loan.end_date, date_format='MM y'),
|
||||
)
|
||||
else:
|
||||
loan.display_name = loan.name or _("New Loan")
|
||||
|
||||
@api.depends('line_ids.date')
|
||||
def _compute_start_end_date(self):
|
||||
for loan in self:
|
||||
dates = loan.line_ids.mapped('date')
|
||||
loan.start_date = min(dates) if dates else False
|
||||
loan.end_date = max(dates) if dates else False
|
||||
|
||||
@api.depends('date', 'line_ids.date')
|
||||
def _compute_is_wrong_date(self):
|
||||
"""Whether the loan date is unusable.
|
||||
|
||||
An installment dated before the loan itself means interest would be
|
||||
charged for time that had not elapsed yet, so the schedule is rejected.
|
||||
"""
|
||||
for loan in self:
|
||||
loan.is_wrong_date = bool(
|
||||
not loan.date
|
||||
or any(d < loan.date for d in loan.line_ids.mapped('date'))
|
||||
)
|
||||
|
||||
@api.depends('amount_borrowed', 'interest', 'duration', 'line_ids.principal',
|
||||
'line_ids.interest', 'currency_id')
|
||||
def _compute_differences(self):
|
||||
for loan in self:
|
||||
rounding = loan.currency_id.rounding or 0.01
|
||||
principal_sum = sum(loan.line_ids.mapped('principal'))
|
||||
interest_sum = sum(loan.line_ids.mapped('interest'))
|
||||
loan.amount_borrowed_difference = loan.currency_id.round(
|
||||
loan.amount_borrowed - principal_sum
|
||||
)
|
||||
loan.interest_difference = loan.currency_id.round(loan.interest - interest_sum)
|
||||
loan.duration_difference = loan.duration - len(loan.line_ids)
|
||||
# Silence the unused variable warning while keeping the rounding
|
||||
# precision explicit at the call site.
|
||||
del rounding
|
||||
|
||||
@api.depends('amount_borrowed', 'state', 'line_ids.principal',
|
||||
'line_ids.is_payment_move_posted', 'skip_until_date',
|
||||
'line_ids.date')
|
||||
def _compute_outstanding_balance(self):
|
||||
"""Principal still owed, based only on what has been posted.
|
||||
|
||||
Deriving this from the schedule instead would show a loan as partly
|
||||
repaid as soon as the schedule exists, even though no entry has been
|
||||
booked. The balance sheet would disagree with the loan list, and the
|
||||
loan list is what people check.
|
||||
"""
|
||||
for loan in self:
|
||||
if loan.state != 'running':
|
||||
loan.outstanding_balance = loan.amount_borrowed
|
||||
continue
|
||||
repaid = sum(
|
||||
line.principal for line in loan.line_ids
|
||||
if line.is_payment_move_posted
|
||||
or (loan.skip_until_date and line.date < loan.skip_until_date)
|
||||
)
|
||||
loan.outstanding_balance = loan.currency_id.round(
|
||||
loan.amount_borrowed - repaid
|
||||
)
|
||||
|
||||
@api.depends('move_ids.state')
|
||||
def _compute_nb_posted_entries(self):
|
||||
for loan in self:
|
||||
loan.nb_posted_entries = len(
|
||||
loan.move_ids.filtered(lambda m: m.state == 'posted')
|
||||
)
|
||||
|
||||
@api.depends('line_ids')
|
||||
def _compute_count_lines(self):
|
||||
for loan in self:
|
||||
loan.count_lines = len(loan.line_ids)
|
||||
|
||||
# -- schedule helpers -------------------------------------------------
|
||||
|
||||
def _schedule_summary(self):
|
||||
"""Totals of the schedule, used by the preview and the confirm check."""
|
||||
self.ensure_one()
|
||||
return {
|
||||
'principal': sum(self.line_ids.mapped('principal')),
|
||||
'interest': sum(self.line_ids.mapped('interest')),
|
||||
'count': len(self.line_ids),
|
||||
}
|
||||
|
||||
def _next_reclassification_amount(self, line):
|
||||
"""Principal due in the twelve months following ``line``.
|
||||
|
||||
This is what the monthly reclassification moves from long term to short
|
||||
term: at each payment date, whatever falls due over the coming year has
|
||||
to sit on the short term account.
|
||||
"""
|
||||
self.ensure_one()
|
||||
ordered = self.line_ids.sorted(lambda l: (l.date, l.id))
|
||||
try:
|
||||
index = ordered.ids.index(line.id)
|
||||
except ValueError:
|
||||
return 0.0
|
||||
return sum(ordered[index + 1:index + 13].mapped('principal'))
|
||||
|
||||
# -- actions ---------------------------------------------------------
|
||||
|
||||
def action_open_compute_wizard(self):
|
||||
"""Open the schedule generator, pre-filled from the current record."""
|
||||
self.ensure_one()
|
||||
if not self.name:
|
||||
raise UserError(_("Please give the loan a name before computing it."))
|
||||
wizard = self.env['dn.loan.compute.wizard'].create({
|
||||
'loan_id': self.id,
|
||||
'loan_amount': self.amount_borrowed or 0.0,
|
||||
'start_date': self.date or fields.Date.context_today(self),
|
||||
'first_payment_date': (self.date or fields.Date.context_today(self)).replace(
|
||||
day=1) + relativedelta(months=1),
|
||||
'method': self.method,
|
||||
})
|
||||
return {
|
||||
'name': _("Compute Loan"),
|
||||
'res_id': wizard.id,
|
||||
'type': 'ir.actions.act_window',
|
||||
'res_model': 'dn.loan.compute.wizard',
|
||||
'target': 'new',
|
||||
'views': [[False, 'form']],
|
||||
}
|
||||
|
||||
def action_confirm(self):
|
||||
"""Post every installment that is due, plus the reclassifications.
|
||||
|
||||
Two kinds of entry are produced per installment:
|
||||
|
||||
* the payment entry, which moves the principal out of the short term
|
||||
liability and books the interest as an expense;
|
||||
* the reclassification entry, which moves the principal falling due in
|
||||
the next twelve months from long term to short term, and its mirror
|
||||
image at the start of the following month.
|
||||
|
||||
The reclassification exists because a loan is long term as a whole but
|
||||
the part due within a year must be reported as current. Without it the
|
||||
balance sheet overstates non-current liabilities by up to a full year of
|
||||
repayments.
|
||||
"""
|
||||
for loan in self:
|
||||
loan._check_confirmable()
|
||||
|
||||
payment_values = []
|
||||
reclass_values = []
|
||||
reclass_reverse_values = []
|
||||
|
||||
ordered = loan.line_ids.sorted(lambda l: (l.date, l.id))
|
||||
for index, line in enumerate(ordered):
|
||||
if loan.skip_until_date and line.date < loan.skip_until_date:
|
||||
continue
|
||||
|
||||
# Book into the month of the due date, but never before the loan
|
||||
# itself: an installment due on the 1st for a loan signed on the
|
||||
# 20th still belongs to the loan's month.
|
||||
accounting_date = max(line.date.replace(day=1), loan.date)
|
||||
period_label = format_date(self.env, line.date, date_format='MM/y')
|
||||
prefix = "%s - " % loan.name
|
||||
|
||||
payment_values.append(
|
||||
loan._prepare_payment_move(line, accounting_date, prefix, period_label)
|
||||
)
|
||||
|
||||
if index == len(ordered) - 1:
|
||||
continue # nothing left to reclassify on the final row
|
||||
|
||||
next_lines = ordered[index + 1:index + 13]
|
||||
if not next_lines:
|
||||
continue
|
||||
moving = sum(next_lines.mapped('principal'))
|
||||
if not moving:
|
||||
continue
|
||||
|
||||
from_label = format_date(self.env, next_lines[0].date, date_format='MM/y')
|
||||
to_label = format_date(self.env, next_lines[-1].date, date_format='MM/y')
|
||||
reclass_values.append(loan._prepare_reclassification_move(
|
||||
line, accounting_date, moving, from_label, to_label, prefix,
|
||||
))
|
||||
reclass_reverse_values.append(loan._prepare_reclassification_reversal(
|
||||
line, moving, from_label, to_label, prefix,
|
||||
accounting_date + relativedelta(months=1, day=1),
|
||||
))
|
||||
|
||||
payment_moves = self.env['account.move'].create(payment_values)
|
||||
reclass_moves = self.env['account.move'].create(reclass_values)
|
||||
reverse_moves = self.env['account.move'].create(reclass_reverse_values)
|
||||
|
||||
# Entries dated in the future stay in draft, so the schedule can be
|
||||
# corrected without reversing anything. `auto_post` is what makes
|
||||
# them post themselves once the date arrives.
|
||||
to_post = (payment_moves | reclass_moves | reverse_moves).filtered(
|
||||
lambda m: m.date <= fields.Date.context_today(self)
|
||||
)
|
||||
to_post.action_post()
|
||||
|
||||
loan._link_reversals(reclass_moves, reverse_moves)
|
||||
|
||||
loan.state = 'running'
|
||||
loan.message_post(body=_(
|
||||
"Loan confirmed: %(count)s installments scheduled, "
|
||||
"%(posted)s entries posted and %(draft)s left for later dates.",
|
||||
count=len(ordered),
|
||||
posted=len(to_post),
|
||||
draft=len(payment_moves | reclass_moves | reverse_moves) - len(to_post),
|
||||
))
|
||||
|
||||
return True
|
||||
|
||||
def _check_confirmable(self):
|
||||
"""Refuse to confirm a loan whose schedule does not add up.
|
||||
|
||||
Each of these conditions would produce entries that cannot be reconciled
|
||||
against the contract, so the loan is blocked rather than booked wrongly.
|
||||
"""
|
||||
self.ensure_one()
|
||||
rounding = self.currency_id.rounding or 0.01
|
||||
|
||||
if not self.name:
|
||||
raise UserError(_("The loan name should be set."))
|
||||
if not self.line_ids:
|
||||
raise UserError(_("The loan has no amortization schedule. Compute or "
|
||||
"import it before confirming the loan."))
|
||||
if self.is_wrong_date:
|
||||
raise UserError(_(
|
||||
"The loan date must be on or before the first installment date."))
|
||||
if float_compare(self.amount_borrowed_difference, 0.0,
|
||||
precision_rounding=rounding) != 0:
|
||||
raise UserError(_(
|
||||
"The amount borrowed (%(amount)s) must equal the sum of the "
|
||||
"principals in the schedule (%(principal)s), a difference of "
|
||||
"%(difference)s remains.",
|
||||
amount=self.currency_id.format(self.amount_borrowed),
|
||||
principal=self.currency_id.format(
|
||||
sum(self.line_ids.mapped('principal'))),
|
||||
difference=self.currency_id.format(self.amount_borrowed_difference),
|
||||
))
|
||||
if float_compare(self.interest_difference, 0.0,
|
||||
precision_rounding=rounding) != 0:
|
||||
raise UserError(_(
|
||||
"The interest (%(interest)s) must equal the sum of the interest "
|
||||
"in the schedule (%(schedule)s).",
|
||||
interest=self.currency_id.format(self.interest),
|
||||
schedule=self.currency_id.format(sum(self.line_ids.mapped('interest'))),
|
||||
))
|
||||
if self.duration_difference != 0:
|
||||
raise UserError(_(
|
||||
"The duration (%(duration)s) must equal the number of "
|
||||
"installments in the schedule (%(lines)s).",
|
||||
duration=self.duration, lines=len(self.line_ids),
|
||||
))
|
||||
if not (self.long_term_account_id and self.short_term_account_id
|
||||
and self.expense_account_id):
|
||||
raise UserError(_(
|
||||
"The long term, short term and interest expense accounts should "
|
||||
"all be set before confirming the loan."))
|
||||
if not self.journal_id:
|
||||
raise UserError(_("The loan journal should be set before "
|
||||
"confirming the loan."))
|
||||
|
||||
# -- entry preparation ------------------------------------------------
|
||||
|
||||
def _move_common_values(self, line, accounting_date, ref, is_payment):
|
||||
self.ensure_one()
|
||||
return {
|
||||
'company_id': self.company_id.id,
|
||||
'journal_id': self.journal_id.id,
|
||||
'date': accounting_date,
|
||||
'ref': ref,
|
||||
'auto_post': 'at_date',
|
||||
'dn_loan_line_id': line.id,
|
||||
'is_loan_payment_move': is_payment,
|
||||
}
|
||||
|
||||
def _prepare_payment_move(self, line, accounting_date, prefix, period_label):
|
||||
"""The entry that actually pays one installment."""
|
||||
self.ensure_one()
|
||||
return {
|
||||
**self._move_common_values(
|
||||
line, accounting_date,
|
||||
_("%(loan)s - Principal & Interest %(period)s",
|
||||
loan=self.name, period=period_label),
|
||||
is_payment=True,
|
||||
),
|
||||
'line_ids': [
|
||||
Command.create({
|
||||
'account_id': self.long_term_account_id.id,
|
||||
'debit': line.principal,
|
||||
'name': _("%(loan)s - Principal %(period)s",
|
||||
loan=self.name, period=period_label),
|
||||
'analytic_distribution': self.analytic_distribution,
|
||||
}),
|
||||
Command.create({
|
||||
'account_id': self.short_term_account_id.id,
|
||||
'credit': line.payment,
|
||||
'name': _("%(loan)s - Due %(period)s (Principal %(principal)s "
|
||||
"+ Interest %(interest)s)",
|
||||
loan=self.name, period=period_label,
|
||||
principal=self.currency_id.format(line.principal),
|
||||
interest=self.currency_id.format(line.interest)),
|
||||
'analytic_distribution': self.analytic_distribution,
|
||||
'date_maturity': line.date,
|
||||
}),
|
||||
Command.create({
|
||||
'account_id': self.expense_account_id.id,
|
||||
'debit': line.interest,
|
||||
'name': _("%(loan)s - Interest %(period)s",
|
||||
loan=self.name, period=period_label),
|
||||
'analytic_distribution': self.analytic_distribution,
|
||||
}),
|
||||
],
|
||||
}
|
||||
|
||||
def _prepare_reclassification_move(self, line, accounting_date, amount,
|
||||
from_label, to_label, prefix):
|
||||
"""Move the principal due within a year to the short term account."""
|
||||
self.ensure_one()
|
||||
label = _("Reclassification LT - ST %(from_date)s to %(to_date)s",
|
||||
from_date=from_label, to_date=to_label)
|
||||
return {
|
||||
**self._move_common_values(
|
||||
line, accounting_date, "%s%s" % (prefix, label), is_payment=False,
|
||||
),
|
||||
'line_ids': [
|
||||
Command.create({
|
||||
'account_id': self.long_term_account_id.id,
|
||||
'debit': amount,
|
||||
'name': "%s%s (To %s)" % (prefix, label, self.short_term_account_id.code),
|
||||
'analytic_distribution': self.analytic_distribution,
|
||||
}),
|
||||
Command.create({
|
||||
'account_id': self.short_term_account_id.id,
|
||||
'credit': amount,
|
||||
'name': "%s%s (From %s)" % (prefix, label, self.long_term_account_id.code),
|
||||
'analytic_distribution': self.analytic_distribution,
|
||||
}),
|
||||
],
|
||||
}
|
||||
|
||||
def _prepare_reclassification_reversal(self, line, amount, from_label,
|
||||
to_label, prefix, reversal_date):
|
||||
"""The mirror of the reclassification, on the first of the next month.
|
||||
|
||||
The reclassification is not a carry-forward: it only restates the split
|
||||
as of the closing date. Leaving it in place would double the short term
|
||||
liability every month, so it is reversed immediately.
|
||||
"""
|
||||
self.ensure_one()
|
||||
label = _("Reversal reclassification LT - ST %(from_date)s to %(to_date)s",
|
||||
from_date=from_label, to_date=to_label)
|
||||
return {
|
||||
**self._move_common_values(
|
||||
line, reversal_date, "%s%s" % (prefix, label), is_payment=False,
|
||||
),
|
||||
'line_ids': [
|
||||
Command.create({
|
||||
'account_id': self.long_term_account_id.id,
|
||||
'credit': amount,
|
||||
'name': "%s%s (To %s)" % (prefix, label, self.short_term_account_id.code),
|
||||
'analytic_distribution': self.analytic_distribution,
|
||||
}),
|
||||
Command.create({
|
||||
'account_id': self.short_term_account_id.id,
|
||||
'debit': amount,
|
||||
'name': "%s%s (From %s)" % (prefix, label, self.long_term_account_id.code),
|
||||
'analytic_distribution': self.analytic_distribution,
|
||||
}),
|
||||
],
|
||||
}
|
||||
|
||||
def _link_reversals(self, reclass_moves, reverse_moves):
|
||||
"""Tie each reversal to its original, both ways, with a log message."""
|
||||
self.ensure_one()
|
||||
bodies = {}
|
||||
for original, reversal in zip(reclass_moves, reverse_moves):
|
||||
reversal.reversed_entry_id = original.id
|
||||
reversal.message_post(body=_(
|
||||
"This entry reverses %s.",
|
||||
original._get_html_link(),
|
||||
))
|
||||
bodies[original.id] = _(
|
||||
"This entry has been reversed by %s.",
|
||||
reversal._get_html_link(title=_("reversed")),
|
||||
)
|
||||
if bodies:
|
||||
reclass_moves._message_log_batch(bodies=bodies)
|
||||
|
||||
# -- lifecycle --------------------------------------------------------
|
||||
|
||||
def action_set_to_draft(self):
|
||||
"""Undo the confirmation, removing the entries it produced."""
|
||||
for loan in self:
|
||||
loan.move_ids.filtered(lambda m: m.state != 'cancel')._unlink_or_reverse()
|
||||
loan.state = 'draft'
|
||||
loan.message_post(body=_("Loan reset to draft."))
|
||||
|
||||
def action_cancel(self):
|
||||
for loan in self:
|
||||
loan.move_ids.filtered(lambda m: m.state != 'cancel')._unlink_or_reverse()
|
||||
loan.state = 'cancelled'
|
||||
loan.message_post(body=_("Loan cancelled."))
|
||||
|
||||
def action_reset_schedule(self):
|
||||
"""Clear the schedule so it can be computed again."""
|
||||
for loan in self:
|
||||
loan.line_ids.unlink()
|
||||
loan.message_post(body=_("Amortization schedule cleared."))
|
||||
|
||||
def action_close(self):
|
||||
"""Open the wizard that closes the loan at a chosen date."""
|
||||
self.ensure_one()
|
||||
wizard = self.env['dn.loan.close.wizard'].create({'loan_id': self.id})
|
||||
return {
|
||||
'name': _("Close Loan"),
|
||||
'view_mode': 'form',
|
||||
'res_model': 'dn.loan.close.wizard',
|
||||
'type': 'ir.actions.act_window',
|
||||
'target': 'new',
|
||||
'res_id': wizard.id,
|
||||
}
|
||||
|
||||
def action_reopen(self):
|
||||
"""Put a closed loan back in progress, keeping its schedule."""
|
||||
for loan in self:
|
||||
if loan.state != 'closed':
|
||||
continue
|
||||
loan.state = 'running'
|
||||
loan.message_post(body=_("Loan reopened."))
|
||||
|
||||
# -- navigation -------------------------------------------------------
|
||||
|
||||
def action_open_loan_entries(self):
|
||||
self.ensure_one()
|
||||
return {
|
||||
'name': _("Loan Entries"),
|
||||
'view_mode': 'list,form',
|
||||
'res_model': 'account.move',
|
||||
'views': [(self.env.ref(
|
||||
'accountant_cn.dn_loan_move_list_view').id, 'list'),
|
||||
(False, 'form')],
|
||||
'type': 'ir.actions.act_window',
|
||||
'domain': [('id', 'in', self.move_ids.ids)],
|
||||
}
|
||||
|
||||
# -- import -----------------------------------------------------------
|
||||
|
||||
def action_upload_amortization_schedule(self):
|
||||
"""Let the user drop a spreadsheet and map its columns.
|
||||
|
||||
Reusing the standard import wizard keeps the behaviour people already
|
||||
know, instead of inventing a bespoke CSV parser.
|
||||
"""
|
||||
self.ensure_one()
|
||||
return {
|
||||
'type': 'ir.actions.act_window',
|
||||
'name': _("Import Amortization Schedule"),
|
||||
'res_model': 'base_import.import',
|
||||
'view_mode': 'form',
|
||||
'target': 'new',
|
||||
'context': {
|
||||
'default_res_model': 'dn.loan.line',
|
||||
'default_loan_id': self.id,
|
||||
},
|
||||
}
|
||||
|
||||
# -- crud -------------------------------------------------------------
|
||||
|
||||
@api.ondelete(at_uninstall=False)
|
||||
def _unlink_loan(self):
|
||||
"""Remove the loan's entries together with the loan.
|
||||
|
||||
`dn_loan_line_id` cascades at the database level, but a posted entry
|
||||
cannot be deleted, only reversed. Handling it explicitly keeps the
|
||||
ledger consistent instead of raising a foreign key error.
|
||||
"""
|
||||
for loan in self:
|
||||
loan.move_ids._unlink_or_reverse()
|
||||
loan.line_ids.unlink()
|
||||
|
||||
def unlink(self):
|
||||
if any(loan.state == 'running' for loan in self):
|
||||
raise UserError(_(
|
||||
"A running loan cannot be deleted: its entries are in the "
|
||||
"ledger. Cancel it first, then delete it."))
|
||||
return super().unlink()
|
||||
12
accountant_cn/models/dn_loan_journal.py
Normal file
12
accountant_cn/models/dn_loan_journal.py
Normal file
@@ -0,0 +1,12 @@
|
||||
from odoo import fields, models
|
||||
|
||||
|
||||
class AccountJournal(models.Model):
|
||||
_inherit = 'account.journal'
|
||||
|
||||
loan_properties_definition = fields.PropertiesDefinition(
|
||||
string='Loan Properties',
|
||||
help="Fields offered on the Properties tab of the loans booked in this "
|
||||
"journal. Defining them per journal keeps each kind of borrowing "
|
||||
"recording the attributes it actually has.",
|
||||
)
|
||||
127
accountant_cn/models/dn_loan_line.py
Normal file
127
accountant_cn/models/dn_loan_line.py
Normal file
@@ -0,0 +1,127 @@
|
||||
from odoo import _, api, fields, models
|
||||
|
||||
|
||||
class DnLoanLine(models.Model):
|
||||
_name = 'dn.loan.line'
|
||||
_description = 'Loan Installment'
|
||||
_order = 'date, id'
|
||||
_check_company_auto = True
|
||||
|
||||
sequence = fields.Integer(string='#', compute='_compute_sequence')
|
||||
loan_id = fields.Many2one(
|
||||
'dn.loan', string='Loan', required=True, ondelete='cascade', index=True,
|
||||
)
|
||||
company_id = fields.Many2one(related='loan_id.company_id', store=True, index=True)
|
||||
currency_id = fields.Many2one(related='loan_id.currency_id')
|
||||
loan_state = fields.Selection(related='loan_id.state', store=True)
|
||||
loan_name = fields.Char(related='loan_id.name', store=True)
|
||||
|
||||
date = fields.Date(string='Date', required=True)
|
||||
principal = fields.Monetary(string='Principal')
|
||||
interest = fields.Monetary(string='Interest')
|
||||
payment = fields.Monetary(
|
||||
string='Payment', compute='_compute_payment', store=True,
|
||||
# Stored so the pivot view can sum it.
|
||||
)
|
||||
outstanding_balance = fields.Monetary(
|
||||
string='Outstanding Balance', compute='_compute_outstanding_balance',
|
||||
help="Principal still owed once this installment has been paid.",
|
||||
)
|
||||
long_term_theoretical_balance = fields.Monetary(
|
||||
string='Long-Term', compute='_compute_theoretical_balances', store=True,
|
||||
help="Principal still owed more than twelve months after this date. "
|
||||
"Stored so a pivot can sum it.",
|
||||
)
|
||||
short_term_theoretical_balance = fields.Monetary(
|
||||
string='Short-Term', compute='_compute_theoretical_balances', store=True,
|
||||
help="Principal due within twelve months after this date.",
|
||||
)
|
||||
|
||||
move_ids = fields.One2many(
|
||||
'account.move', 'dn_loan_line_id', string='Generated Entries',
|
||||
readonly=True, copy=False,
|
||||
help="Entries generated from this installment.",
|
||||
)
|
||||
is_payment_move_posted = fields.Boolean(
|
||||
compute='_compute_is_payment_move_posted',
|
||||
help="Whether the payment entry for this installment is in the ledger.",
|
||||
)
|
||||
|
||||
# -- computes --------------------------------------------------------
|
||||
|
||||
@api.depends('principal', 'interest')
|
||||
def _compute_payment(self):
|
||||
for line in self:
|
||||
line.payment = line.principal + line.interest
|
||||
|
||||
@api.depends('loan_id.amount_borrowed', 'loan_id.line_ids.principal',
|
||||
'loan_id.line_ids.date', 'date', 'principal')
|
||||
def _compute_outstanding_balance(self):
|
||||
"""Theoretical balance after paying this installment.
|
||||
|
||||
This is the schedule's own view of the balance, used in the schedule
|
||||
table. The loan's `outstanding_balance` is the accounting one and can
|
||||
legitimately differ while entries are still in draft.
|
||||
"""
|
||||
for line in self:
|
||||
if not line.date:
|
||||
line.outstanding_balance = line.loan_id.amount_borrowed
|
||||
continue
|
||||
repaid = sum(
|
||||
other.principal for other in line.loan_id.line_ids
|
||||
if other.date and other.date <= line.date
|
||||
)
|
||||
line.outstanding_balance = line.loan_id.amount_borrowed - repaid
|
||||
|
||||
@api.depends('date', 'loan_id.line_ids.date', 'loan_id.line_ids.principal')
|
||||
def _compute_theoretical_balances(self):
|
||||
"""Split the remaining principal into the part due within a year.
|
||||
|
||||
This is what the reclassification entry books, shown next to each row
|
||||
so the amounts can be checked before anything is posted.
|
||||
"""
|
||||
for line in self:
|
||||
if not line.date:
|
||||
line.long_term_theoretical_balance = 0.0
|
||||
line.short_term_theoretical_balance = 0.0
|
||||
continue
|
||||
later = line.loan_id.line_ids.filtered(
|
||||
lambda other: other.date and other.date > line.date
|
||||
).sorted(lambda other: (other.date, other.id))
|
||||
line.short_term_theoretical_balance = sum(
|
||||
later[:12].mapped('principal'))
|
||||
line.long_term_theoretical_balance = sum(
|
||||
later[12:].mapped('principal'))
|
||||
|
||||
@api.depends('date', 'loan_id.line_ids.date')
|
||||
def _compute_sequence(self):
|
||||
for line in self.sorted(lambda l: (l.date or fields.Date.today(), l.id)):
|
||||
if not line.date:
|
||||
line.sequence = 0
|
||||
continue
|
||||
line.sequence = len(line.loan_id.line_ids.filtered(
|
||||
lambda other: other.date and other.date <= line.date
|
||||
))
|
||||
|
||||
@api.depends('move_ids.state', 'move_ids.is_loan_payment_move',
|
||||
'move_ids.reversal_move_ids')
|
||||
def _compute_is_payment_move_posted(self):
|
||||
for line in self:
|
||||
payments = line.move_ids.filtered(lambda m: m.is_loan_payment_move)
|
||||
# When the audit trail is enabled a loan can be cancelled and
|
||||
# confirmed again, which leaves several payment entries. The one
|
||||
# that still stands is the one without a reversal.
|
||||
if len(payments) > 1 and any(m.reversal_move_ids for m in payments):
|
||||
payments = payments.filtered(lambda m: not m.reversal_move_ids)
|
||||
line.is_payment_move_posted = any(m.state == 'posted' for m in payments)
|
||||
|
||||
# -- constrains ------------------------------------------------------
|
||||
|
||||
@api.constrains('principal', 'interest')
|
||||
def _check_positive_amounts(self):
|
||||
for line in self:
|
||||
if line.principal < 0 or line.interest < 0:
|
||||
from odoo.exceptions import ValidationError
|
||||
raise ValidationError(_(
|
||||
"An installment cannot have a negative principal or a "
|
||||
"negative interest."))
|
||||
56
accountant_cn/models/dn_loan_move.py
Normal file
56
accountant_cn/models/dn_loan_move.py
Normal file
@@ -0,0 +1,56 @@
|
||||
from odoo import _, fields, models
|
||||
|
||||
|
||||
class AccountMove(models.Model):
|
||||
_inherit = 'account.move'
|
||||
|
||||
dn_loan_line_id = fields.Many2one(
|
||||
'dn.loan.line', string='Loan Installment',
|
||||
help="Installment of the loan that generated this entry.",
|
||||
copy=False, readonly=True, index=True, ondelete='cascade',
|
||||
)
|
||||
dn_loan_id = fields.Many2one(
|
||||
related='dn_loan_line_id.loan_id', string='Loan', store=True, index=True,
|
||||
)
|
||||
is_loan_payment_move = fields.Boolean(
|
||||
string='Is Loan Payment',
|
||||
help="True for the entry that pays an installment, false for the "
|
||||
"reclassification and its reversal.",
|
||||
)
|
||||
|
||||
def _post(self, soft=True):
|
||||
"""Close the loan once its last installment has been posted.
|
||||
|
||||
Checking here rather than on the installment keeps the state correct no
|
||||
matter where the posting comes from: the confirm action, a manual post,
|
||||
or the scheduler honouring `auto_post`.
|
||||
"""
|
||||
posted = super()._post(soft=soft)
|
||||
loans = self.env['dn.loan']
|
||||
for move in self:
|
||||
loan = move.dn_loan_id
|
||||
if not loan or loan.state != 'running':
|
||||
continue
|
||||
skip = loan.skip_until_date
|
||||
if all(
|
||||
line.is_payment_move_posted
|
||||
or (skip and line.date < skip)
|
||||
for line in loan.line_ids
|
||||
):
|
||||
loans |= loan
|
||||
if loans:
|
||||
loans.write({'state': 'closed'})
|
||||
for loan in loans:
|
||||
loan.message_post(body=_(
|
||||
"All installments are posted, the loan is now closed."))
|
||||
return posted
|
||||
|
||||
def action_open_dn_loan(self):
|
||||
self.ensure_one()
|
||||
return {
|
||||
'type': 'ir.actions.act_window',
|
||||
'name': _("Loan"),
|
||||
'views': [(False, 'form')],
|
||||
'res_model': 'dn.loan',
|
||||
'res_id': self.dn_loan_id.id,
|
||||
}
|
||||
431
accountant_cn/models/dn_report.py
Normal file
431
accountant_cn/models/dn_report.py
Normal file
@@ -0,0 +1,431 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
DN Financial Report Engine — original implementation for Odoo 20 Community.
|
||||
|
||||
Design (written from scratch, inspired by the generic "report as data" pattern):
|
||||
|
||||
A report is pure DATA: a tree of lines, each line owning expressions.
|
||||
An expression is one calculation unit with an "engine" and a "formula":
|
||||
|
||||
domain Python domain on account.move.line -> SUM(balance)
|
||||
account_codes Comma separated account-code prefixes -> SUM(balance)
|
||||
aggregation Arithmetic over other expression labels, e.g. "CA + RE"
|
||||
text A literal label
|
||||
|
||||
The engine evaluates every expression once per "column group" (a period),
|
||||
then assembles the line tree. Rendering is delegated to a client action so
|
||||
the same payload can later be drawn as HTML / PDF / XLSX.
|
||||
|
||||
Only depends on the LGPL-3 community `account` module.
|
||||
|
||||
Odoo 20 notes (these differ from 17/18 and are the reason for several choices):
|
||||
* `read_group()` returns *tuples* and takes `aggregates=` (not list-of-dicts).
|
||||
`_read_group()` is the modern entry point and is used here.
|
||||
* Backend view tag is `<list>`, `<tree>` no longer exists.
|
||||
* `_sql_constraints` is deprecated -> `models.Constraint(...)`.
|
||||
* QWeb uses `t-out` (`t-esc` is legacy).
|
||||
"""
|
||||
import ast
|
||||
import logging
|
||||
import re
|
||||
|
||||
from odoo import _, api, fields, models
|
||||
from odoo.exceptions import UserError
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
# Aggregation formulas are arithmetic only; keep the sandbox deliberately tiny.
|
||||
_SAFE_GLOBALS = {"__builtins__": {}, "abs": abs, "round": round, "max": max, "min": min}
|
||||
_TOKEN_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
|
||||
_SIGNED_NUMBER_RE = re.compile(r"^\s*-\s*\d")
|
||||
|
||||
|
||||
def _eval_aggregation(formula, variables):
|
||||
"""Evaluate an arithmetic formula (e.g. ``CA + RE``) over `variables`."""
|
||||
try:
|
||||
return eval(formula, _SAFE_GLOBALS, dict(variables)) # noqa: S307 - sandboxed
|
||||
except Exception as exc: # noqa: BLE001 - turn into a readable report error
|
||||
raise UserError(
|
||||
_("Invalid aggregation formula '%(f)s': %(e)s", f=formula, e=exc)
|
||||
) from exc
|
||||
|
||||
|
||||
class DnReport(models.Model):
|
||||
_name = "dn.report"
|
||||
_description = "DN Financial Report"
|
||||
_order = "sequence, id"
|
||||
|
||||
name = fields.Char(required=True, translate=True)
|
||||
code = fields.Char(required=True, help="Unique technical code of the report.")
|
||||
sequence = fields.Integer(default=10)
|
||||
active = fields.Boolean(default=True)
|
||||
description = fields.Text(translate=True)
|
||||
line_ids = fields.One2many("dn.report.line", "report_id", string="Lines")
|
||||
column_ids = fields.One2many("dn.report.column", "report_id", string="Columns")
|
||||
group_by_account = fields.Boolean(
|
||||
default=False, help="Generate one dynamic line per account (for ledgers)."
|
||||
)
|
||||
|
||||
_code_uniq = models.Constraint("unique(code)", "Report code must be unique.")
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Public entry point (client action / controller)
|
||||
# ------------------------------------------------------------------
|
||||
def get_report_data(self, options=None):
|
||||
"""Return ``{columns, headers, lines}`` ready for rendering.
|
||||
|
||||
:param options: dict with date_from, date_to, company_ids,
|
||||
column_groups, unfold_all
|
||||
"""
|
||||
self.ensure_one()
|
||||
options = self._normalize_options(options or {})
|
||||
groups = self._column_groups(options)
|
||||
columns = [
|
||||
{
|
||||
"key": "c%d" % idx,
|
||||
"label": g["label"],
|
||||
"date_from": g.get("date_from"),
|
||||
"date_to": g.get("date_to"),
|
||||
}
|
||||
for idx, g in enumerate(groups)
|
||||
]
|
||||
return {
|
||||
"report_id": self.id,
|
||||
"name": self.name,
|
||||
"code": self.code,
|
||||
"columns": columns,
|
||||
"headers": [c["label"] for c in columns],
|
||||
"lines": self._compute_lines(options, groups),
|
||||
}
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Options & columns
|
||||
# ------------------------------------------------------------------
|
||||
def _normalize_options(self, options):
|
||||
options = dict(options or {})
|
||||
if not options.get("company_ids"):
|
||||
options["company_ids"] = self.env.company.ids
|
||||
return options
|
||||
|
||||
def _column_groups(self, options):
|
||||
groups = options.get("column_groups")
|
||||
if groups:
|
||||
normalized = []
|
||||
for idx, g in enumerate(groups):
|
||||
normalized.append(
|
||||
{
|
||||
"label": g.get("label") or _("Period %s", idx + 1),
|
||||
"date_from": g.get("date_from"),
|
||||
"date_to": g.get("date_to"),
|
||||
}
|
||||
)
|
||||
return normalized
|
||||
return [
|
||||
{
|
||||
"label": options.get("column_label") or _("Amount of the period"),
|
||||
"date_from": options.get("date_from"),
|
||||
"date_to": options.get("date_to"),
|
||||
}
|
||||
]
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Calculation
|
||||
# ------------------------------------------------------------------
|
||||
def _compute_lines(self, options, column_groups):
|
||||
expressions = self.line_ids.expression_ids
|
||||
values_per_column = {}
|
||||
for idx, group in enumerate(column_groups):
|
||||
values_per_column["c%d" % idx] = self._compute_expressions(
|
||||
options, group, expressions
|
||||
)
|
||||
account_breakdown = None
|
||||
if self.group_by_account:
|
||||
account_breakdown = [
|
||||
self._account_breakdown(options, group) for group in column_groups
|
||||
]
|
||||
|
||||
result = []
|
||||
for line in self.line_ids.filtered(lambda l: not l.parent_id).sorted("sequence"):
|
||||
result.append(
|
||||
self._serialize_line(line, values_per_column, level=0,
|
||||
account_breakdown=account_breakdown)
|
||||
)
|
||||
return result
|
||||
|
||||
def _serialize_line(self, line, values_per_column, level, account_breakdown=None):
|
||||
children = [
|
||||
self._serialize_line(child, values_per_column, level + 1)
|
||||
for child in line.children_ids.sorted("sequence")
|
||||
]
|
||||
# Leaf ledger lines can be drilled down to one row per account.
|
||||
if not children and account_breakdown and not line.is_total:
|
||||
children = self._account_children(line, account_breakdown, level + 1)
|
||||
|
||||
row = {
|
||||
"id": line.id,
|
||||
"code": line.code or "",
|
||||
"name": line.name,
|
||||
"level": level,
|
||||
"is_total": line.is_total,
|
||||
"foldable": bool(children),
|
||||
"values": {
|
||||
key: self._line_value(line, expr_values)
|
||||
for key, expr_values in values_per_column.items()
|
||||
},
|
||||
"children": children,
|
||||
}
|
||||
return row
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Optional drill-down: one child row per account
|
||||
# ------------------------------------------------------------------
|
||||
def _account_breakdown(self, options, group):
|
||||
"""Return {account_id: {code, name, balance}} for the period."""
|
||||
domain = self._base_domain(options, group)
|
||||
rows = self.env["account.move.line"].sudo()._read_group(
|
||||
domain,
|
||||
groupby=["account_id"],
|
||||
aggregates=["balance:sum"],
|
||||
)
|
||||
breakdown = {}
|
||||
for account, balance in rows:
|
||||
if not account:
|
||||
continue
|
||||
breakdown[account.id] = {
|
||||
"code": account.code or "",
|
||||
"name": account.name or "",
|
||||
"balance": float(balance or 0.0),
|
||||
}
|
||||
return breakdown
|
||||
|
||||
def _account_children(self, line, account_breakdown, level):
|
||||
"""Build one child row per account matching the line's expressions."""
|
||||
matching = self._matching_account_ids(line, account_breakdown)
|
||||
if not matching:
|
||||
return []
|
||||
children = []
|
||||
for col_idx, breakdown in enumerate(account_breakdown):
|
||||
for account_id in matching:
|
||||
if account_id not in breakdown:
|
||||
continue
|
||||
info = breakdown[account_id]
|
||||
children.append(
|
||||
{
|
||||
"id": "acc-%s-%s" % (line.id, account_id),
|
||||
"code": info["code"],
|
||||
"name": info["name"],
|
||||
"level": level,
|
||||
"is_total": False,
|
||||
"foldable": False,
|
||||
"values": {"c%d" % col_idx: info["balance"]},
|
||||
"children": [],
|
||||
}
|
||||
)
|
||||
# Merge rows coming from several periods into a single row per account.
|
||||
merged = {}
|
||||
for child in children:
|
||||
existing = merged.setdefault(
|
||||
child["id"],
|
||||
dict(child, values={}, level=level, foldable=False, children=[]),
|
||||
)
|
||||
existing["values"].update(child["values"])
|
||||
return sorted(merged.values(), key=lambda c: (c["code"] or "", c["name"] or ""))
|
||||
|
||||
def _matching_account_ids(self, line, account_breakdown):
|
||||
"""Accounts whose journal items satisfy at least one expression.
|
||||
|
||||
The discovery query runs on ``account.move.line`` (the expressions are
|
||||
written for that model), then the resulting accounts are intersected
|
||||
with the accounts that actually have a balance in the period.
|
||||
"""
|
||||
ids = set()
|
||||
ledger_exprs = line.expression_ids.filtered(
|
||||
lambda e: e.engine in ("domain", "account_codes")
|
||||
)
|
||||
if not ledger_exprs:
|
||||
return ids
|
||||
for expr in ledger_exprs:
|
||||
try:
|
||||
if expr.engine == "domain":
|
||||
domain = self._parse_domain(expr.formula)
|
||||
else:
|
||||
domain = self._account_code_domain(expr.formula)
|
||||
except UserError:
|
||||
continue
|
||||
rows = self.env["account.move.line"].sudo()._read_group(
|
||||
domain, groupby=["account_id"]
|
||||
)
|
||||
ids.update(account.id for account, in rows if account)
|
||||
if account_breakdown:
|
||||
ids &= set(account_breakdown[0])
|
||||
return ids
|
||||
|
||||
def _line_value(self, line, expr_values):
|
||||
"""An explicit aggregation wins, otherwise the line's own sum."""
|
||||
aggregation = line.expression_ids.filtered(lambda e: e.engine == "aggregation")
|
||||
for expr in aggregation:
|
||||
if expr.id in expr_values:
|
||||
return expr_values[expr.id]["value"]
|
||||
for expr in line.expression_ids:
|
||||
if expr.id in expr_values:
|
||||
return expr_values[expr.id]["value"]
|
||||
return 0.0
|
||||
|
||||
def _compute_expressions(self, options, group, expressions):
|
||||
"""Evaluate every expression of the report for one column group."""
|
||||
values = {}
|
||||
|
||||
# 1) Ledger engines
|
||||
for expr in expressions.filtered(lambda e: e.engine in ("domain", "account_codes")):
|
||||
values[expr.id] = {
|
||||
"value": self._run_balance_engine(expr, options, group),
|
||||
"is_text": False,
|
||||
}
|
||||
|
||||
# 2) Text engine
|
||||
for expr in expressions.filtered(lambda e: e.engine == "text"):
|
||||
values[expr.id] = {"value": expr.formula or "", "is_text": True}
|
||||
|
||||
# 3) Aggregation — a formula may reference a label produced by another
|
||||
# aggregation, so keep looping until a round resolves nothing.
|
||||
pending = expressions.filtered(lambda e: e.engine == "aggregation")
|
||||
for _round in range(len(pending) + 1):
|
||||
if not pending:
|
||||
break
|
||||
resolved = self.env["dn.report.expression"]
|
||||
label_map = self._label_value_map(expressions, values)
|
||||
for expr in pending:
|
||||
try:
|
||||
computed = _eval_aggregation(expr.formula, label_map)
|
||||
except UserError:
|
||||
# Probably a label that is not computed yet: retry next round.
|
||||
continue
|
||||
values[expr.id] = {"value": computed, "is_text": False}
|
||||
resolved |= expr
|
||||
if expr.label:
|
||||
label_map[expr.label] = computed
|
||||
pending -= resolved
|
||||
if not resolved:
|
||||
_logger.warning(
|
||||
"DN report %s: unresolved aggregation formulas %s",
|
||||
self.code,
|
||||
pending.mapped("label"),
|
||||
)
|
||||
break
|
||||
return values
|
||||
|
||||
@staticmethod
|
||||
def _label_value_map(expressions, values):
|
||||
"""Map expression label -> numeric value for aggregation formulas."""
|
||||
label_map = {}
|
||||
for expr in expressions:
|
||||
payload = values.get(expr.id)
|
||||
if not payload or payload["is_text"] or not expr.label:
|
||||
continue
|
||||
label_map[expr.label] = label_map.get(expr.label, 0.0) + payload["value"]
|
||||
return label_map
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Ledger engine — the only place that reads account.move.line
|
||||
# ------------------------------------------------------------------
|
||||
def _run_balance_engine(self, expr, options, group):
|
||||
domain = self._base_domain(options, group)
|
||||
|
||||
if expr.engine == "domain":
|
||||
domain = domain + self._parse_domain(expr.formula)
|
||||
else: # account_codes
|
||||
domain = domain + self._account_code_domain(expr.formula)
|
||||
|
||||
if not domain:
|
||||
return 0.0
|
||||
|
||||
rows = self.env["account.move.line"].sudo()._read_group(
|
||||
domain, aggregates=["balance:sum"]
|
||||
)
|
||||
# With no groupby, _read_group returns a single (sum,) row; an empty
|
||||
# recordset yields (None,) or (0,).
|
||||
return float(rows[0][0] or 0.0) if rows else 0.0
|
||||
|
||||
def _base_domain(self, options, group):
|
||||
domain = [("parent_state", "=", "posted")]
|
||||
company_ids = options.get("company_ids") or self.env.company.ids
|
||||
domain.append(("company_id", "in", company_ids))
|
||||
date_from = group.get("date_from") or options.get("date_from")
|
||||
date_to = group.get("date_to") or options.get("date_to")
|
||||
if date_from:
|
||||
domain.append(("date", ">=", date_from))
|
||||
if date_to:
|
||||
domain.append(("date", "<=", date_to))
|
||||
return domain
|
||||
|
||||
@staticmethod
|
||||
def _account_code_domain(formula):
|
||||
"""Build an OR-ed prefix domain: ``"60,62"`` -> 60* or 62*."""
|
||||
prefixes = [p.strip() for p in (formula or "").split(",") if p.strip()]
|
||||
if not prefixes:
|
||||
return []
|
||||
domain = []
|
||||
for prefix in prefixes[:-1]:
|
||||
domain += ["|", ("account_id.code", "=like", prefix + "%")]
|
||||
domain.append(("account_id.code", "=like", prefixes[-1] + "%"))
|
||||
return domain
|
||||
|
||||
@staticmethod
|
||||
def _parse_domain(formula):
|
||||
try:
|
||||
parsed = ast.literal_eval((formula or "").strip())
|
||||
except (ValueError, SyntaxError) as exc:
|
||||
raise UserError(_("Invalid domain formula: %s", formula)) from exc
|
||||
if not isinstance(parsed, (list, tuple)):
|
||||
raise UserError(_("Domain formula must be a list: %s", formula))
|
||||
return list(parsed)
|
||||
|
||||
|
||||
class DnReportLine(models.Model):
|
||||
_name = "dn.report.line"
|
||||
_description = "DN Report Line"
|
||||
_order = "sequence, id"
|
||||
|
||||
report_id = fields.Many2one("dn.report", required=True, ondelete="cascade")
|
||||
parent_id = fields.Many2one("dn.report.line", ondelete="cascade")
|
||||
children_ids = fields.One2many("dn.report.line", "parent_id")
|
||||
name = fields.Char(required=True, translate=True)
|
||||
code = fields.Char(help="Line code, unique within a report.")
|
||||
sequence = fields.Integer(default=10)
|
||||
is_total = fields.Boolean(default=False)
|
||||
expression_ids = fields.One2many("dn.report.expression", "report_line_id")
|
||||
|
||||
|
||||
class DnReportExpression(models.Model):
|
||||
_name = "dn.report.expression"
|
||||
_description = "DN Report Expression (calculation unit)"
|
||||
_order = "sequence, id"
|
||||
|
||||
report_line_id = fields.Many2one("dn.report.line", required=True, ondelete="cascade")
|
||||
label = fields.Char(help="Name used by aggregation formulas.")
|
||||
formula = fields.Text(required=True)
|
||||
engine = fields.Selection(
|
||||
[
|
||||
("domain", "Domain on Journal Items"),
|
||||
("account_codes", "Account Code Prefixes"),
|
||||
("aggregation", "Aggregation"),
|
||||
("text", "Text"),
|
||||
],
|
||||
default="domain",
|
||||
required=True,
|
||||
)
|
||||
sequence = fields.Integer(default=10)
|
||||
figure_type = fields.Selection(
|
||||
[("monetary", "Monetary"), ("integer", "Integer"), ("text", "Text")],
|
||||
default="monetary",
|
||||
)
|
||||
|
||||
|
||||
class DnReportColumn(models.Model):
|
||||
_name = "dn.report.column"
|
||||
_description = "DN Report Column"
|
||||
_order = "sequence, id"
|
||||
|
||||
report_id = fields.Many2one("dn.report", required=True, ondelete="cascade")
|
||||
name = fields.Char(required=True, translate=True)
|
||||
sequence = fields.Integer(default=10)
|
||||
52
accountant_cn/security/account_groups.xml
Normal file
52
accountant_cn/security/account_groups.xml
Normal file
@@ -0,0 +1,52 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<odoo>
|
||||
|
||||
<!--
|
||||
Groups: what Enterprise adds on top of Community.
|
||||
|
||||
Odoo 20 Community defines the accounting groups like this
|
||||
(account/security/account_security.xml):
|
||||
|
||||
group_account_invoice -> base.group_user
|
||||
group_account_readonly -> base.group_user
|
||||
group_account_basic -> group_account_invoice
|
||||
group_account_user -> group_account_basic + group_account_readonly
|
||||
group_account_manager -> group_account_invoice (chain stops here)
|
||||
|
||||
That last line is the problem. `group_account_manager` implies only
|
||||
`group_account_invoice`, so a user who is a full accounting
|
||||
administrator does NOT get:
|
||||
|
||||
* `group_account_readonly`, which every report and every Accounting
|
||||
menu entry in Community is gated on
|
||||
* `group_account_basic`, which the dashboard menu requires
|
||||
|
||||
Result on plain Community: the Accounting app opens and immediately
|
||||
shows "You do not have access to the Accounting Dashboard", and the
|
||||
report entries disappear from the menu.
|
||||
|
||||
Enterprise fixes this in two steps:
|
||||
* accountant : manager -> (remove invoice) + account_user
|
||||
* account_accountant: manager -> + account_basic
|
||||
|
||||
We reproduce the same end state in one place: manager implies
|
||||
`group_account_user`, which itself implies basic + readonly. This is
|
||||
pure group wiring, no Enterprise code involved.
|
||||
-->
|
||||
<record id="account.group_account_manager" model="res.groups">
|
||||
<field name="implied_ids" eval="[(4, ref('account.group_account_user'))]"/>
|
||||
</record>
|
||||
|
||||
<!-- Administrators get the full accounting feature set, the way Enterprise
|
||||
grants it to `base.user_admin` / `base.user_root`. Without this the
|
||||
person installing the modules cannot see the reports they just
|
||||
installed. -->
|
||||
<record id="base.user_admin" model="res.users">
|
||||
<field name="group_ids" eval="[(4, ref('account.group_account_user'))]"/>
|
||||
</record>
|
||||
|
||||
<record id="base.user_root" model="res.users">
|
||||
<field name="group_ids" eval="[(4, ref('account.group_account_user'))]"/>
|
||||
</record>
|
||||
|
||||
</odoo>
|
||||
5
accountant_cn/security/ir.access-accounting.csv
Normal file
5
accountant_cn/security/ir.access-accounting.csv
Normal file
@@ -0,0 +1,5 @@
|
||||
id,name,model_id,group_id/id,operation,domain
|
||||
access_dn_fiscal_year,dn.fiscal.year,dn.fiscal.year,account.group_account_manager,crud,
|
||||
access_dn_fiscal_year_closing,dn.fiscal.year.closing,dn.fiscal.year.closing,account.group_account_manager,crud,
|
||||
access_dn_fiscal_year_closing_line,dn.fiscal.year.closing.line,dn.fiscal.year.closing.line,account.group_account_manager,crud,
|
||||
access_dn_lock_date_wizard,dn.lock.date.wizard,dn.lock.date.wizard,account.group_account_manager,crud,
|
||||
|
9
accountant_cn/security/ir.access-audit.csv
Normal file
9
accountant_cn/security/ir.access-audit.csv
Normal file
@@ -0,0 +1,9 @@
|
||||
id,name,model_id:id,group_id:id,operation,domain
|
||||
access_dn_audit_return_user,dn.audit.return user,model_dn_audit_return,account.group_account_user,crud,
|
||||
access_dn_audit_return_readonly,dn.audit.return readonly,model_dn_audit_return,account.group_account_readonly,r,
|
||||
access_dn_audit_check_user,dn.audit.check user,model_dn_audit_check,account.group_account_user,crud,
|
||||
access_dn_audit_check_readonly,dn.audit.check readonly,model_dn_audit_check,account.group_account_readonly,r,
|
||||
access_dn_audit_cycle_user,dn.audit.cycle user,model_dn_audit_cycle,account.group_account_user,crud,
|
||||
access_dn_audit_cycle_readonly,dn.audit.cycle readonly,model_dn_audit_cycle,account.group_account_readonly,r,
|
||||
access_dn_audit_check_template_user,dn.audit.check.template user,model_dn_audit_check_template,account.group_account_user,crud,
|
||||
access_dn_audit_check_template_readonly,dn.audit.check.template readonly,model_dn_audit_check_template,account.group_account_readonly,r,
|
||||
|
3
accountant_cn/security/ir.access-bank_rec.csv
Normal file
3
accountant_cn/security/ir.access-bank_rec.csv
Normal file
@@ -0,0 +1,3 @@
|
||||
id,name,model_id,group_id/id,operation,domain
|
||||
access_dn_bank_rec_wizard,dn.bank.rec.wizard,dn.bank.rec.wizard,account.group_account_user,crud,
|
||||
access_dn_bank_rec_candidate,dn.bank.rec.candidate,dn.bank.rec.candidate,account.group_account_user,crud,
|
||||
|
9
accountant_cn/security/ir.access-fr.csv
Normal file
9
accountant_cn/security/ir.access-fr.csv
Normal file
@@ -0,0 +1,9 @@
|
||||
id,name,model_id,group_id/id,operation,domain
|
||||
access_dn_fr_read,dn.fr read,dn.fr,account.group_account_readonly,r,
|
||||
access_dn_fr_manager,dn.fr manage,dn.fr,account.group_account_manager,crud,
|
||||
access_dn_fr_line_read,dn.fr.line read,dn.fr.line,account.group_account_readonly,r,
|
||||
access_dn_fr_line_manager,dn.fr.line manage,dn.fr.line,account.group_account_manager,crud,
|
||||
access_dn_fr_expr_read,dn.fr.expression read,dn.fr.expression,account.group_account_readonly,r,
|
||||
access_dn_fr_expr_manager,dn.fr.expression manage,dn.fr.expression,account.group_account_manager,crud,
|
||||
access_dn_fr_external_read,dn.fr.external.value read,dn.fr.external.value,account.group_account_readonly,r,
|
||||
access_dn_fr_external_manager,dn.fr.external.value manage,dn.fr.external.value,account.group_account_manager,crud,
|
||||
|
7
accountant_cn/security/ir.access-loans.csv
Normal file
7
accountant_cn/security/ir.access-loans.csv
Normal file
@@ -0,0 +1,7 @@
|
||||
id,name,model_id:id,group_id:id,operation,domain
|
||||
access_dn_loan_readonly,dn.loan readonly,model_dn_loan,account.group_account_readonly,r,
|
||||
access_dn_loan_manager,dn.loan manager,model_dn_loan,account.group_account_manager,crud,
|
||||
access_dn_loan_line_readonly,dn.loan.line readonly,model_dn_loan_line,account.group_account_readonly,r,
|
||||
access_dn_loan_line_manager,dn.loan.line manager,model_dn_loan_line,account.group_account_manager,crud,
|
||||
access_dn_loan_compute_wizard,dn.loan.compute.wizard,model_dn_loan_compute_wizard,account.group_account_manager,crud,
|
||||
access_dn_loan_close_wizard,dn.loan.close.wizard,model_dn_loan_close_wizard,account.group_account_manager,crud,
|
||||
|
9
accountant_cn/security/ir.access-reports_core.csv
Normal file
9
accountant_cn/security/ir.access-reports_core.csv
Normal file
@@ -0,0 +1,9 @@
|
||||
id,name,model_id,group_id/id,operation,domain
|
||||
access_dn_report_readonly,dn.report readonly,dn.report,account.group_account_readonly,r,
|
||||
access_dn_report_manager,dn.report manager,dn.report,account.group_account_manager,crud,
|
||||
access_dn_report_line_readonly,dn.report.line readonly,dn.report.line,account.group_account_readonly,r,
|
||||
access_dn_report_line_manager,dn.report.line manager,dn.report.line,account.group_account_manager,crud,
|
||||
access_dn_report_expression_readonly,dn.report.expression readonly,dn.report.expression,account.group_account_readonly,r,
|
||||
access_dn_report_expression_manager,dn.report.expression manager,dn.report.expression,account.group_account_manager,crud,
|
||||
access_dn_report_column_readonly,dn.report.column readonly,dn.report.column,account.group_account_readonly,r,
|
||||
access_dn_report_column_manager,dn.report.column manager,dn.report.column,account.group_account_manager,crud,
|
||||
|
BIN
accountant_cn/static/description/icon.png
Normal file
BIN
accountant_cn/static/description/icon.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 2.2 KiB |
44
accountant_cn/static/src/js/dn_fr_filter_comparison.js
Normal file
44
accountant_cn/static/src/js/dn_fr_filter_comparison.js
Normal file
@@ -0,0 +1,44 @@
|
||||
/** @odoo-module **/
|
||||
/**
|
||||
* Comparison filter for the report control panel.
|
||||
*
|
||||
* Same shape as enterprise: a `btn btn-secondary` labelled "Comparison" with
|
||||
* the selected period appended, backed by a Dropdown of choices. Keeps the
|
||||
* control panel consistent with the date filter next to it.
|
||||
*/
|
||||
import { Component } from "@odoo/owl";
|
||||
import { Dropdown } from "@web/core/dropdown/dropdown";
|
||||
import { DropdownItem } from "@web/core/dropdown/dropdown_item";
|
||||
import { _t } from "@web/core/l10n/translation";
|
||||
|
||||
export class DnFrComparisonFilter extends Component {
|
||||
static template = "dn_financial_reports.DnFrComparisonFilter";
|
||||
static components = { Dropdown, DropdownItem };
|
||||
|
||||
get options() {
|
||||
return [
|
||||
{ value: "", label: _t("No Comparison") },
|
||||
{ value: "previous_period", label: _t("Previous Period") },
|
||||
{ value: "previous_year", label: _t("Previous Year") },
|
||||
{ value: "both", label: _t("Previous Period + Previous Year") },
|
||||
];
|
||||
}
|
||||
|
||||
get labelComparison() {
|
||||
return _t("Comparison");
|
||||
}
|
||||
|
||||
get selectedLabel() {
|
||||
const value = this.view.comparison();
|
||||
const found = this.options.find((o) => o.value === value);
|
||||
return found ? found.label : _t("No Comparison");
|
||||
}
|
||||
|
||||
select(value) {
|
||||
this.view.setComparison(value);
|
||||
}
|
||||
|
||||
get view() {
|
||||
return this.env.dnFrView;
|
||||
}
|
||||
}
|
||||
21
accountant_cn/static/src/js/dn_fr_filter_comparison.xml
Normal file
21
accountant_cn/static/src/js/dn_fr_filter_comparison.xml
Normal file
@@ -0,0 +1,21 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<templates xml:space="preserve">
|
||||
<t t-name="dn_financial_reports.DnFrComparisonFilter">
|
||||
<Dropdown menuClass="'account_report_filter comparison'">
|
||||
<button class="btn btn-secondary">
|
||||
<t t-out="this.labelComparison"/>
|
||||
<t t-if="this.view.comparison()">
|
||||
<span>: </span><t t-out="this.selectedLabel"/>
|
||||
</t>
|
||||
</button>
|
||||
<t t-set-slot="content">
|
||||
<t t-foreach="this.options" t-as="option" t-key="option.value">
|
||||
<DropdownItem onSelected="() => this.select(option.value)"
|
||||
class="{ 'selected': this.view.comparison() === option.value }">
|
||||
<t t-out="option.label"/>
|
||||
</DropdownItem>
|
||||
</t>
|
||||
</t>
|
||||
</Dropdown>
|
||||
</t>
|
||||
</templates>
|
||||
88
accountant_cn/static/src/js/dn_fr_filter_date.js
Normal file
88
accountant_cn/static/src/js/dn_fr_filter_date.js
Normal file
@@ -0,0 +1,88 @@
|
||||
/** @odoo-module **/
|
||||
/**
|
||||
* Date filter for the report control panel.
|
||||
*
|
||||
* Enterprise renders this as a `btn btn-secondary` carrying a calendar icon
|
||||
* and the human-readable period ("January 2026", "This Year", ...), with a
|
||||
* Dropdown of periods behind it. Reproducing that shape — rather than a bare
|
||||
* `<input type="date">` with a `<label>` above it — is what makes the control
|
||||
* panel read as an Odoo report instead of a custom form.
|
||||
*
|
||||
* The actual dates live on the parent view (shared through the sub-env), so
|
||||
* this component only formats and offers the choices; it never owns state.
|
||||
*/
|
||||
import { Component } from "@odoo/owl";
|
||||
import { Dropdown } from "@web/core/dropdown/dropdown";
|
||||
import { DropdownItem } from "@web/core/dropdown/dropdown_item";
|
||||
import { _t } from "@web/core/l10n/translation";
|
||||
|
||||
// Luxon is loaded globally by Odoo's web assets and its default locale is set
|
||||
// to the session language, so `toLocaleString` renders "2026年1月" in zh_CN and
|
||||
// "January 2026" in en_US. Using it instead of a hard-coded English month list
|
||||
// is what keeps the control-panel button in the user's language.
|
||||
const DateTime = luxon.DateTime;
|
||||
|
||||
export class DnFrDateFilter extends Component {
|
||||
static template = "dn_financial_reports.DnFrDateFilter";
|
||||
static components = { Dropdown, DropdownItem };
|
||||
|
||||
/** Presets the reviewer can pick without typing two dates. */
|
||||
get presets() {
|
||||
const now = new Date();
|
||||
const y = now.getFullYear();
|
||||
const m = now.getMonth();
|
||||
const iso = (d) => {
|
||||
const pad = (n) => String(n).padStart(2, "0");
|
||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
|
||||
};
|
||||
return [
|
||||
{ key: "this_month", label: _t("This Month"),
|
||||
from: iso(new Date(y, m, 1)), to: iso(new Date(y, m + 1, 0)) },
|
||||
{ key: "last_month", label: _t("Last Month"),
|
||||
from: iso(new Date(y, m - 1, 1)), to: iso(new Date(y, m, 0)) },
|
||||
{ key: "this_year", label: _t("This Year"),
|
||||
from: iso(new Date(y, 0, 1)), to: iso(new Date(y, 11, 31)) },
|
||||
{ key: "last_year", label: _t("Last Year"),
|
||||
from: iso(new Date(y - 1, 0, 1)), to: iso(new Date(y - 1, 11, 31)) },
|
||||
{ key: "today", label: _t("Today"),
|
||||
from: iso(now), to: iso(now) },
|
||||
];
|
||||
}
|
||||
|
||||
/** Human description shown on the button, in the session language. */
|
||||
get description() {
|
||||
const from = this.view.dateFrom();
|
||||
const to = this.view.dateTo();
|
||||
if (!from || !to) return _t("Custom Dates");
|
||||
const start = DateTime.fromISO(from);
|
||||
const end = DateTime.fromISO(to);
|
||||
const short = (d) => d.toLocaleString({ month: "short", day: "numeric" });
|
||||
if (from === to) {
|
||||
return start.toLocaleString(luxon.DateTime.DATE_FULL);
|
||||
}
|
||||
if (this.isFullMonth(from, to)) {
|
||||
// "2026年1月" / "January 2026" — no day, because the whole month
|
||||
// is selected. This mirrors the enterprise date button exactly.
|
||||
return start.toLocaleString({ month: "long", year: "numeric" });
|
||||
}
|
||||
return `${short(start)} – ${short(end)}, ${end.year}`;
|
||||
}
|
||||
|
||||
isFullMonth(from, to) {
|
||||
if (!from || !to) return false;
|
||||
const start = new Date(from + "T00:00:00");
|
||||
const end = new Date(to + "T00:00:00");
|
||||
return start.getDate() === 1 &&
|
||||
end.getDate() === new Date(end.getFullYear(), end.getMonth() + 1, 0).getDate() &&
|
||||
start.getFullYear() === end.getFullYear() &&
|
||||
start.getMonth() === end.getMonth();
|
||||
}
|
||||
|
||||
get view() {
|
||||
return this.env.dnFrView;
|
||||
}
|
||||
|
||||
applyPreset(preset) {
|
||||
this.view.setDates(preset.from, preset.to);
|
||||
}
|
||||
}
|
||||
29
accountant_cn/static/src/js/dn_fr_filter_date.xml
Normal file
29
accountant_cn/static/src/js/dn_fr_filter_date.xml
Normal file
@@ -0,0 +1,29 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<templates xml:space="preserve">
|
||||
<t t-name="dn_financial_reports.DnFrDateFilter">
|
||||
<Dropdown menuClass="'account_report_filter date'">
|
||||
<button class="btn btn-secondary">
|
||||
<i class="oi oi-filled me-1" data-icon="calendar_today"/>
|
||||
<t t-out="this.description"/>
|
||||
</button>
|
||||
<t t-set-slot="content">
|
||||
<t t-foreach="this.presets" t-as="preset" t-key="preset.key">
|
||||
<DropdownItem onSelected="() => this.applyPreset(preset)"
|
||||
class="{ 'date_filter': true, 'selected': this.view.dateFrom() === preset.from and this.view.dateTo() === preset.to }">
|
||||
<span t-out="preset.label"/>
|
||||
</DropdownItem>
|
||||
</t>
|
||||
<div class="dropdown-divider"/>
|
||||
<div class="dropdown-item date d-flex align-items-center gap-2">
|
||||
<input type="date" class="o_input form-control form-control-sm"
|
||||
t-att-value="this.view.dateFrom()"
|
||||
t-on-change="(ev) => this.view.setDates(ev.target.value, this.view.dateTo())"/>
|
||||
<span t-out="'→'"/>
|
||||
<input type="date" class="o_input form-control form-control-sm"
|
||||
t-att-value="this.view.dateTo()"
|
||||
t-on-change="(ev) => this.view.setDates(this.view.dateFrom(), ev.target.value)"/>
|
||||
</div>
|
||||
</t>
|
||||
</Dropdown>
|
||||
</t>
|
||||
</templates>
|
||||
47
accountant_cn/static/src/js/dn_fr_header.js
Normal file
47
accountant_cn/static/src/js/dn_fr_header.js
Normal file
@@ -0,0 +1,47 @@
|
||||
/** @odoo-module **/
|
||||
/**
|
||||
* DN Financial Reports — table header.
|
||||
*
|
||||
* A separate component from the body, for the same reason the enterprise report
|
||||
* has one: the header is sticky, and re-rendering it on every fold would make
|
||||
* the whole page flicker. Here it renders once per payload and stays put.
|
||||
*
|
||||
* The header is also where the column widths are decided. There is no
|
||||
* `<colgroup>` on purpose — see `dn_fr_view.scss` — because `<col>` widths
|
||||
* override the hints given here, and the hint is the only mechanism that makes
|
||||
* the amount columns sit next to the label column instead of at the far right
|
||||
* edge of a stretched table:
|
||||
*
|
||||
* 1. the label header asks for `width: 100%`, so it absorbs all slack;
|
||||
* 2. every amount header asks for `width: 1%` plus a `min-width` floor, so it
|
||||
* shrinks to exactly its content — or to the floor when the content is
|
||||
* narrower than the floor.
|
||||
*/
|
||||
import { Component, t, useProps } from "@odoo/owl";
|
||||
|
||||
export class DnFrHeader extends Component {
|
||||
static template = "dn_financial_reports.DnFrHeader";
|
||||
|
||||
props = useProps({
|
||||
columns: t.array(),
|
||||
labels: t.object(),
|
||||
isLedger: t.boolean().optional(false),
|
||||
});
|
||||
|
||||
/**
|
||||
* The dates under a column title.
|
||||
*
|
||||
* Only one of the two ends is always present: a balance-sheet column has a
|
||||
* date_to but no date_from (it is a point in time), so printing
|
||||
* "— 2026-12-31" with a leading dash reads like a missing value. Emitting
|
||||
* whichever ends exist avoids that.
|
||||
*/
|
||||
formatRange(column) {
|
||||
const from = column.date_from || "";
|
||||
const to = column.date_to || "";
|
||||
if (from && to) {
|
||||
return `${from} — ${to}`;
|
||||
}
|
||||
return from || to;
|
||||
}
|
||||
}
|
||||
33
accountant_cn/static/src/js/dn_fr_header.xml
Normal file
33
accountant_cn/static/src/js/dn_fr_header.xml
Normal file
@@ -0,0 +1,33 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<templates xml:space="preserve">
|
||||
<t t-name="dn_financial_reports.DnFrHeader">
|
||||
<!-- `sticky` is the enterprise class name and this stylesheet defines
|
||||
it, so the header stays pinned while the card scrolls. `dn_fr_label_col`
|
||||
asks for 100% of the remaining width and `dn_fr_amount_col` for 1%,
|
||||
which is the only reliable way to get "label takes the rest,
|
||||
amounts take their content width" out of `table-layout: auto`. -->
|
||||
<thead class="dn_fr_thead sticky">
|
||||
<tr t-if="this.props.isLedger" data-id="column_headers_row">
|
||||
<th class="dn_fr_label_col" t-out="this.props.labels.ledgerHeader"/>
|
||||
<th class="dn_fr_amount_col column_header numeric-header" t-out="this.props.labels.debit"/>
|
||||
<th class="dn_fr_amount_col column_header numeric-header" t-out="this.props.labels.credit"/>
|
||||
<th class="dn_fr_amount_col column_header numeric-header" t-out="this.props.labels.cumulativeBalance"/>
|
||||
</tr>
|
||||
<tr t-else="" data-id="column_headers_row">
|
||||
<th class="dn_fr_label_col" t-out="this.props.labels.accountHeader"/>
|
||||
<t t-foreach="this.props.columns" t-as="column" t-key="column.key">
|
||||
<th class="dn_fr_amount_col column_header numeric-header">
|
||||
<div t-out="column.label"/>
|
||||
<!-- Second line: the period the column covers. Only
|
||||
rendered when the server actually sent a range, so
|
||||
a single-column report does not get an empty
|
||||
sub-heading that doubles the header height. -->
|
||||
<div t-if="column.date_from or column.date_to"
|
||||
class="dn_fr_subhead fw-normal"
|
||||
t-out="this.formatRange(column)"/>
|
||||
</th>
|
||||
</t>
|
||||
</tr>
|
||||
</thead>
|
||||
</t>
|
||||
</templates>
|
||||
72
accountant_cn/static/src/js/dn_fr_line.js
Normal file
72
accountant_cn/static/src/js/dn_fr_line.js
Normal file
@@ -0,0 +1,72 @@
|
||||
/** @odoo-module **/
|
||||
/**
|
||||
* DN Financial Reports — one report line.
|
||||
*
|
||||
* The line is a component so that folding one section does not re-render the
|
||||
* whole table: the row reads its own `DnFrLine` model instance, and Owl only
|
||||
* repaints the rows whose model object actually changed.
|
||||
*
|
||||
* The label cell is inline rather than a sub-component like the enterprise
|
||||
* `AccountReportLineName`. Enterprise needs that extra layer because it also
|
||||
* hosts chatter annotations, caret menus and account status badges; none of
|
||||
* that exists here, so a sub-component would only add a render boundary with
|
||||
* nothing to gain. The amount cells *are* separate components — there are many
|
||||
* of them, and they change independently.
|
||||
*/
|
||||
import { Component, computed, t, useProps } from "@odoo/owl";
|
||||
import { formatFloat } from "@web/views/fields/formatters";
|
||||
import { DnFrLineCell } from "./dn_fr_line_cell";
|
||||
|
||||
export class DnFrLine extends Component {
|
||||
static template = "dn_financial_reports.DnFrLine";
|
||||
static components = { DnFrLineCell };
|
||||
|
||||
props = useProps({
|
||||
line: t.object(),
|
||||
labels: t.object(),
|
||||
unfolded: t.boolean().optional(false),
|
||||
isLedger: t.boolean().optional(false),
|
||||
onToggle: t.function(),
|
||||
onAction: t.function(),
|
||||
});
|
||||
|
||||
/**
|
||||
* Recomputed only when this row's own fold state changes.
|
||||
*
|
||||
* The fold state is a prop rather than something the row reads off the
|
||||
* model, so toggling one section re-runs the class computation for that
|
||||
* row alone instead of for every row of the table.
|
||||
*/
|
||||
classes = computed(() => this.props.line.lineClasses(this.props.unfolded));
|
||||
|
||||
get line() {
|
||||
return this.props.line;
|
||||
}
|
||||
|
||||
toggle() {
|
||||
this.props.onToggle(this.props.line);
|
||||
}
|
||||
|
||||
runAction(ev) {
|
||||
ev.preventDefault();
|
||||
ev.stopPropagation();
|
||||
this.props.onAction(this.props.line);
|
||||
}
|
||||
|
||||
/**
|
||||
* A detail row's figures are already plain numbers; format them the same
|
||||
* way a normal cell does so the columns stay aligned. An empty figure
|
||||
* renders as an empty cell rather than "0.00": on a ledger, a line with no
|
||||
* debit has no debit, and printing a zero would imply it does.
|
||||
*/
|
||||
detailValue(key) {
|
||||
const value = this.line.detail ? this.line.detail[key] : undefined;
|
||||
if (value === null || value === undefined || value === "") {
|
||||
return "";
|
||||
}
|
||||
if (!value) {
|
||||
return "";
|
||||
}
|
||||
return formatFloat(Number(value), { digits: [16, 2] });
|
||||
}
|
||||
}
|
||||
75
accountant_cn/static/src/js/dn_fr_line.xml
Normal file
75
accountant_cn/static/src/js/dn_fr_line.xml
Normal file
@@ -0,0 +1,75 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<templates xml:space="preserve">
|
||||
<t t-name="dn_financial_reports.DnFrLine">
|
||||
<!-- ==========================================================
|
||||
A journal-item detail row (ledger expansion).
|
||||
The date, entry number, label and partner share the first
|
||||
cell: they are one piece of information, and splitting them
|
||||
across columns would leave three near-empty columns on
|
||||
every other report.
|
||||
========================================================== -->
|
||||
<tr t-if="this.line.detail" data-id="line" t-att-class="this.classes()">
|
||||
<td data-id="line_name" class="line_name">
|
||||
<span class="text-muted me-2" t-out="this.line.detail.date"/>
|
||||
<span class="fw-semibold me-2" t-out="this.line.detail.move_name"/>
|
||||
<span t-out="this.line.detail.label"/>
|
||||
<span t-if="this.line.detail.partner" class="text-muted ms-2"
|
||||
t-out="'· ' + this.line.detail.partner"/>
|
||||
</td>
|
||||
<td data-id="line_cell" class="line_cell numeric text-end"
|
||||
t-out="this.detailValue('debit')"/>
|
||||
<td data-id="line_cell" class="line_cell numeric text-end line_cell_odd"
|
||||
t-out="this.detailValue('credit')"/>
|
||||
<td data-id="line_cell" class="line_cell numeric text-end"
|
||||
t-out="this.detailValue('cumulative')"/>
|
||||
</tr>
|
||||
|
||||
<!-- ==========================================================
|
||||
A summary / account row.
|
||||
========================================================== -->
|
||||
<tr t-else="" data-id="line" t-att-class="this.classes()">
|
||||
<!-- Name column. A foldable section keeps its arrow in a fixed
|
||||
20px box so that labels line up whether or not they can be
|
||||
unfolded; enterprise calls this `.btn_foldable` and the
|
||||
geometry below is identical. -->
|
||||
<td data-id="line_name"
|
||||
t-att-class="this.line.unfoldable ? 'line_name unfoldable' : 'line_name'"
|
||||
tabindex="-1"
|
||||
t-on-click="() => this.toggle()">
|
||||
|
||||
<i t-if="this.line.unfoldable"
|
||||
data-id="btn_foldable"
|
||||
class="btn btn_foldable oi"
|
||||
tabindex="-1"
|
||||
t-att-data-icon="this.props.unfolded ? 'arrow_drop_down' : 'arrow_right'"/>
|
||||
|
||||
<span t-if="this.line.showCode"
|
||||
class="text-muted me-2" t-out="this.line.code"/>
|
||||
|
||||
<a t-if="this.line.hasAction"
|
||||
class="clickable cursor-pointer"
|
||||
tabindex="-1"
|
||||
t-on-click="(ev) => this.runAction(ev)"
|
||||
t-out="this.line.label"/>
|
||||
<t t-else="" t-out="this.line.label"/>
|
||||
|
||||
<!-- Drill-down affordance, revealed on row hover exactly like
|
||||
the enterprise `.btn_action`. It is a hover-only button,
|
||||
not a permanent arrow, so an accountant reading a column
|
||||
of figures is not distracted by 300 icons. -->
|
||||
<button t-if="this.line.hasAction"
|
||||
data-id="btn_action"
|
||||
class="btn btn_action"
|
||||
tabindex="-1"
|
||||
t-att-title="this.props.labels.viewDetails"
|
||||
t-on-click="(ev) => this.runAction(ev)">
|
||||
<i class="fa fa-arrow-right"/>
|
||||
</button>
|
||||
</td>
|
||||
|
||||
<t t-foreach="this.line.cells" t-as="cell" t-key="cell.key">
|
||||
<DnFrLineCell cell="cell"/>
|
||||
</t>
|
||||
</tr>
|
||||
</t>
|
||||
</templates>
|
||||
39
accountant_cn/static/src/js/dn_fr_line_cell.js
Normal file
39
accountant_cn/static/src/js/dn_fr_line_cell.js
Normal file
@@ -0,0 +1,39 @@
|
||||
/** @odoo-module **/
|
||||
/**
|
||||
* DN Financial Reports — one amount cell.
|
||||
*
|
||||
* A component of its own rather than an inline `<td>` in the row template, so
|
||||
* that a cell re-renders only when its own value changes. On a balance sheet
|
||||
* with 300 accounts and two comparison columns that is 900 cells; keeping them
|
||||
* as separate components is what stops a fold from repainting all of them.
|
||||
*
|
||||
* All the decisions live in `DnFrCell` (see `dn_fr_model.js`); this component
|
||||
* is deliberately thin and only maps the model onto markup.
|
||||
*/
|
||||
import { Component, computed, t, useProps } from "@odoo/owl";
|
||||
import { COMPARISON_MODE } from "./dn_fr_model";
|
||||
|
||||
export class DnFrLineCell extends Component {
|
||||
static template = "dn_financial_reports.DnFrLineCell";
|
||||
|
||||
props = useProps({
|
||||
cell: t.object(),
|
||||
});
|
||||
|
||||
/** The styling hooks, recomputed only when the value itself changes. */
|
||||
classes = computed(() => {
|
||||
const classes = this.props.cell.cssClass;
|
||||
switch (this.props.cell.comparisonMode) {
|
||||
case COMPARISON_MODE.MUTED:
|
||||
return `${classes} muted`;
|
||||
case COMPARISON_MODE.RED:
|
||||
return `${classes} text-danger`;
|
||||
default:
|
||||
return classes;
|
||||
}
|
||||
});
|
||||
|
||||
get name() {
|
||||
return this.props.cell.name;
|
||||
}
|
||||
}
|
||||
6
accountant_cn/static/src/js/dn_fr_line_cell.xml
Normal file
6
accountant_cn/static/src/js/dn_fr_line_cell.xml
Normal file
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<templates xml:space="preserve">
|
||||
<t t-name="dn_financial_reports.DnFrLineCell">
|
||||
<td data-id="line_cell" t-att-class="this.classes()" t-out="this.name"/>
|
||||
</t>
|
||||
</templates>
|
||||
362
accountant_cn/static/src/js/dn_fr_model.js
Normal file
362
accountant_cn/static/src/js/dn_fr_model.js
Normal file
@@ -0,0 +1,362 @@
|
||||
/** @odoo-module **/
|
||||
/**
|
||||
* DN Financial Reports — row and cell model.
|
||||
*
|
||||
* This file is the structural half of the report renderer. It turns the nested
|
||||
* tree the server sends into the shape the components want to render, and it
|
||||
* owns every decision about *how* a line or a cell should look. The components
|
||||
* in `dn_fr_line.js` / `dn_fr_line_cell.js` then do nothing but read from this
|
||||
* model, which keeps them cheap to re-render and easy to override one at a
|
||||
* time through the component registry.
|
||||
*
|
||||
* Two shape decisions are deliberate and mirror the way enterprise reports are
|
||||
* built, because they are what makes the rendered page look right:
|
||||
*
|
||||
* 1. **Lines are a flat array, not a tree.** A report page is a long list of
|
||||
* rows. Nesting depth survives as `level`, which is all the indentation
|
||||
* CSS needs; parenthood survives as a `parentId`, which is all the fold
|
||||
* logic needs. Deciding what is drawn is then a single pass over an
|
||||
* already-ordered array instead of a recursive walk on every render.
|
||||
* 2. **A line owns a `cells` array, one entry per amount column.** Columns
|
||||
* are data (they change with the comparison filter), so they cannot be
|
||||
* hard-coded in a template. Each cell carries its own figure type and
|
||||
* sign semantics, which is what lets a loss render in the danger colour
|
||||
* and a zero render muted without any conditional logic in the template.
|
||||
*
|
||||
* **The model is immutable from the view's point of view.** Fold state is not
|
||||
* stored here: it lives in the view as a reactive `{lineId: folded}` map. That
|
||||
* split matters, because mutating a deeply-nested reactive tree is what makes
|
||||
* Owl re-render every row whenever one section is folded. With the fold state
|
||||
* separate, the view re-renders, the fold map decides which rows are drawn, and
|
||||
* each row's `unfolded` prop changes only for the row that was clicked.
|
||||
*/
|
||||
import { formatFloat } from "@web/views/fields/formatters";
|
||||
|
||||
/** Column figure types, matching what the server sends per expression. */
|
||||
export const FIGURE_TYPE = {
|
||||
MONETARY: "monetary",
|
||||
PERCENT: "percent",
|
||||
RATIO: "ratio",
|
||||
INTEGER: "integer",
|
||||
FLOAT: "float",
|
||||
STRING: "string",
|
||||
DATE: "date",
|
||||
};
|
||||
|
||||
/**
|
||||
* Numeric types are end-aligned and go through `formatFloat`.
|
||||
*
|
||||
* `ratio` belongs here: the server uses it for a plain quotient that has no
|
||||
* percent sign, so it must be right-aligned like any other figure but must not
|
||||
* get the `%` suffix that `percent` gets.
|
||||
*/
|
||||
const NUMERIC_TYPES = new Set([
|
||||
FIGURE_TYPE.MONETARY,
|
||||
FIGURE_TYPE.PERCENT,
|
||||
FIGURE_TYPE.RATIO,
|
||||
FIGURE_TYPE.INTEGER,
|
||||
FIGURE_TYPE.FLOAT,
|
||||
]);
|
||||
|
||||
/**
|
||||
* Comparison semantics for a cell value.
|
||||
*
|
||||
* Enterprise distinguishes three cases: a normal figure, a zero ("muted"), and
|
||||
* a negative figure shown in red. Applying the red only to cells the server did
|
||||
* not already flag as text avoids the classic false positive — a credit-balance
|
||||
* asset account is not an error and must not be painted red.
|
||||
*/
|
||||
export const COMPARISON_MODE = {
|
||||
DEFAULT: "default",
|
||||
MUTED: "muted",
|
||||
RED: "red",
|
||||
};
|
||||
|
||||
/**
|
||||
* One amount in one column of one line.
|
||||
*
|
||||
* Constructed once per line per column and never mutated afterwards, so the
|
||||
* getters can be cheap and the component can trust them. `raw` keeps the
|
||||
* unformatted value so CSV export and drill-downs do not have to re-parse a
|
||||
* localised string.
|
||||
*/
|
||||
export class DnFrCell {
|
||||
/**
|
||||
* @param {object} params
|
||||
* @param {*} params.raw server value (number, string, null)
|
||||
* @param {boolean} params.isText the server says this is a label, not a figure
|
||||
* @param {string} params.figureType one of FIGURE_TYPE
|
||||
* @param {string} params.key the column key (`c0`, `c1`, …)
|
||||
* @param {number} params.index position in the row, used for striping
|
||||
*/
|
||||
constructor({ raw, isText, figureType, key, index }) {
|
||||
this.raw = raw;
|
||||
this.isText = isText;
|
||||
this.figureType = figureType || FIGURE_TYPE.MONETARY;
|
||||
this.key = key;
|
||||
this.index = index;
|
||||
}
|
||||
|
||||
/** True when the value should be rendered right-aligned as a figure. */
|
||||
get isNumeric() {
|
||||
return !this.isText && NUMERIC_TYPES.has(this.figureType);
|
||||
}
|
||||
|
||||
/** True when there is nothing to show at all. */
|
||||
get isEmpty() {
|
||||
return this.raw === null || this.raw === undefined || this.raw === "";
|
||||
}
|
||||
|
||||
/**
|
||||
* The value as it should appear on screen.
|
||||
*
|
||||
* `formatFloat` applies the user's own language parameters (thousands
|
||||
* separator, decimal point) rather than a fixed locale, so a French user
|
||||
* reads 1 234,56 and an English user 1,234.56. The precision is 2 for
|
||||
* amounts and 1 for percentages, which is what enterprise shows.
|
||||
*/
|
||||
get name() {
|
||||
if (this.isEmpty) {
|
||||
return "";
|
||||
}
|
||||
if (!this.isNumeric) {
|
||||
return String(this.raw);
|
||||
}
|
||||
const value = Number(this.raw);
|
||||
if (Number.isNaN(value)) {
|
||||
return String(this.raw);
|
||||
}
|
||||
if (this.figureType === FIGURE_TYPE.PERCENT) {
|
||||
return `${formatFloat(value, { digits: [16, 1] })}%`;
|
||||
}
|
||||
if (this.figureType === FIGURE_TYPE.INTEGER) {
|
||||
// An integer figure (a headcount, a count of entries) must not grow
|
||||
// two decimals: 12 stays 12, not 12.00.
|
||||
return formatFloat(value, { digits: [16, 0] });
|
||||
}
|
||||
return formatFloat(value, { digits: [16, 2] });
|
||||
}
|
||||
|
||||
/** The value used for export and for drill-downs. */
|
||||
get no_format() {
|
||||
return this.isEmpty ? "" : this.raw;
|
||||
}
|
||||
|
||||
/** Zero renders muted, negatives render in the danger colour. */
|
||||
get comparisonMode() {
|
||||
if (!this.isNumeric || this.isEmpty) {
|
||||
return COMPARISON_MODE.DEFAULT;
|
||||
}
|
||||
const value = Number(this.raw);
|
||||
if (!value) {
|
||||
return COMPARISON_MODE.MUTED;
|
||||
}
|
||||
return value < 0 ? COMPARISON_MODE.RED : COMPARISON_MODE.DEFAULT;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extra classes the stylesheet hooks into.
|
||||
*
|
||||
* `line_cell` is the base class every amount cell carries in enterprise,
|
||||
* and the whole cell stylesheet is written as `.line_cell.numeric` /
|
||||
* `.line_cell.date`. Leaving it out would silently drop the right-aligned
|
||||
* gutter and the date centring, so it is added here rather than in the
|
||||
* template — the template writes `t-att-class` and a static `class`
|
||||
* attribute would be overwritten by it.
|
||||
*
|
||||
* `line_cell_odd` is the zebra stripe for every second amount column. It
|
||||
* exists in enterprise too and is the reason a comparison report reads as
|
||||
* pairs of columns instead of one wide block of numbers.
|
||||
*/
|
||||
get cssClass() {
|
||||
const classes = ["line_cell"];
|
||||
if (this.isNumeric) {
|
||||
classes.push("numeric");
|
||||
} else if (this.figureType === FIGURE_TYPE.DATE) {
|
||||
classes.push("date");
|
||||
} else {
|
||||
classes.push("text");
|
||||
}
|
||||
if (this.index % 2) {
|
||||
classes.push("line_cell_odd");
|
||||
}
|
||||
return classes.join(" ");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One rendered row.
|
||||
*
|
||||
* @param {object} payload one node from the server tree
|
||||
* @param {Array<object>} columns the column descriptors
|
||||
* @param {number|null} parentId id of the enclosing line
|
||||
*/
|
||||
export class DnFrLine {
|
||||
constructor(payload, columns, parentId = null) {
|
||||
this.level = payload.level || 0;
|
||||
this.id = payload.id;
|
||||
this.parentId = parentId;
|
||||
this.code = payload.code || "";
|
||||
this.label = payload.name || "";
|
||||
this.isTotal = Boolean(payload.is_total);
|
||||
this.actionId = payload.action_id || false;
|
||||
this.detail = payload.detail || null;
|
||||
|
||||
// `unfoldable` comes from the server, but the child count is the
|
||||
// authority: a pruned tree can leave the flag set on a line whose
|
||||
// children were all dropped for being zero, and showing a fold arrow
|
||||
// that opens onto nothing is worse than showing none.
|
||||
this.childCount = (payload.children || []).length;
|
||||
this.unfoldable = this.childCount > 0;
|
||||
|
||||
this.cells = columns.map(
|
||||
(column, index) =>
|
||||
new DnFrCell({
|
||||
raw: (payload.values || {})[column.key],
|
||||
isText: Boolean((payload.is_text || {})[column.key]),
|
||||
figureType: payload.figure_type,
|
||||
key: column.key,
|
||||
index,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
/** True when the line is a section header drawn as a filled band. */
|
||||
get isLevelZero() {
|
||||
return this.level === 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* The classes that drive the whole visual hierarchy.
|
||||
*
|
||||
* `line_level_N` is the same vocabulary enterprise uses: it carries the
|
||||
* indentation and, for `line_level_0`, the filled band. `total` makes a row
|
||||
* bold, `unfolded` thickens its bottom rule. Keeping these names identical
|
||||
* means the stylesheet can be reasoned about next to the enterprise one.
|
||||
*
|
||||
* `unfolded` is only honoured on a line that actually has children. The
|
||||
* view passes `!folded[id]`, and for a leaf that expression is `true`
|
||||
* (nothing is folded away), which would otherwise make every leaf bold.
|
||||
*
|
||||
* @param {boolean} unfolded whether this section is currently open
|
||||
*/
|
||||
lineClasses(unfolded) {
|
||||
const classes = [`line_level_${this.level}`];
|
||||
if (this.isTotal) {
|
||||
classes.push("total");
|
||||
}
|
||||
if (this.unfoldable) {
|
||||
classes.push("unfoldable");
|
||||
if (unfolded) {
|
||||
classes.push("unfolded");
|
||||
}
|
||||
}
|
||||
if (this.detail) {
|
||||
classes.push("detail");
|
||||
}
|
||||
return classes.join(" ");
|
||||
}
|
||||
|
||||
/**
|
||||
* Indentation is *not* set here.
|
||||
*
|
||||
* Enterprise drives it from the stylesheet, with one rule per
|
||||
* `line_level_N` class, and that turns out to matter: the amount cells
|
||||
* need `padding-right: calc(20px + 0.75rem) !important` to keep the same
|
||||
* gutter as the header, and `!important` in the stylesheet beats a plain
|
||||
* inline `padding-left`. Setting the indent inline would therefore be
|
||||
* silently overridden on the first cell. The class alone is enough.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Report line codes are technical identifiers ("REVENUE", "BS_AP"). Show
|
||||
* them only when they look like real account codes, otherwise the label is
|
||||
* duplicated by an internal key that means nothing to the user.
|
||||
*/
|
||||
get showCode() {
|
||||
if (!this.code) {
|
||||
return false;
|
||||
}
|
||||
return !/^[A-Z][A-Z0-9_]*$/.test(this.code);
|
||||
}
|
||||
|
||||
/** The label cell carries the fold arrow and, on ledger rows, the details. */
|
||||
get hasAction() {
|
||||
return Boolean(this.actionId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the flat line array from the server tree.
|
||||
*
|
||||
* A recursive walk whose *result* is flat: the components never see a nested
|
||||
* structure, they see an ordered array where an ancestor always precedes its
|
||||
* descendants. That ordering is what lets the fold logic be a single forward
|
||||
* pass, and it is also the order the browser paints in.
|
||||
*
|
||||
* @param {Array<object>} tree the `lines` array from the server payload
|
||||
* @param {Array<object>} columns the `columns` array from the same payload
|
||||
* @returns {Array<DnFrLine>}
|
||||
*/
|
||||
export function buildLines(tree, columns) {
|
||||
const lines = [];
|
||||
|
||||
const walk = (nodes, parentId) => {
|
||||
for (const node of nodes || []) {
|
||||
const line = new DnFrLine(node, columns, parentId);
|
||||
lines.push(line);
|
||||
if (node.children && node.children.length) {
|
||||
walk(node.children, line.id);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
walk(tree, null);
|
||||
return lines;
|
||||
}
|
||||
|
||||
/**
|
||||
* The ids that must be folded for a report to start collapsed.
|
||||
*
|
||||
* Only sections below the first level: a balance sheet with every account
|
||||
* expanded is unreadable, but hiding its main headings behind a fold would hide
|
||||
* the structure the report exists to show.
|
||||
*/
|
||||
export function defaultFoldedIds(lines) {
|
||||
const folded = {};
|
||||
for (const line of lines) {
|
||||
if (line.unfoldable && line.level > 0) {
|
||||
folded[line.id] = true;
|
||||
}
|
||||
}
|
||||
return folded;
|
||||
}
|
||||
|
||||
/**
|
||||
* Which lines are drawn, given a fold map.
|
||||
*
|
||||
* One forward pass over the ordered array: an ancestor always appears before
|
||||
* its descendants, so by the time a descendant is reached its parent's
|
||||
* visibility is already known. Lines whose parent chain contains a folded
|
||||
* section are dropped.
|
||||
*
|
||||
* @param {Array<DnFrLine>} lines
|
||||
* @param {Object} folded `{lineId: true}` for every closed section
|
||||
* @returns {Array<DnFrLine>}
|
||||
*/
|
||||
export function visibleLines(lines, folded) {
|
||||
const visible = [];
|
||||
const hidden = new Set();
|
||||
for (const line of lines) {
|
||||
const parentHidden = line.parentId !== null && hidden.has(line.parentId);
|
||||
if (parentHidden) {
|
||||
hidden.add(line.id);
|
||||
continue;
|
||||
}
|
||||
visible.push(line);
|
||||
if (line.unfoldable && folded[line.id]) {
|
||||
hidden.add(line.id);
|
||||
}
|
||||
}
|
||||
return visible;
|
||||
}
|
||||
426
accountant_cn/static/src/js/dn_fr_view.js
Normal file
426
accountant_cn/static/src/js/dn_fr_view.js
Normal file
@@ -0,0 +1,426 @@
|
||||
/** @odoo-module **/
|
||||
/**
|
||||
* DN Financial Reports — report renderer.
|
||||
*
|
||||
* A client action that draws a hierarchical financial report: sticky header,
|
||||
* collapsible line tree, journal-item drill-down, date / comparison / filter
|
||||
* controls and CSV export. Written for Odoo 20's Owl 3 runtime.
|
||||
*
|
||||
* ## Architecture
|
||||
*
|
||||
* The page is split the same way the enterprise report page is, because that
|
||||
* split is what makes the geometry come out right:
|
||||
*
|
||||
* DnFrView control panel, filter bar, scroll container
|
||||
* ├── DnFrHeader sticky <thead>, owns the column widths
|
||||
* └── DnFrLine one <tr> per line, reads a DnFrLine model
|
||||
* └── DnFrLineCell one <td> per amount column
|
||||
*
|
||||
* with `dn_fr_model.js` holding the row/cell model that all three read from.
|
||||
* The dedicated `dn_fr_model.js` / `dn_fr_line.js` / `dn_fr_line_cell.js` files
|
||||
* exist so a report variant can override exactly one of those layers without
|
||||
* copying the rest.
|
||||
*
|
||||
* ## Why the lines are flat
|
||||
*
|
||||
* The server sends a nested tree; `buildLines` flattens it into an ordered
|
||||
* array where an ancestor always precedes its descendants. Fold state lives
|
||||
* here in a reactive `{lineId: folded}` map rather than inside the model, so
|
||||
* folding a section repaints the rows whose visibility actually changed
|
||||
* instead of rebuilding the tree — and the template stays a single
|
||||
* `t-foreach`, which is what keeps a 300-account balance sheet responsive.
|
||||
*/
|
||||
import { registry } from "@web/core/registry";
|
||||
import { Component, onWillStart, proxy, signal, t, useProps } from "@odoo/owl";
|
||||
import { rpc } from "@web/core/network/rpc";
|
||||
import { useService } from "@web/core/utils/hooks";
|
||||
import { useSubEnv } from "@web/owl2/utils";
|
||||
import { _t, translationIsReady } from "@web/core/l10n/translation";
|
||||
import { ControlPanel } from "@web/search/control_panel/control_panel";
|
||||
import { Dropdown } from "@web/core/dropdown/dropdown";
|
||||
import { DropdownItem } from "@web/core/dropdown/dropdown_item";
|
||||
|
||||
import { DnFrHeader } from "./dn_fr_header";
|
||||
import { DnFrLine } from "./dn_fr_line";
|
||||
import { DnFrDateFilter } from "./dn_fr_filter_date";
|
||||
import { DnFrComparisonFilter } from "./dn_fr_filter_comparison";
|
||||
import {
|
||||
buildLines,
|
||||
defaultFoldedIds,
|
||||
visibleLines as computeVisibleLines,
|
||||
} from "./dn_fr_model";
|
||||
|
||||
function isoDate(value) {
|
||||
const pad = (n) => String(n).padStart(2, "0");
|
||||
return `${value.getFullYear()}-${pad(value.getMonth() + 1)}-${pad(value.getDate())}`;
|
||||
}
|
||||
|
||||
export class DnFrView extends Component {
|
||||
static template = "dn_financial_reports.DnFrView";
|
||||
static components = {
|
||||
ControlPanel,
|
||||
Dropdown,
|
||||
DropdownItem,
|
||||
DnFrHeader,
|
||||
DnFrLine,
|
||||
DnFrDateFilter,
|
||||
DnFrComparisonFilter,
|
||||
};
|
||||
|
||||
// Owl 3 no longer reads a static `props`; the schema must be declared
|
||||
// through the `useProps` hook, which also returns the live props object.
|
||||
props = useProps({
|
||||
action: t.object().optional({}),
|
||||
actionId: t.number().optional(0),
|
||||
});
|
||||
|
||||
setup() {
|
||||
this.orm = useService("orm");
|
||||
this.actionService = useService("action");
|
||||
this.notification = useService("notification");
|
||||
this.state = proxy({
|
||||
loading: true,
|
||||
error: null,
|
||||
report: null,
|
||||
// The flat line array from `buildLines`. Kept in state (not
|
||||
// derived in a getter) because the array is the identity Owl uses
|
||||
// to decide whether the table changed at all.
|
||||
lines: [],
|
||||
filtersOpen: false,
|
||||
});
|
||||
|
||||
// Fold state, kept outside the model: `{lineId: true}` for every closed
|
||||
// section. A reactive proxy rather than a plain object so the template
|
||||
// can read `this.folded[line.id]` directly, and kept as **one object
|
||||
// for the lifetime of the component** — replacing it with a new proxy
|
||||
// would not notify Owl, because the property holding it is not itself
|
||||
// reactive.
|
||||
this.folded = proxy({});
|
||||
|
||||
const today = new Date();
|
||||
this.dateFrom = signal(isoDate(new Date(today.getFullYear(), 0, 1)));
|
||||
this.dateTo = signal(isoDate(today));
|
||||
this.comparison = signal("");
|
||||
this.unreconciled = signal(false);
|
||||
this.includeDraft = signal(false);
|
||||
|
||||
const action = this.props.action || {};
|
||||
const params = action.params || {};
|
||||
const context = action.context || {};
|
||||
this.reportId = params.report_id || context.report_id || context.active_id || null;
|
||||
this.reportCode = params.report_code || context.report_code || null;
|
||||
|
||||
// The control-panel filter components read and write the dates and
|
||||
// comparison from here. Sharing the view through the sub-env is the
|
||||
// same pattern the community stock-valuation report uses to let its
|
||||
// filter component drive the parent controller — it keeps a single
|
||||
// source of truth (these signals) instead of copying values around.
|
||||
useSubEnv({ dnFrView: this });
|
||||
|
||||
onWillStart(() => this.initialise());
|
||||
}
|
||||
|
||||
/**
|
||||
* Set both dates from the control-panel filter and reload.
|
||||
* Kept as one method so the preset buttons and the two date inputs always
|
||||
* move together — a range whose end precedes its start is never sent.
|
||||
*/
|
||||
setDates(from, to) {
|
||||
if (from) this.dateFrom.set(from);
|
||||
if (to) this.dateTo.set(to);
|
||||
if (from && to && from <= to) {
|
||||
return this.load();
|
||||
}
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
setComparison(value) {
|
||||
this.comparison.set(value || "");
|
||||
return this.load();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------- lifecycle
|
||||
async initialise() {
|
||||
// The localization service is a proxy that throws while the language
|
||||
// parameters are still loading, and the template formats numbers
|
||||
// during its very first render. Waiting here is what keeps
|
||||
// `formatNumber` callable (otherwise: "parameters are not ready yet").
|
||||
await translationIsReady;
|
||||
try {
|
||||
let reportId = this.reportId;
|
||||
if (!reportId && this.reportCode) {
|
||||
const found = await this.orm.searchRead(
|
||||
"dn.fr", [["code", "=", this.reportCode]], ["id"], { limit: 1 }
|
||||
);
|
||||
reportId = found.length ? found[0].id : null;
|
||||
}
|
||||
if (!reportId) {
|
||||
this.state.error = _t("No report configuration found.");
|
||||
this.state.loading = false;
|
||||
return;
|
||||
}
|
||||
this.reportId = reportId;
|
||||
// Pull the default dates declared by the report definition.
|
||||
const defaults = await this.orm.call(
|
||||
"dn.fr", "get_default_dates", [[reportId]]
|
||||
);
|
||||
if (defaults && defaults.date_from) this.dateFrom.set(defaults.date_from);
|
||||
if (defaults && defaults.date_to) this.dateTo.set(defaults.date_to);
|
||||
await this.load();
|
||||
} catch (error) {
|
||||
this.state.error = error.message || String(error);
|
||||
this.state.loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
async load() {
|
||||
if (!this.reportId) return;
|
||||
this.state.loading = true;
|
||||
this.state.error = null;
|
||||
try {
|
||||
const result = await rpc("/dn/fr/data", {
|
||||
report_id: this.reportId,
|
||||
options: {
|
||||
date_from: this.dateFrom() || undefined,
|
||||
date_to: this.dateTo() || undefined,
|
||||
comparison: this.comparison() || undefined,
|
||||
unreconciled: this.unreconciled(),
|
||||
include_draft: this.includeDraft(),
|
||||
},
|
||||
});
|
||||
if (!result.ok) {
|
||||
this.state.error = result.error || _t("Computation failed.");
|
||||
this.state.report = null;
|
||||
this.state.lines = [];
|
||||
} else {
|
||||
this.state.report = result.data;
|
||||
this.rebuildLines();
|
||||
}
|
||||
} catch (error) {
|
||||
this.state.error = error.message || String(error);
|
||||
} finally {
|
||||
this.state.loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Rebuild the line model array from the payload.
|
||||
*
|
||||
* Called on every successful load. The fold state is reset here on
|
||||
* purpose: the filters changed, so the set of lines changed too, and
|
||||
* keeping stale fold flags would hide rows the user is now looking for.
|
||||
* A report that declares `unfold_all` starts fully open; every other
|
||||
* report starts with its sub-sections collapsed and its top-level
|
||||
* headings visible.
|
||||
*/
|
||||
rebuildLines() {
|
||||
const report = this.state.report;
|
||||
if (!report) {
|
||||
this.state.lines = [];
|
||||
this.applyFoldState({});
|
||||
return;
|
||||
}
|
||||
const lines = buildLines(report.lines || [], report.columns || []);
|
||||
this.state.lines = lines;
|
||||
const unfoldAll = Boolean(report.features && report.features.unfold_all);
|
||||
this.applyFoldState(unfoldAll ? {} : defaultFoldedIds(lines));
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace the fold state in place.
|
||||
*
|
||||
* The `folded` object is mutated rather than reassigned: Owl tracks reads
|
||||
* of its keys, not of the property that holds it, so swapping in a fresh
|
||||
* proxy would leave the table body showing the previous fold state.
|
||||
*/
|
||||
applyFoldState(folded) {
|
||||
for (const id of Object.keys(this.folded)) {
|
||||
delete this.folded[id];
|
||||
}
|
||||
for (const [id, value] of Object.entries(folded)) {
|
||||
this.folded[id] = value;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- getters
|
||||
get report() {
|
||||
return this.state.report;
|
||||
}
|
||||
/** Title shown in the control panel, with a sane fallback while loading. */
|
||||
get reportTitle() {
|
||||
return (this.state.report && this.state.report.name) || _t("Financial Reports");
|
||||
}
|
||||
get ready() {
|
||||
return Boolean(this.state.report) && !this.state.loading;
|
||||
}
|
||||
|
||||
/**
|
||||
* UI strings, resolved through `_t` on every read.
|
||||
*
|
||||
* Owl templates can only be translated through `_t(...)` calls, and those
|
||||
* calls have to live in JavaScript — a literal like `<label>Start Date</label>`
|
||||
* inside the template is never picked up by `i18n export` and therefore can
|
||||
* never be translated. Keeping them in a getter (not a module-level const)
|
||||
* avoids freezing the language at import time.
|
||||
*/
|
||||
get labels() {
|
||||
return {
|
||||
exportCsv: _t("Export CSV"),
|
||||
print: _t("Print"),
|
||||
startDate: _t("Start Date"),
|
||||
endDate: _t("End Date"),
|
||||
comparison: _t("Comparison"),
|
||||
noComparison: _t("No comparison"),
|
||||
previousPeriod: _t("Previous Period"),
|
||||
previousYear: _t("Previous Year"),
|
||||
bothPeriods: _t("Previous Period + Previous Year"),
|
||||
apply: _t("Apply"),
|
||||
moreFilters: _t("More Filters"),
|
||||
includeDraft: _t("Include draft entries"),
|
||||
unreconciledOnly: _t("Unreconciled only"),
|
||||
unfoldAll: _t("Expand All"),
|
||||
foldAll: _t("Collapse All"),
|
||||
reset: _t("Reset"),
|
||||
hideFilters: _t("Hide Filters"),
|
||||
computing: _t("Computing…"),
|
||||
noData: _t("No accounting data for this period."),
|
||||
viewDetails: _t("View details"),
|
||||
ledgerHeader: _t("Date / Entry / Label / Partner"),
|
||||
debit: _t("Debit"),
|
||||
credit: _t("Credit"),
|
||||
cumulativeBalance: _t("Cumulative Balance"),
|
||||
accountHeader: _t("Account / Item"),
|
||||
};
|
||||
}
|
||||
|
||||
get columns() {
|
||||
return this.state.report ? this.state.report.columns : [];
|
||||
}
|
||||
get features() {
|
||||
return (this.state.report && this.state.report.features) || {};
|
||||
}
|
||||
|
||||
/**
|
||||
* The rows actually drawn, given the current fold state.
|
||||
*
|
||||
* A getter over the flat array, so Owl tracks `this.folded` and re-renders
|
||||
* the table body when a section opens or closes. `computeVisibleLines` is
|
||||
* a single forward pass — see the note in `dn_fr_model.js` for why that is
|
||||
* enough.
|
||||
*/
|
||||
get visibleLines() {
|
||||
return computeVisibleLines(this.state.lines, this.folded);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------- actions
|
||||
/**
|
||||
* Fold or unfold one section.
|
||||
*
|
||||
* Writing through the proxy is what notifies Owl; the model objects are
|
||||
* untouched, so the rows that stayed visible are not rebuilt.
|
||||
*/
|
||||
onToggle(line) {
|
||||
if (!line.unfoldable) {
|
||||
return;
|
||||
}
|
||||
this.folded[line.id] = !this.folded[line.id];
|
||||
}
|
||||
|
||||
unfoldAll() {
|
||||
this.applyFoldState({});
|
||||
}
|
||||
|
||||
foldAll() {
|
||||
const folded = {};
|
||||
for (const line of this.state.lines) {
|
||||
if (line.unfoldable) {
|
||||
folded[line.id] = true;
|
||||
}
|
||||
}
|
||||
this.applyFoldState(folded);
|
||||
}
|
||||
|
||||
toggleFilters() {
|
||||
this.state.filtersOpen = !this.state.filtersOpen;
|
||||
}
|
||||
|
||||
async resetFilters() {
|
||||
this.comparison.set("");
|
||||
this.unreconciled.set(false);
|
||||
this.includeDraft.set(false);
|
||||
await this.initialise();
|
||||
}
|
||||
|
||||
async exportCsv() {
|
||||
if (!this.state.report) return;
|
||||
const columnKeys = this.columns.map((c) => c.key);
|
||||
const header = [_t("Account / Item"), ...columnKeys.map(
|
||||
(key, index) => this.columns[index].label
|
||||
)].join(",");
|
||||
const escape = (value) => {
|
||||
const text = value === null || value === undefined ? "" : String(value);
|
||||
return `"${text.replace(/"/g, '""')}"`;
|
||||
};
|
||||
const lines = [header];
|
||||
for (const row of this.visibleLines) {
|
||||
const indent = " ".repeat(row.level || 0);
|
||||
const label = escape(`${indent}${row.code ? row.code + " " : ""}${row.label}`);
|
||||
const cells = row.cells.map((cell) => escape(cell.no_format));
|
||||
lines.push([label, ...cells].join(","));
|
||||
}
|
||||
const blob = new Blob(["\uFEFF" + lines.join("\n")], {
|
||||
type: "text/csv;charset=utf-8;",
|
||||
});
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = document.createElement("a");
|
||||
link.href = url;
|
||||
link.download = `${this.state.report.name || "report"}.csv`;
|
||||
link.click();
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
async printReport() {
|
||||
window.print();
|
||||
}
|
||||
|
||||
async onAction(line) {
|
||||
if (!line.actionId) return;
|
||||
await this.actionService.doAction(line.actionId);
|
||||
}
|
||||
|
||||
get hasComparison() {
|
||||
return this.columns.length > 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Classes for the report table.
|
||||
*
|
||||
* The base is `table table-borderless table-hover mx-auto`, which is the
|
||||
* exact list the enterprise report table carries:
|
||||
*
|
||||
* - `mx-auto` centres the card once the window is wider than the
|
||||
* `min-width: 800px` report. Its containing block is the flex row added
|
||||
* in `dn_fr_view.xml`; without that wrapper `mx-auto` is inert.
|
||||
* - `table-hover` is Bootstrap's row highlight. Our own `tbody tr:hover`
|
||||
* rule is more specific and still wins, so this only keeps the base
|
||||
* contract identical to enterprise.
|
||||
*
|
||||
* `dn_fr_striped` only when there really are comparison columns: the zebra
|
||||
* stripe exists to make pairs of columns separable, so on a single-column
|
||||
* report it would tint half the rows for no reason at all.
|
||||
*/
|
||||
get tableClasses() {
|
||||
const classes = ["table", "table-borderless", "table-hover", "mx-auto", "dn_fr_table"];
|
||||
if (this.hasComparison) {
|
||||
classes.push("dn_fr_striped");
|
||||
}
|
||||
return classes.join(" ");
|
||||
}
|
||||
|
||||
/** True when the report's only meaningful output is journal item detail. */
|
||||
get isLedgerReport() {
|
||||
return this.state.lines.some((line) => line.detail);
|
||||
}
|
||||
}
|
||||
|
||||
registry.category("actions").add("dn_fr_view", DnFrView);
|
||||
529
accountant_cn/static/src/js/dn_fr_view.scss
Normal file
529
accountant_cn/static/src/js/dn_fr_view.scss
Normal file
@@ -0,0 +1,529 @@
|
||||
/* DN Financial Reports — report page styling.
|
||||
*
|
||||
* The visual target is the Odoo Enterprise report page, whose stylesheet lives
|
||||
* in `account_reports/static/src/components/account_report/account_report.scss`.
|
||||
* Odoo Community has no equivalent, so the look has to be reproduced here —
|
||||
* but reproduced *by class name*, not by eye. Every selector below uses the
|
||||
* same vocabulary enterprise uses (`line_name`, `line_cell`, `line_level_N`,
|
||||
* `total`, `unfolded`, `btn_foldable`, `btn_action`, `muted`, `line_cell_odd`),
|
||||
* so the numbers in this file can be checked one-to-one against that file.
|
||||
*
|
||||
* The geometry, and why each constant is what it is:
|
||||
*
|
||||
* 1. **The table is a card, not a grid.** `margin: 24px`, `padding: 24px`,
|
||||
* `1px` border, `0.25rem` radius, `min-width: 800px`, `font-size: 0.8rem`.
|
||||
* Without the padding the figures touch the border; without the radius the
|
||||
* page looks like a spreadsheet dump rather than a report.
|
||||
* 2. **`border-collapse: separate; border-spacing: 0`.** Required — the card
|
||||
* padding only applies to cells under `separate`, and `spacing: 0` removes
|
||||
* the gaps that `separate` normally introduces.
|
||||
* 3. **Numeric cells carry an extra 20px right gutter**
|
||||
* (`padding-right: calc(20px + 0.75rem)`). That 20px is the room the
|
||||
* hover-only row action needs, and it is `!important` in enterprise
|
||||
* because the Bootstrap `td` rule is more specific.
|
||||
* 4. **Row height is computed**:
|
||||
* `0.8rem * body-line-height + 0.5rem + 5px` (two paddings plus the
|
||||
* border), which is what makes a 300-row report read as evenly spaced
|
||||
* lines instead of variable ones.
|
||||
* 5. **`line_level_0` is a filled band** (`$o-gray-300`) with no bottom
|
||||
* border; deeper levels indent 8px per level. Level 1 is special-cased to
|
||||
* the same 20px gutter as level 0 so the first nested level sits under its
|
||||
* heading rather than past it.
|
||||
* 6. **Bold means total.** `total` and `unfolded` are both bold; `unfolded`
|
||||
* additionally darkens its bottom rule, which is what signals "this
|
||||
* section is open" without an icon.
|
||||
* 7. **Row actions are invisible until hover**, driven by a CSS custom
|
||||
* property (`--row-action-opacity`) so one `:hover` rule can reveal every
|
||||
* affordance in the row at once.
|
||||
*
|
||||
* Two constraints learned the hard way:
|
||||
* - Column widths must come from `table-layout: auto` plus a 100% label
|
||||
* header and 1% amount headers. `fixed` cannot express "label absorbs the
|
||||
* slack, amounts take their content width" — a column with no width under
|
||||
* `fixed` swallows everything.
|
||||
* - There must be **no `<colgroup>`**: `<col>` widths override the header
|
||||
* hints and the amounts drift to the far right.
|
||||
*/
|
||||
|
||||
.dn_fr_view {
|
||||
/* ---- control panel ------------------------------------------------
|
||||
* The panel itself is Odoo's own <ControlPanel> component, so its layout,
|
||||
* ordering and responsive rules come from web core. Only the two report
|
||||
* specifics below are ours, both copied from enterprise's account_report:
|
||||
* the breadcrumbs may not shrink, and the control-panel dropdown items
|
||||
* carry flush btn-link children. */
|
||||
.o_control_panel_main_buttons {
|
||||
.dropdown-item {
|
||||
padding: 0;
|
||||
.btn-link {
|
||||
width: 100%;
|
||||
text-align: left;
|
||||
padding: 3px 20px;
|
||||
border-radius: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.o_control_panel_breadcrumbs {
|
||||
min-width: fit-content;
|
||||
}
|
||||
|
||||
/* Enterprise filter dropdowns: an underlined name on the left, the value
|
||||
* input centred, and prev/next arrows that only darken on hover. These
|
||||
* selectors are the same as account_reports/filters/filters.scss so the
|
||||
* two dropdown buttons read identically. */
|
||||
.account_report_filter {
|
||||
&.date {
|
||||
.date_filter {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
}
|
||||
}
|
||||
&.date, &.comparison {
|
||||
.dropdown-item.date {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.dn_fr_advfilters {
|
||||
border-top: 1px solid var(--border-color, #dee2e6);
|
||||
}
|
||||
|
||||
/* ---- body --------------------------------------------------------- */
|
||||
.dn_fr_content {
|
||||
min-height: 0; // lets overflow-auto actually clip inside the flex column
|
||||
padding-bottom: 40px; // same breathing room as the enterprise scroll container
|
||||
background-color: var(--bs-body-bg, #fff);
|
||||
}
|
||||
|
||||
/* The horizontal scroller. `margin-inline: 0 !important` mirrors
|
||||
* enterprise's own override: the class is also styled by web core, and the
|
||||
* core rule would otherwise reintroduce an inline margin on the card. */
|
||||
.o_account_report_scroll_container {
|
||||
margin-inline: 0 !important;
|
||||
padding-bottom: 0;
|
||||
}
|
||||
|
||||
/* =================================================================
|
||||
* Table — the card
|
||||
* ================================================================= */
|
||||
.dn_fr_table {
|
||||
background-color: var(--bs-body-bg, #fff);
|
||||
border-collapse: separate;
|
||||
border-spacing: 0;
|
||||
font-size: 0.8rem;
|
||||
margin: 24px;
|
||||
padding: 24px;
|
||||
width: auto;
|
||||
min-width: 800px;
|
||||
border: 1px solid #dee2e6; // $o-gray-300
|
||||
border-radius: 0.25rem;
|
||||
overflow-anchor: none;
|
||||
|
||||
table-layout: auto;
|
||||
font-variant-numeric: tabular-nums;
|
||||
|
||||
// Room for the hover-only action, revealed by `--row-action-opacity`
|
||||
// on row hover. Declared here (not on the button) so every affordance
|
||||
// in the row can read the same value.
|
||||
--row-action-color: #dee2e6;
|
||||
--row-action-opacity: 0;
|
||||
--row-muted-color: #dee2e6;
|
||||
|
||||
td,
|
||||
th {
|
||||
// `!important` because Bootstrap's `> :not(caption) > * > *`
|
||||
// selector is more specific than any plain `td` rule here.
|
||||
padding: 0.25rem 0.75rem !important;
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
/* ---- header ---- */
|
||||
/* Column titles are dark, not muted.
|
||||
*
|
||||
* Enterprise sets `color: $o-gray-300` on `> tr:first-child > th`, but
|
||||
* its first header row is `column_companies_row` — the list of company
|
||||
* names, which is empty on a single-company database. The row that
|
||||
* actually carries the column titles is `column_headers_row`, and it
|
||||
* inherits the normal text colour.
|
||||
*
|
||||
* Copying that rule onto our only header row painted the column titles
|
||||
* in #dee2e6 on white — a 1.3:1 contrast ratio, which is why the header
|
||||
* looked washed out and the report read differently from enterprise.
|
||||
* $o-gray-700 gives 8.2:1 and matches what enterprise actually shows. */
|
||||
> thead > tr > th {
|
||||
color: #495057; // $o-gray-700
|
||||
font-weight: 600;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
|
||||
&.dn_fr_amount_col {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
// The extra 20px right gutter, so a header never sits flush with
|
||||
// the figures beneath it.
|
||||
&.numeric-header {
|
||||
padding-right: calc(20px + 0.75rem) !important;
|
||||
}
|
||||
}
|
||||
|
||||
/* Amount headers are centred and share the column rules of the figures
|
||||
* below them. No left border: enterprise only draws header cell borders
|
||||
* between *stacked* header rows (`tr:not(:last-child)`), which never
|
||||
* matches a single-row header — adding them would put three vertical
|
||||
* rules through a header that has none in enterprise. */
|
||||
> thead > tr > th.column_header {
|
||||
text-align: center;
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
> thead.sticky {
|
||||
background-color: var(--bs-body-bg, #fff);
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 999;
|
||||
|
||||
> tr > th {
|
||||
background-color: var(--bs-body-bg, #fff);
|
||||
border-bottom: 1px solid #dee2e6;
|
||||
}
|
||||
}
|
||||
|
||||
// Width hints, see the file header.
|
||||
.dn_fr_label_col {
|
||||
width: 100%;
|
||||
text-align: left;
|
||||
color: #495057; // $o-gray-700, same as the amount headers
|
||||
}
|
||||
|
||||
// The floor matters on the ledger report, whose four short headers
|
||||
// ("Debit" / "Credit" / "Cumulative Balance") would otherwise collapse
|
||||
// to ~61px each. 8rem = 128px keeps the figures legible; the
|
||||
// three-column reports are unaffected because their content is wider.
|
||||
.dn_fr_amount_col {
|
||||
width: 1%;
|
||||
min-width: 8rem;
|
||||
}
|
||||
|
||||
// Second line under a column title: the period the column covers.
|
||||
.dn_fr_subhead {
|
||||
font-size: 0.7rem;
|
||||
font-weight: 400;
|
||||
color: #adb5bd; // $o-gray-500
|
||||
}
|
||||
|
||||
/* ---- body ---- */
|
||||
> tbody > tr {
|
||||
// 1.5 line-height × 0.8rem + 0.25rem × 2 padding + 5px border
|
||||
height: calc(0.8rem * var(--body-line-height) + 0.5rem + 5px);
|
||||
}
|
||||
|
||||
> tbody > tr > td {
|
||||
border-bottom: 1px solid #e9ecef; // $o-gray-200
|
||||
}
|
||||
|
||||
/* The spacer above every level-0 line (see dn_fr_view.xml).
|
||||
* It holds one cell so the browser keeps the row; the cell itself must
|
||||
* contribute no border, no padding and no background, otherwise the
|
||||
* gap reads as a thin line instead of empty space. */
|
||||
> tbody > tr.empty {
|
||||
height: calc(0.8rem * var(--body-line-height, 1.5) + 0.5rem + 5px);
|
||||
|
||||
> td {
|
||||
padding: 0 !important;
|
||||
border: 0 !important;
|
||||
background: transparent !important;
|
||||
height: 0;
|
||||
line-height: 0;
|
||||
}
|
||||
}
|
||||
|
||||
/* `table-hover` (added so the base class list matches enterprise) tints
|
||||
* a hovered row through `--bs-table-hover-bg`, applied as an
|
||||
* `inset 0 0 0 9999px` box-shadow on each cell. That shadow paints
|
||||
* *over* the background our own `tr:hover` rule sets, so the two would
|
||||
* fight. Neutralising the variable hands hover back to the single rule
|
||||
* below, which is the one that also flips `--row-action-opacity`. */
|
||||
> tbody > tr {
|
||||
--bs-table-hover-bg: transparent;
|
||||
}
|
||||
|
||||
/* =============================================================
|
||||
* Line name column
|
||||
* ============================================================= */
|
||||
.line_name {
|
||||
vertical-align: middle;
|
||||
white-space: nowrap;
|
||||
|
||||
sup {
|
||||
top: auto;
|
||||
}
|
||||
|
||||
&.unfoldable:hover {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
// Long account labels wrap rather than dragging the column wider,
|
||||
// but only when they are genuinely long: `nowrap` above is what
|
||||
// keeps short labels on one line.
|
||||
.dn_fr_wrap & {
|
||||
white-space: normal;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
}
|
||||
|
||||
/* =============================================================
|
||||
* Amount cells
|
||||
* ============================================================= */
|
||||
.line_cell {
|
||||
vertical-align: middle;
|
||||
white-space: nowrap;
|
||||
|
||||
&.date {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
&.numeric {
|
||||
text-align: end;
|
||||
padding-right: calc(20px + 0.75rem) !important;
|
||||
}
|
||||
|
||||
a.cursor-pointer {
|
||||
color: inherit;
|
||||
}
|
||||
}
|
||||
|
||||
/* Zebra stripe on every second amount column: this is what makes a
|
||||
* comparison report read as pairs of columns instead of one wide band
|
||||
* of numbers. A level-0 band needs a darker stripe to stay visible
|
||||
* against its own fill. */
|
||||
&.dn_fr_striped > tbody > tr > td.line_cell_odd {
|
||||
background: #f8f9fa; // $o-gray-100
|
||||
}
|
||||
|
||||
&.dn_fr_striped > tbody > tr.line_level_0 > td.line_cell_odd {
|
||||
background: #ced4da; // $o-gray-400, darker than the band
|
||||
}
|
||||
|
||||
/* =============================================================
|
||||
* Hierarchy
|
||||
* ============================================================= */
|
||||
|
||||
/* Level 0 is a filled band: it groups everything below it, so it must
|
||||
* not have its own bottom border — the fill does the separating. */
|
||||
.line_level_0 {
|
||||
color: #495057; // $o-gray-700
|
||||
font-weight: bold;
|
||||
|
||||
> td {
|
||||
border-bottom: 0 !important;
|
||||
background-color: #dee2e6; // $o-gray-300
|
||||
}
|
||||
|
||||
.muted {
|
||||
color: #ced4da !important; // $o-gray-400
|
||||
}
|
||||
}
|
||||
|
||||
/* Level 1 sits at the same gutter as level 0 so the first nested level
|
||||
* lines up under its heading instead of past it. A foldable cell drops
|
||||
* back to the plain 0.75rem padding because its own arrow already
|
||||
* provides the indent. */
|
||||
.line_level_1 > td:nth-child(1) {
|
||||
padding-left: calc(20px + 0.75rem) !important;
|
||||
|
||||
&.unfoldable {
|
||||
padding-left: 0.75rem !important;
|
||||
}
|
||||
}
|
||||
|
||||
// Levels 2..16: 8px per level on top of the 20px gutter. Past 16 the
|
||||
// indentation stops growing — deep enough that any further shift would
|
||||
// leave no room for the label on a normal window.
|
||||
@for $i from 2 through 16 {
|
||||
.line_level_#{$i} {
|
||||
$indentation: ($i - 1) * 8px;
|
||||
|
||||
> td:nth-child(1) {
|
||||
color: #495057; // $o-gray-700
|
||||
padding-left: calc(#{$indentation} + 20px + 0.75rem) !important;
|
||||
|
||||
&.unfoldable {
|
||||
padding-left: calc(#{$indentation} + 0.75rem) !important;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* =============================================================
|
||||
* Row states
|
||||
* ============================================================= */
|
||||
> tbody > tr {
|
||||
&.unfolded,
|
||||
&.total {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
// An open section gets a darker rule under it: that line is the
|
||||
// only signal that the rows below belong to it.
|
||||
&.unfolded {
|
||||
--row-action-opacity: 1;
|
||||
|
||||
> td {
|
||||
border-bottom: 1px solid #dee2e6;
|
||||
}
|
||||
}
|
||||
|
||||
// Journal-item detail rows are secondary information: smaller,
|
||||
// greyer, and without the hover lift of a summary row.
|
||||
&.detail > td {
|
||||
color: #6c757d;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.btn_action,
|
||||
.btn_foldable {
|
||||
color: var(--row-action-color);
|
||||
}
|
||||
|
||||
.btn_action {
|
||||
opacity: var(--row-action-opacity);
|
||||
}
|
||||
|
||||
&:hover {
|
||||
--row-action-opacity: 1;
|
||||
--row-action-color: #017e84; // $o-enterprise-action-color
|
||||
--row-muted-color: #343a40;
|
||||
|
||||
> td {
|
||||
background-color: #f8f9fa; // $o-gray-100
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* =============================================================
|
||||
* Buttons
|
||||
* ============================================================= */
|
||||
.btn_foldable,
|
||||
.btn_action {
|
||||
border: none;
|
||||
color: #dee2e6; // $o-gray-300
|
||||
font-size: inherit;
|
||||
font-weight: normal;
|
||||
padding: 0 !important;
|
||||
text-align: center;
|
||||
width: 20px;
|
||||
white-space: nowrap;
|
||||
|
||||
&:hover {
|
||||
color: #017e84 !important;
|
||||
cursor: pointer;
|
||||
}
|
||||
}
|
||||
|
||||
// The fold arrow is slightly darker than a hover-only action: it is
|
||||
// the primary way to navigate a hierarchical report, so it must be
|
||||
// visible without hovering.
|
||||
.btn_foldable {
|
||||
color: #adb5bd; // $o-gray-500
|
||||
}
|
||||
|
||||
// The drill-down button is a bordered pill that fades in on hover, not
|
||||
// a bare icon: it sits inline with the label and would otherwise read
|
||||
// as part of the text.
|
||||
.btn_action {
|
||||
opacity: 0;
|
||||
background-color: var(--bs-body-bg, #fff);
|
||||
color: #6c757d;
|
||||
width: auto;
|
||||
padding: 0 0.25rem !important;
|
||||
margin: 0 0.25rem;
|
||||
border: 1px solid #dee2e6 !important;
|
||||
border-radius: 0.25rem;
|
||||
line-height: 1.4;
|
||||
font-size: 0.7rem;
|
||||
}
|
||||
|
||||
/* Links inside the report use the enterprise action colour. */
|
||||
a {
|
||||
color: #017e84;
|
||||
}
|
||||
|
||||
@media print {
|
||||
border: 0;
|
||||
padding: 0;
|
||||
}
|
||||
}
|
||||
|
||||
/* Muted figures: a zero in a comparison column. Greyed rather than
|
||||
* hidden so the column keeps its shape. */
|
||||
.muted {
|
||||
color: var(--row-muted-color, #dee2e6);
|
||||
}
|
||||
}
|
||||
|
||||
/* =====================================================================
|
||||
* Print
|
||||
* The card chrome and the interactive controls are pointless on paper;
|
||||
* the figures are not.
|
||||
* ===================================================================== */
|
||||
@media print {
|
||||
.dn_fr_view {
|
||||
.o_control_panel,
|
||||
.dn_fr_advfilters {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.dn_fr_content {
|
||||
overflow: visible !important;
|
||||
padding-bottom: 0;
|
||||
}
|
||||
|
||||
.dn_fr_table {
|
||||
font-size: 10pt;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
min-width: 0;
|
||||
|
||||
> thead.sticky {
|
||||
position: static;
|
||||
}
|
||||
|
||||
.btn_foldable,
|
||||
.btn_action {
|
||||
display: none !important;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* =====================================================================
|
||||
* Narrow screens
|
||||
* The amounts keep a floor so figures stay legible, the label column keeps
|
||||
* a floor of its own so it cannot be squeezed away, and the card margins
|
||||
* shrink so the table still fits.
|
||||
* ===================================================================== */
|
||||
@media (max-width: 900px) {
|
||||
.dn_fr_view .dn_fr_table {
|
||||
margin: 8px;
|
||||
padding: 8px;
|
||||
min-width: 0;
|
||||
|
||||
.dn_fr_label_col {
|
||||
width: auto;
|
||||
min-width: 14rem;
|
||||
}
|
||||
|
||||
.dn_fr_amount_col {
|
||||
width: 1%;
|
||||
min-width: 6rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
132
accountant_cn/static/src/js/dn_fr_view.xml
Normal file
132
accountant_cn/static/src/js/dn_fr_view.xml
Normal file
@@ -0,0 +1,132 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<templates xml:space="preserve">
|
||||
<t t-name="dn_financial_reports.DnFrView">
|
||||
<!-- The enterprise report page is an `o_action account_report` whose
|
||||
first child is Odoo's own <ControlPanel>, filled through named
|
||||
slots. Reproducing that structure — rather than a hand-stacked
|
||||
div — is what makes the header geometry match: Owl's ControlPanel
|
||||
owns the breadcrumbs row, the buttons row, the filters row and the
|
||||
pager/navigation row, with the exact flex ordering and responsive
|
||||
breakpoints the rest of Odoo uses. -->
|
||||
<div class="o_action account_report dn_fr_view d-flex flex-column h-100">
|
||||
<ControlPanel display="{ buttons: true, actions: true }">
|
||||
<t t-set-slot="control-panel-buttons">
|
||||
<button class="btn btn-primary text-nowrap"
|
||||
t-on-click="() => this.load()"
|
||||
t-att-disabled="this.state.loading">
|
||||
<t t-out="this.labels.apply"/>
|
||||
</button>
|
||||
</t>
|
||||
|
||||
<t t-set-slot="control-panel-additional-actions">
|
||||
<Dropdown>
|
||||
<button class="btn p-0 ms-1 border-0" title="Options">
|
||||
<i class="oi oi-fw oi-filled" data-icon="settings"/>
|
||||
</button>
|
||||
<t t-set-slot="content">
|
||||
<DropdownItem onSelected="() => this.exportCsv()"
|
||||
t-if="this.features.export">
|
||||
<t t-out="this.labels.exportCsv"/>
|
||||
</DropdownItem>
|
||||
<DropdownItem onSelected="() => this.printReport()">
|
||||
<t t-out="this.labels.print"/>
|
||||
</DropdownItem>
|
||||
<DropdownItem onSelected="() => this.unfoldAll()">
|
||||
<t t-out="this.labels.unfoldAll"/>
|
||||
</DropdownItem>
|
||||
<DropdownItem onSelected="() => this.foldAll()">
|
||||
<t t-out="this.labels.foldAll"/>
|
||||
</DropdownItem>
|
||||
</t>
|
||||
</Dropdown>
|
||||
</t>
|
||||
|
||||
<t t-set-slot="control-panel-actions">
|
||||
<div class="d-flex gap-1 flex-wrap" id="reportFilterCollapse">
|
||||
<DnFrDateFilter t-if="this.ready"/>
|
||||
<DnFrComparisonFilter t-if="this.ready and this.features.comparison"/>
|
||||
<!-- "More Filters" opens the extra-options row, the same
|
||||
role enterprise's extra-options dropdown plays. -->
|
||||
<button class="btn btn-secondary" type="button"
|
||||
t-on-click="() => this.toggleFilters()">
|
||||
<i class="oi oi-filled me-1" data-icon="tune"/>
|
||||
<t t-out="this.labels.moreFilters"/>
|
||||
</button>
|
||||
</div>
|
||||
</t>
|
||||
</ControlPanel>
|
||||
|
||||
<!-- Expanded "more filters" row: the switches that would clutter
|
||||
the main filter line. Kept outside the ControlPanel slots and
|
||||
styled to sit flush under it, like enterprise's extra-options
|
||||
dropdown content. -->
|
||||
<div t-if="this.state.filtersOpen"
|
||||
class="dn_fr_advfilters d-flex flex-wrap gap-3 align-items-center px-3 py-2">
|
||||
<div t-if="this.features.draft_entries" class="form-check form-switch mb-0">
|
||||
<input class="form-check-input" type="checkbox" id="dn_fr_draft"
|
||||
t-model="this.includeDraft"/>
|
||||
<label class="form-check-label small" for="dn_fr_draft"
|
||||
t-out="this.labels.includeDraft"/>
|
||||
</div>
|
||||
<div t-if="this.features.unreconciled_only" class="form-check form-switch mb-0">
|
||||
<input class="form-check-input" type="checkbox" id="dn_fr_unrec"
|
||||
t-model="this.unreconciled"/>
|
||||
<label class="form-check-label small" for="dn_fr_unrec"
|
||||
t-out="this.labels.unreconciledOnly"/>
|
||||
</div>
|
||||
<button class="btn btn-link btn-sm" t-on-click="() => this.toggleFilters()"
|
||||
t-out="this.labels.hideFilters"/>
|
||||
<button class="btn btn-link btn-sm" t-on-click="() => this.resetFilters()"
|
||||
t-out="this.labels.reset"/>
|
||||
</div>
|
||||
|
||||
<!-- ===================================================== body -->
|
||||
<div class="dn_fr_content o_content flex-grow-1 overflow-auto">
|
||||
<div t-if="this.state.loading" class="alert alert-info m-3">
|
||||
<i class="fa fa-circle-o-notch fa-spin me-2"/><t t-out="this.labels.computing"/>
|
||||
</div>
|
||||
<div t-if="this.state.error" class="alert alert-danger m-3" t-out="this.state.error"/>
|
||||
|
||||
<!-- Two nested wrappers, the same pair the enterprise page uses:
|
||||
the outer one is the horizontal scroller, the inner one is
|
||||
the flex row the card is centred in. `mx-auto` on the table
|
||||
only works because the inner wrapper is a flex container. -->
|
||||
<div t-if="this.ready"
|
||||
class="mx-auto o_account_report_scroll_container overflow-x-auto">
|
||||
<div class="d-flex align-items-start">
|
||||
<table t-att-class="this.tableClasses">
|
||||
<DnFrHeader columns="this.columns"
|
||||
labels="this.labels"
|
||||
isLedger="this.isLedgerReport"/>
|
||||
<tbody>
|
||||
<!-- One flat walk over `visibleLines`, which is
|
||||
already filtered by the fold map. -->
|
||||
<t t-foreach="this.visibleLines" t-as="line" t-key="line.id">
|
||||
<!-- Enterprise inserts an empty spacer above
|
||||
every level-0 line so adjacent bands do
|
||||
not read as one block. The cell keeps the
|
||||
browser from collapsing the empty row. -->
|
||||
<tr t-if="line.level === 0" class="empty">
|
||||
<td t-att-colspan="this.columns.length + 1"/>
|
||||
</tr>
|
||||
<DnFrLine line="line"
|
||||
labels="this.labels"
|
||||
unfolded="!this.folded[line.id]"
|
||||
isLedger="this.isLedgerReport"
|
||||
onToggle="(l) => this.onToggle(l)"
|
||||
onAction="(l) => this.onAction(l)"/>
|
||||
</t>
|
||||
<tr t-if="!this.visibleLines.length">
|
||||
<td t-att-colspan="this.columns.length + 1"
|
||||
class="text-center text-muted py-5">
|
||||
<t t-out="this.labels.noData"/>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</t>
|
||||
</templates>
|
||||
187
accountant_cn/static/src/js/dn_report_view.js
Normal file
187
accountant_cn/static/src/js/dn_report_view.js
Normal file
@@ -0,0 +1,187 @@
|
||||
/** @odoo-module **/
|
||||
import { registry } from "@web/core/registry";
|
||||
import { Component, onWillStart, proxy, signal, t, useProps } from "@odoo/owl";
|
||||
import { rpc } from "@web/core/network/rpc";
|
||||
import { useService } from "@web/core/utils/hooks";
|
||||
import { _t, translationIsReady } from "@web/core/l10n/translation";
|
||||
import { formatFloat } from "@web/views/fields/formatters";
|
||||
|
||||
/**
|
||||
* DN Report viewer.
|
||||
*
|
||||
* Renders the payload produced by the self-implemented engine
|
||||
* (`dn.report.get_report_data`) as a hierarchical, collapsible table.
|
||||
* Everything the UI shows comes from the server payload, so adding a new
|
||||
* report is purely a matter of defining data records — no JS change needed.
|
||||
*/
|
||||
export class DnReportView extends Component {
|
||||
static template = "dn_account_reports_core.DnReportView";
|
||||
|
||||
// Owl 3: props are declared through useProps, not a static `props`.
|
||||
props = useProps({
|
||||
action: t.object().optional(),
|
||||
});
|
||||
|
||||
setup() {
|
||||
this.orm = useService("orm");
|
||||
this.notification = useService("notification");
|
||||
// Numbers go through `formatFloat`, which applies the user's own
|
||||
// language parameters (separators, decimal point) instead of a
|
||||
// hard-coded locale.
|
||||
// `t-model` in Owl 3 requires a signal (it needs a `.set` method), so the
|
||||
// two date inputs are bound to signals rather than to `proxy` fields.
|
||||
// Default range: January 1st of the current year -> today. Financial
|
||||
// statements are normally read on a year-to-date basis.
|
||||
const today = new Date();
|
||||
const pad = (n) => String(n).padStart(2, "0");
|
||||
const iso = (d) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
|
||||
this.dateFrom = signal(iso(new Date(today.getFullYear(), 0, 1)));
|
||||
this.dateTo = signal(iso(today));
|
||||
this.state = proxy({
|
||||
loading: true,
|
||||
report: null,
|
||||
error: null,
|
||||
folded: {},
|
||||
});
|
||||
// A report can be reached two ways: from the menu (the action carries
|
||||
// `params.report_code`), or from the "Preview Report" button on a report
|
||||
// form, where the current record id travels in the action context.
|
||||
const action = this.props.action || {};
|
||||
const params = action.params || {};
|
||||
const context = action.context || {};
|
||||
this.reportCode = params.report_code || context.report_code || null;
|
||||
this.reportId =
|
||||
params.report_id || context.report_id || context.active_id || null;
|
||||
onWillStart(() => this.load());
|
||||
}
|
||||
|
||||
get headers() {
|
||||
return this.state.report ? this.state.report.headers : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* UI strings. They live here rather than in the template because terms are
|
||||
* extracted from `_t(...)` calls in JavaScript; a literal inside an Owl
|
||||
* template never reaches the translation file. Going through a getter
|
||||
* means the labels follow the user's language at render time.
|
||||
*/
|
||||
get labels() {
|
||||
return {
|
||||
title: _t("Financial Report"),
|
||||
start: _t("Start"),
|
||||
end: _t("End"),
|
||||
apply: _t("Apply"),
|
||||
computing: _t("Computing…"),
|
||||
account: _t("Account / Item"),
|
||||
empty: _t("No data for this period."),
|
||||
};
|
||||
}
|
||||
|
||||
/** True while a report payload has been received and no request is pending. */
|
||||
get ready() {
|
||||
return Boolean(this.state.report) && !this.state.loading;
|
||||
}
|
||||
|
||||
async load() {
|
||||
// Wait for the language parameters before rendering: the localization
|
||||
// proxy throws on any read until they arrive, and the first render
|
||||
// already formats numbers through `formatNumber`.
|
||||
await translationIsReady;
|
||||
this.state.loading = true;
|
||||
this.state.error = null;
|
||||
try {
|
||||
let reportId = this.reportId;
|
||||
if (!reportId && this.reportCode) {
|
||||
const found = await this.orm.searchRead(
|
||||
"dn.report",
|
||||
[["code", "=", this.reportCode]],
|
||||
["id"],
|
||||
{ limit: 1 }
|
||||
);
|
||||
reportId = found.length ? found[0].id : false;
|
||||
}
|
||||
if (!reportId) {
|
||||
this.state.error = _t("No report configuration found (invalid report_code).");
|
||||
return;
|
||||
}
|
||||
const result = await rpc("/dn/report/data", {
|
||||
report_id: reportId,
|
||||
options: {
|
||||
date_from: this.dateFrom() || undefined,
|
||||
date_to: this.dateTo() || undefined,
|
||||
},
|
||||
});
|
||||
if (!result.ok) {
|
||||
this.state.error = result.error || _t("Unknown error");
|
||||
} else {
|
||||
this.state.report = result.data;
|
||||
}
|
||||
} catch (error) {
|
||||
this.state.error = error.message || String(error);
|
||||
} finally {
|
||||
this.state.loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
toggleLine(lineId) {
|
||||
this.state.folded[lineId] = !this.state.folded[lineId];
|
||||
}
|
||||
|
||||
isFolded(line) {
|
||||
return Boolean(this.state.folded[line.id]);
|
||||
}
|
||||
|
||||
cellValue(line, index) {
|
||||
const value = (line.values || {})[`c${index}`];
|
||||
return this.fmt(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Mirror the enterprise class vocabulary so the SCSS can target the same
|
||||
* concepts: `line_level_N` is the level-0 filled band and the indentation
|
||||
* hook, `dn_report_total` is a bold summary.
|
||||
*/
|
||||
rowClass(line) {
|
||||
const classes = [`line_level_${line.level || 0}`];
|
||||
if (line.is_total) classes.push("dn_report_total");
|
||||
return classes.join(" ");
|
||||
}
|
||||
|
||||
/**
|
||||
* Enterprise indents 8px per level on top of the 20px gutter that the
|
||||
* label cell already carries. Level 0 gets no indent so its filled band
|
||||
* starts flush with the card padding.
|
||||
*/
|
||||
indentStyle(line) {
|
||||
const level = line.level || 0;
|
||||
if (!level) return "";
|
||||
return `padding-left: calc(${level * 8}px + 20px + 0.75rem)`;
|
||||
}
|
||||
|
||||
fmt(value) {
|
||||
if (value === null || value === undefined || value === "") {
|
||||
return "";
|
||||
}
|
||||
if (typeof value !== "number") {
|
||||
return value;
|
||||
}
|
||||
return formatFloat(value, { digits: [16, 2] });
|
||||
}
|
||||
|
||||
/** Flatten the line tree into visible rows, honouring the fold state. */
|
||||
get visibleRows() {
|
||||
const rows = [];
|
||||
const walk = (lines, depth) => {
|
||||
for (const line of lines) {
|
||||
rows.push({ ...line, level: depth });
|
||||
if (line.children && line.children.length && !this.isFolded(line)) {
|
||||
walk(line.children, depth + 1);
|
||||
}
|
||||
}
|
||||
};
|
||||
walk(this.state.report ? this.state.report.lines : [], 0);
|
||||
return rows;
|
||||
}
|
||||
}
|
||||
|
||||
registry.category("actions").add("dn_report_view", DnReportView);
|
||||
212
accountant_cn/static/src/js/dn_report_view.scss
Normal file
212
accountant_cn/static/src/js/dn_report_view.scss
Normal file
@@ -0,0 +1,212 @@
|
||||
/* DN Financial Reports (Core) — report view styling.
|
||||
*
|
||||
* Same visual target as `dn_financial_reports`: Odoo Enterprise's
|
||||
* `account_reports` report card. See `dn_fr_view.scss` for the annotated list
|
||||
* of enterprise traits; the geometry constants are identical so the two report
|
||||
* engines look like one product.
|
||||
*
|
||||
* The column-width approach is also shared: `table-layout: auto` with a 100%
|
||||
* label header and 1% amount headers. `fixed` was measured and rejected — an
|
||||
* un-sized column under `fixed` takes the whole remainder (1120px label /
|
||||
* 144px amount), which is exactly the broken look this replaces.
|
||||
*/
|
||||
|
||||
.dn_report_view {
|
||||
.o_control_panel {
|
||||
flex: 0 0 auto;
|
||||
border-bottom: 1px solid var(--border-color, #dee2e6);
|
||||
}
|
||||
|
||||
.o_control_panel_breadcrumbs h3 {
|
||||
font-size: 1.25rem;
|
||||
line-height: 1.3;
|
||||
}
|
||||
|
||||
.dn_report_toolbar {
|
||||
margin: 0;
|
||||
|
||||
.dn_report_field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 8.5rem;
|
||||
|
||||
input {
|
||||
min-width: 8.5rem;
|
||||
}
|
||||
|
||||
label {
|
||||
font-size: 0.75rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.02em;
|
||||
color: var(--o-gray-600, #6c757d);
|
||||
margin-bottom: 0.125rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.dn_report_content {
|
||||
min-height: 0; // lets overflow-auto clip inside the flex column
|
||||
background-color: var(--o-view-background-color, #fff);
|
||||
}
|
||||
|
||||
/* ---- table: enterprise "card" ------------------------------------- */
|
||||
.dn_report_table {
|
||||
background-color: var(--o-view-background-color, #fff);
|
||||
border-collapse: separate;
|
||||
border-spacing: 0;
|
||||
font-size: 0.8rem;
|
||||
margin: 24px;
|
||||
padding: 24px;
|
||||
width: auto;
|
||||
min-width: 800px;
|
||||
border: 1px solid var(--o-gray-300, #dee2e6);
|
||||
border-radius: 0.25rem;
|
||||
overflow-anchor: none;
|
||||
|
||||
table-layout: auto;
|
||||
font-variant-numeric: tabular-nums;
|
||||
|
||||
.dn_report_label_col {
|
||||
width: 100%;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.dn_report_amount_col {
|
||||
width: 1%;
|
||||
min-width: 8rem;
|
||||
}
|
||||
|
||||
td,
|
||||
th {
|
||||
padding: 0.25rem 0.75rem;
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
/* ---- header ---- */
|
||||
> thead > tr > th {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 2;
|
||||
background-color: var(--o-view-background-color, #fff);
|
||||
border-bottom: 2px solid var(--o-gray-300, #dee2e6);
|
||||
font-weight: 600;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
color: var(--o-main-text-color, #212529);
|
||||
|
||||
&.dn_report_amount_col {
|
||||
padding-right: calc(20px + 0.75rem);
|
||||
text-align: end;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- body ---- */
|
||||
> tbody > tr {
|
||||
height: calc(0.8rem * var(--body-line-height) + 0.5rem + 5px);
|
||||
|
||||
> td {
|
||||
border-bottom: 1px solid var(--o-gray-200, #e9ecef);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
&:last-child > td {
|
||||
border-bottom: 0;
|
||||
}
|
||||
}
|
||||
|
||||
tbody td.dn_report_cell_label {
|
||||
white-space: normal;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
tbody td.text-end {
|
||||
padding-right: calc(20px + 0.75rem);
|
||||
}
|
||||
|
||||
/* Level-0 rows are a filled band, like the enterprise `line_level_0`. */
|
||||
tr.line_level_0 > td {
|
||||
background-color: var(--o-gray-300, #dee2e6);
|
||||
border-bottom: 0;
|
||||
font-weight: 700;
|
||||
color: var(--o-gray-700, #495057);
|
||||
}
|
||||
|
||||
/* A level-0 line that is also a total must keep the darker band: the
|
||||
enterprise hierarchy is read top-down by shade, and collapsing it
|
||||
into the total colour makes every level look the same. */
|
||||
tr.dn_report_total:not(.line_level_0) > td {
|
||||
font-weight: 700;
|
||||
background-color: var(--o-gray-100, #f8f9fa);
|
||||
border-top: 1px solid var(--o-gray-300, #dee2e6);
|
||||
}
|
||||
|
||||
> tbody > tr:not(.line_level_0):hover > td {
|
||||
background-color: var(--o-gray-100, #f8f9fa);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.dn_report_toggle_wrap {
|
||||
display: inline-block;
|
||||
width: 1.25rem;
|
||||
}
|
||||
|
||||
.dn_report_toggle {
|
||||
color: var(--o-gray-500, #adb5bd);
|
||||
text-decoration: none;
|
||||
|
||||
&:hover {
|
||||
color: var(--o-enterprise-action-color, #017e84);
|
||||
}
|
||||
}
|
||||
|
||||
a {
|
||||
color: var(--o-enterprise-action-color, #017e84);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Narrow screens: amounts keep a legible floor, the label keeps its own. */
|
||||
@media (max-width: 900px) {
|
||||
.dn_report_view .dn_report_table {
|
||||
margin: 8px;
|
||||
padding: 8px;
|
||||
min-width: 0;
|
||||
|
||||
.dn_report_label_col {
|
||||
width: auto;
|
||||
min-width: 14rem;
|
||||
}
|
||||
|
||||
.dn_report_amount_col {
|
||||
width: 1%;
|
||||
min-width: 6rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@media print {
|
||||
.dn_report_view {
|
||||
.o_control_panel,
|
||||
.dn_report_toolbar {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.dn_report_content {
|
||||
overflow: visible !important;
|
||||
}
|
||||
|
||||
.dn_report_table {
|
||||
font-size: 10pt;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
min-width: 0;
|
||||
|
||||
> thead > tr > th {
|
||||
position: static;
|
||||
background: transparent !important;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
88
accountant_cn/static/src/js/dn_report_view.xml
Normal file
88
accountant_cn/static/src/js/dn_report_view.xml
Normal file
@@ -0,0 +1,88 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<templates xml:space="preserve">
|
||||
|
||||
<t t-name="dn_account_reports_core.DnReportView">
|
||||
<div class="dn_report_view o_action d-flex flex-column h-100">
|
||||
<!-- Control panel: same class names as Odoo 20's own control panel
|
||||
(o_control_panel_main / o_control_panel_breadcrumbs /
|
||||
o_control_panel_navigation). The older o_cp_top / o_cp_bottom
|
||||
names carry no styles in Odoo 20, which made the title, the
|
||||
filters and the buttons stack as full-width blocks. -->
|
||||
<div class="o_control_panel d-flex flex-column gap-2 px-3 pt-2">
|
||||
<div class="o_control_panel_main d-flex flex-wrap flex-lg-nowrap justify-content-between align-items-lg-start gap-2">
|
||||
<div class="o_control_panel_breadcrumbs d-flex align-items-center min-w-0">
|
||||
<h3 class="m-0 text-truncate"
|
||||
t-out="this.state.report ? this.state.report.name : this.labels.title"/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="dn_report_toolbar d-flex flex-wrap align-items-end gap-2 pb-2">
|
||||
<div class="dn_report_field">
|
||||
<label class="d-block small text-muted mb-1" t-out="this.labels.start"/>
|
||||
<input type="date" class="form-control form-control-sm" t-model="this.dateFrom"/>
|
||||
</div>
|
||||
<div class="dn_report_field">
|
||||
<label class="d-block small text-muted mb-1" t-out="this.labels.end"/>
|
||||
<input type="date" class="form-control form-control-sm" t-model="this.dateTo"/>
|
||||
</div>
|
||||
<div class="pb-1">
|
||||
<button class="btn btn-primary btn-sm text-nowrap"
|
||||
t-on-click="this.load"
|
||||
t-att-disabled="this.state.loading"
|
||||
t-out="this.labels.apply"/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="dn_report_content flex-grow-1 overflow-auto">
|
||||
<div t-if="this.state.loading" class="alert alert-info m-3" t-out="this.labels.computing"/>
|
||||
<div t-if="this.state.error" class="alert alert-danger m-3" t-out="this.state.error"/>
|
||||
|
||||
<!-- `table table-borderless` matches the enterprise report
|
||||
table base. No `table-sm` / `mb-0` / `table-hover`: they
|
||||
would flatten the card padding, zero the card margin and
|
||||
add a competing hover colour. -->
|
||||
<table t-if="this.ready" class="table table-borderless dn_report_table">
|
||||
<!-- No <colgroup> on purpose. Column widths are driven by
|
||||
the header cells: the label header hints 100% and each
|
||||
amount header hints 1%, so under `table-layout: auto`
|
||||
the browser gives the amounts their content width and
|
||||
the label column absorbs the rest. A <colgroup> would
|
||||
override that. -->
|
||||
<thead class="dn_report_thead">
|
||||
<tr>
|
||||
<th class="text-start dn_report_label_col" t-out="this.labels.account"/>
|
||||
<t t-foreach="this.headers" t-as="header" t-key="header_index">
|
||||
<th class="text-end text-nowrap dn_report_amount_col" t-out="header"/>
|
||||
</t>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr t-foreach="this.visibleRows" t-as="line" t-key="line.id"
|
||||
t-att-class="this.rowClass(line)">
|
||||
<td class="dn_report_cell_label">
|
||||
<span t-att-style="this.indentStyle(line)"/>
|
||||
<span t-if="line.children and line.children.length" class="dn_report_toggle_wrap">
|
||||
<button class="btn btn-link btn-sm p-0 dn_report_toggle"
|
||||
t-on-click="(ev) => this.toggleLine(line.id)">
|
||||
<i t-att-class="this.isFolded(line) ? 'fa fa-caret-right' : 'fa fa-caret-down'"/>
|
||||
</button>
|
||||
</span>
|
||||
<span t-else="" class="dn_report_toggle_wrap"/>
|
||||
<span t-if="line.code" class="text-muted me-2 small" t-out="line.code"/>
|
||||
<span t-out="line.name"/>
|
||||
</td>
|
||||
<t t-foreach="this.headers" t-as="header" t-key="header_index">
|
||||
<td class="text-end text-nowrap" t-out="this.cellValue(line, header_index)"/>
|
||||
</t>
|
||||
</tr>
|
||||
<tr t-if="!this.visibleRows.length">
|
||||
<td t-att-colspan="this.headers.length + 1" class="text-center text-muted py-4" t-out="this.labels.empty"/>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</t>
|
||||
|
||||
</templates>
|
||||
28
accountant_cn/static/src/scss/dn_loan.scss
Normal file
28
accountant_cn/static/src/scss/dn_loan.scss
Normal file
@@ -0,0 +1,28 @@
|
||||
/* DN Loans Management.
|
||||
*
|
||||
* Two adjustments to the generic Odoo list rendering, both driven by how an
|
||||
* amortization schedule is read rather than by taste.
|
||||
*/
|
||||
|
||||
/* The schedule is a table of amounts. Right-aligning them, with a tabular
|
||||
* figure width, makes the columns line up so a column of principals can be read
|
||||
* as a column; proportional digits make every row a slightly different width
|
||||
* and the eye cannot follow a column down. */
|
||||
.o_list_renderer .o_data_cell.o_dn_amount_cell,
|
||||
.o_list_renderer .o_data_row .o_data_cell[name="principal"],
|
||||
.o_list_renderer .o_data_row .o_data_cell[name="interest"],
|
||||
.o_list_renderer .o_data_row .o_data_cell[name="payment"],
|
||||
.o_list_renderer .o_data_row .o_data_cell[name="outstanding_balance"] {
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
/* The wizard preview is a fixed-width text block: it is a table drawn with
|
||||
* spaces, so it only aligns if the font is monospaced and the whitespace is
|
||||
* preserved. Bootstrap's `text-monospace` sets the font but the textarea would
|
||||
* still wrap the long lines. */
|
||||
.o_field_text.dn_loan_preview textarea,
|
||||
.dn_loan_preview textarea {
|
||||
white-space: pre;
|
||||
overflow-x: auto;
|
||||
font-variant-ligatures: none;
|
||||
}
|
||||
30
accountant_cn/static/src/scss/dn_lock_date.scss
Normal file
30
accountant_cn/static/src/scss/dn_lock_date.scss
Normal file
@@ -0,0 +1,30 @@
|
||||
/* DN Accounting — lock-date dialog.
|
||||
*
|
||||
* The dialog lists, next to each lock date, the exceptions that currently
|
||||
* apply to the signed-in user and to everyone. When both exist they have to be
|
||||
* separated by "; ", and that separator is punctuation, not a translatable
|
||||
* word: putting it in the XML made `i18n export` emit four multi-line HTML
|
||||
* fragments as translatable strings, which can only be translated by matching
|
||||
* the markup byte for byte and silently breaks on any reformatting.
|
||||
*
|
||||
* A pseudo-element says the same thing with no translatable content at all.
|
||||
* `content` is inherited from the element, so the separator never appears in
|
||||
* the po file and never needs a translation.
|
||||
*/
|
||||
.dn_lock_sep::before {
|
||||
content: "; ";
|
||||
white-space: pre;
|
||||
}
|
||||
|
||||
/* Italic hints.
|
||||
*
|
||||
* These were `<i>` elements, but an `<i>` wrapping nothing but text makes
|
||||
* `i18n export` emit the whole tag as the translatable string
|
||||
* (`<i>Checks before locking</i>`), so the translator has to reproduce the
|
||||
* markup exactly and any later styling change breaks the translation. A
|
||||
* class on a `<span>` gives the identical italic look while leaving the text
|
||||
* as the bare msgid.
|
||||
*/
|
||||
.dn_italic {
|
||||
font-style: italic;
|
||||
}
|
||||
1
accountant_cn/tests/__init__.py
Normal file
1
accountant_cn/tests/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
from . import test_dn_audit_return
|
||||
145
accountant_cn/tests/test_dn_audit_return.py
Normal file
145
accountant_cn/tests/test_dn_audit_return.py
Normal file
@@ -0,0 +1,145 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from odoo import fields
|
||||
from odoo.exceptions import UserError
|
||||
from odoo.tests import TransactionCase, tagged
|
||||
|
||||
|
||||
@tagged("post_install", "-at_install")
|
||||
class TestAuditWorkingFiles(TransactionCase):
|
||||
"""The workflow rules that the Review > Audit > Working Files screen relies on.
|
||||
|
||||
These are the invariants that a refactor would silently break: the
|
||||
completion guard, the meaning of "n/a" in the counters, template loading
|
||||
being idempotent, and cycles actually filtering what gets stamped on.
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
super().setUpClass()
|
||||
cls.Return = cls.env["dn.audit.return"]
|
||||
cls.Check = cls.env["dn.audit.check"]
|
||||
cls.CheckTemplate = cls.env["dn.audit.check.template"]
|
||||
cls.bank = cls.env.ref("accountant_cn.cycle_bank")
|
||||
cls.payroll = cls.env.ref("accountant_cn.cycle_payroll")
|
||||
today = fields.Date.context_today(cls.env.user)
|
||||
cls.today = today
|
||||
|
||||
def _make_file(self, **kwargs):
|
||||
values = {
|
||||
"name": "2026-10 Close",
|
||||
"date_from": self.today.replace(day=1),
|
||||
"date_to": self.today,
|
||||
"date_deadline": fields.Date.add(self.today, days=5),
|
||||
}
|
||||
values.update(kwargs)
|
||||
return self.Return.create(values)
|
||||
|
||||
def test_template_load_is_idempotent(self):
|
||||
"""Pressing "Load templates" twice must not duplicate the checks.
|
||||
|
||||
The button is the only way checks get onto a file, so a duplicate on
|
||||
the second press would double the review workload of every period.
|
||||
"""
|
||||
wf = self._make_file(cycle_ids=[(6, 0, self.bank.ids)])
|
||||
wf.action_load_templates()
|
||||
first = len(wf.check_ids)
|
||||
self.assertTrue(first, "Bank templates should have created checks")
|
||||
|
||||
wf.action_load_templates()
|
||||
self.assertEqual(
|
||||
len(wf.check_ids), first,
|
||||
"Loading templates twice must not add the checks again")
|
||||
|
||||
def test_cycles_filter_templates(self):
|
||||
"""A file filed only under Payroll must not inherit the Bank checks."""
|
||||
wf = self._make_file(cycle_ids=[(6, 0, self.payroll.ids)])
|
||||
wf.action_load_templates()
|
||||
bank_templates = self.CheckTemplate.search([("cycle_id", "=", self.bank.id)])
|
||||
self.assertTrue(bank_templates, "The test needs at least one bank template")
|
||||
self.assertFalse(
|
||||
wf.check_ids.filtered(lambda c: c.template_id in bank_templates),
|
||||
"Bank checks leaked into a payroll-only file")
|
||||
|
||||
def test_completion_guard_blocks_unresolved_checks(self):
|
||||
"""A file with a to-do check cannot be signed off."""
|
||||
wf = self._make_file(cycle_ids=[(6, 0, self.bank.ids)])
|
||||
wf.action_load_templates()
|
||||
with self.assertRaises(UserError):
|
||||
wf.action_mark_done()
|
||||
self.assertEqual(wf.review_state, "ongoing")
|
||||
self.assertFalse(wf.is_completed)
|
||||
|
||||
def test_not_applicable_counts_as_resolved(self):
|
||||
"""``na`` must clear the issue counter, or a file stays red forever.
|
||||
|
||||
A check that does not apply to the period has been dealt with; treating
|
||||
it as outstanding would make it impossible to ever complete the file
|
||||
without lying about the result.
|
||||
"""
|
||||
wf = self._make_file()
|
||||
check = self.Check.create({
|
||||
"return_id": wf.id,
|
||||
"name": "Not applicable this period",
|
||||
"check_type": "check",
|
||||
})
|
||||
self.assertEqual(wf.unresolved_check_count, 1)
|
||||
self.assertEqual(wf.progress, 0.0)
|
||||
|
||||
check.action_mark_na()
|
||||
self.assertEqual(wf.unresolved_check_count, 0)
|
||||
self.assertEqual(wf.progress, 100.0)
|
||||
self.assertEqual(wf.resolved_check_count, 1)
|
||||
|
||||
def test_completion_after_resolving_everything(self):
|
||||
wf = self._make_file(cycle_ids=[(6, 0, self.bank.ids)])
|
||||
wf.action_load_templates()
|
||||
for check in wf.check_ids:
|
||||
check.action_mark_done()
|
||||
self.assertEqual(wf.unresolved_check_count, 0)
|
||||
|
||||
wf.action_mark_done()
|
||||
self.assertEqual(wf.review_state, "done")
|
||||
self.assertTrue(wf.is_completed)
|
||||
|
||||
def test_pause_and_resume_keep_the_checks(self):
|
||||
"""Pausing is a statement about intent, not about the work done."""
|
||||
wf = self._make_file(cycle_ids=[(6, 0, self.bank.ids)])
|
||||
wf.action_load_templates()
|
||||
before = len(wf.check_ids)
|
||||
|
||||
wf.action_pause()
|
||||
self.assertEqual(wf.review_state, "paused")
|
||||
wf.action_resume()
|
||||
self.assertEqual(wf.review_state, "ongoing")
|
||||
self.assertEqual(len(wf.check_ids), before)
|
||||
|
||||
def test_end_date_cannot_precede_start_date(self):
|
||||
wf = self._make_file()
|
||||
with self.assertRaises(UserError):
|
||||
wf.write({"date_to": fields.Date.subtract(wf.date_from, days=1)})
|
||||
|
||||
def test_late_flag_ignores_completed_files(self):
|
||||
"""A finished period is never "late", however old its deadline is."""
|
||||
wf = self._make_file(
|
||||
date_deadline=fields.Date.subtract(self.today, days=10))
|
||||
self.assertTrue(wf.is_late)
|
||||
self.assertEqual(wf.days_to_deadline, -10)
|
||||
|
||||
wf.action_mark_done()
|
||||
self.assertFalse(
|
||||
wf.is_late,
|
||||
"A completed file must not keep showing as late on the kanban")
|
||||
|
||||
def test_date_from_suggests_a_period_name(self):
|
||||
"""An empty name is filled from the start date; a typed one is kept."""
|
||||
wf = self.Return.new({"date_from": self.today.replace(day=1)})
|
||||
wf._onchange_date_from()
|
||||
self.assertTrue(wf.name, "The period name should be suggested")
|
||||
self.assertIn(str(self.today.year), wf.name)
|
||||
|
||||
named = self.Return.new({
|
||||
"name": "Custom name",
|
||||
"date_from": self.today.replace(day=1),
|
||||
})
|
||||
named._onchange_date_from()
|
||||
self.assertEqual(named.name, "Custom name")
|
||||
434
accountant_cn/views/views__dn_accounting_views.xml
Normal file
434
accountant_cn/views/views__dn_accounting_views.xml
Normal file
@@ -0,0 +1,434 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<odoo>
|
||||
<!-- ============================ year-end closing wizard -->
|
||||
<record id="view_dn_fiscal_year_closing_form" model="ir.ui.view">
|
||||
<field name="name">dn.fiscal.year.closing.form</field>
|
||||
<field name="model">dn.fiscal.year.closing</field>
|
||||
<field name="arch" type="xml">
|
||||
<form string="Year-End Closing">
|
||||
<header>
|
||||
<button name="action_preview" type="object" string="Preview"
|
||||
class="btn-secondary"/>
|
||||
<button name="action_close" type="object" string="Generate Closing Entry"
|
||||
class="oe_highlight"/>
|
||||
<field name="move_id" invisible="1"/>
|
||||
</header>
|
||||
<sheet>
|
||||
<div class="alert alert-info" role="alert">
|
||||
Closing transfers every profit and loss balance of the period to retained
|
||||
earnings, so income and expense accounts start the new fiscal year at zero.
|
||||
Assets, liabilities and equity are not affected. Use Preview to check the
|
||||
amounts before generating the entry.
|
||||
</div>
|
||||
<group>
|
||||
<group string="Period">
|
||||
<field name="company_id" groups="base.group_multi_company"/>
|
||||
<field name="fiscal_year_id"/>
|
||||
<field name="date_from"/>
|
||||
<field name="date_to"/>
|
||||
</group>
|
||||
<group string="Settings">
|
||||
<field name="journal_id"/>
|
||||
<field name="retained_earnings_account_id"/>
|
||||
<field name="post_move"/>
|
||||
<field name="lock_after_close"/>
|
||||
<field name="currency_id" invisible="1"/>
|
||||
</group>
|
||||
</group>
|
||||
<group>
|
||||
<group string="Result">
|
||||
<field name="amount"/>
|
||||
<field name="line_count"/>
|
||||
</group>
|
||||
<group string="Generated Entry">
|
||||
<field name="move_id"/>
|
||||
</group>
|
||||
</group>
|
||||
<notebook>
|
||||
<page string="Closing Details" name="preview">
|
||||
<field name="preview_line_ids" readonly="1">
|
||||
<list>
|
||||
<field name="account_code"/>
|
||||
<field name="account_name"/>
|
||||
<field name="balance"/>
|
||||
<field name="closing_amount"/>
|
||||
<field name="currency_id" column_invisible="1"/>
|
||||
</list>
|
||||
</field>
|
||||
<div class="text-muted mt-2" invisible="preview_line_ids">
|
||||
No preview yet. Click Preview to list the accounts and amounts
|
||||
that will be closed.
|
||||
</div>
|
||||
</page>
|
||||
</notebook>
|
||||
</sheet>
|
||||
</form>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
<!-- ============================ lock date wizard -->
|
||||
<!--
|
||||
Layout follows the enterprise `account.change.lock.date` dialog: one
|
||||
row per lock date, with the effective exception shown inline and a
|
||||
Revoke link right next to it. The geometry is the same on purpose —
|
||||
the "For me / For everyone" suffix only makes sense when it sits on
|
||||
the same line as the date it qualifies, and stacking it underneath
|
||||
hides the fact that a period is still open for one audience only.
|
||||
-->
|
||||
<record id="view_dn_lock_date_wizard_form" model="ir.ui.view">
|
||||
<field name="name">dn.lock.date.wizard.form</field>
|
||||
<field name="model">dn.lock.date.wizard</field>
|
||||
<field name="arch" type="xml">
|
||||
<form string="Lock Journal Entries">
|
||||
<sheet>
|
||||
<group>
|
||||
<field name="company_id" invisible="1"/>
|
||||
<field name="show_draft_entries_warning" invisible="1"/>
|
||||
<div class="alert alert-warning mb-0 d-flex gap-2 flex-wrap"
|
||||
role="alert" colspan="2"
|
||||
invisible="not show_draft_entries_warning">
|
||||
There are still draft entries in the period you want to lock. You should either post or delete them.
|
||||
<a type="object" class="oe_link fw-bold"
|
||||
name="action_show_draft_moves_in_locked_period">
|
||||
Review
|
||||
</a>
|
||||
</div>
|
||||
<field name="show_posted_tax_closing_warning" invisible="1"/>
|
||||
<div class="alert alert-warning mb-0 d-flex gap-2 flex-wrap"
|
||||
role="alert" colspan="2"
|
||||
invisible="not show_posted_tax_closing_warning">
|
||||
A posted tax return closing entry exists after this tax lock date. You might want to reset the related tax return to non-submitted.
|
||||
<a type="object" class="oe_link fw-bold"
|
||||
name="action_show_posted_tax_closing_in_locked_period">
|
||||
Review
|
||||
</a>
|
||||
</div>
|
||||
<div class="text-muted mb-1 dn_italic" colspan="2">
|
||||
Lock transactions up to specific dates, inclusive
|
||||
</div>
|
||||
|
||||
<!-- The eight exception pointers are technical: they
|
||||
are what the Revoke buttons act on, so they have to
|
||||
be in the view but never in front of the user. -->
|
||||
<field name="min_sale_lock_date_exception_for_me_id" invisible="1"/>
|
||||
<field name="min_purchase_lock_date_exception_for_me_id" invisible="1"/>
|
||||
<field name="min_tax_lock_date_exception_for_me_id" invisible="1"/>
|
||||
<field name="min_fiscalyear_lock_date_exception_for_me_id" invisible="1"/>
|
||||
<field name="min_sale_lock_date_exception_for_everyone_id" invisible="1"/>
|
||||
<field name="min_purchase_lock_date_exception_for_everyone_id" invisible="1"/>
|
||||
<field name="min_tax_lock_date_exception_for_everyone_id" invisible="1"/>
|
||||
<field name="min_fiscalyear_lock_date_exception_for_everyone_id" invisible="1"/>
|
||||
<field name="exception_needed_fields" invisible="1"/>
|
||||
|
||||
<label for="sale_lock_date"/>
|
||||
<div class="d-flex">
|
||||
<field name="sale_lock_date" placeholder="Not locked"
|
||||
class="oe_inline"
|
||||
decoration-info="exception_needed_fields and 'sale_lock_date' in exception_needed_fields"
|
||||
options="{'warning': 'future'}"/>
|
||||
<span class="text-muted o_form_label"
|
||||
invisible="not min_sale_lock_date_exception_for_me_id">
|
||||
For me:
|
||||
<field name="sale_lock_date_for_me" nolabel="1" class="oe_inline"
|
||||
invisible="not sale_lock_date_for_me"/>
|
||||
<a type="object" class="oe_link fw-bold"
|
||||
name="action_revoke_min_sale_lock_date_exception_for_me">
|
||||
Revoke
|
||||
</a>
|
||||
</span>
|
||||
<span class="text-muted o_form_label dn_lock_sep"
|
||||
invisible="not min_sale_lock_date_exception_for_me_id
|
||||
or not min_sale_lock_date_exception_for_everyone_id"/>
|
||||
<span class="text-muted o_form_label"
|
||||
invisible="not min_sale_lock_date_exception_for_everyone_id">
|
||||
For everyone:
|
||||
<field name="sale_lock_date_for_everyone" nolabel="1" class="oe_inline"
|
||||
invisible="not sale_lock_date_for_everyone"/>
|
||||
<a type="object" class="oe_link fw-bold"
|
||||
name="action_revoke_min_sale_lock_date_exception_for_everyone">
|
||||
Revoke
|
||||
</a>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<label for="purchase_lock_date"/>
|
||||
<div class="d-flex">
|
||||
<field name="purchase_lock_date" placeholder="Not locked"
|
||||
class="oe_inline"
|
||||
decoration-info="exception_needed_fields and 'purchase_lock_date' in exception_needed_fields"
|
||||
options="{'warning': 'future'}"/>
|
||||
<span class="text-muted o_form_label"
|
||||
invisible="not min_purchase_lock_date_exception_for_me_id">
|
||||
For me:
|
||||
<field name="purchase_lock_date_for_me" nolabel="1" class="oe_inline"
|
||||
invisible="not purchase_lock_date_for_me"/>
|
||||
<a type="object" class="oe_link fw-bold"
|
||||
name="action_revoke_min_purchase_lock_date_exception_for_me">
|
||||
Revoke
|
||||
</a>
|
||||
</span>
|
||||
<span class="text-muted o_form_label dn_lock_sep"
|
||||
invisible="not min_purchase_lock_date_exception_for_me_id
|
||||
or not min_purchase_lock_date_exception_for_everyone_id"/>
|
||||
<span class="text-muted o_form_label"
|
||||
invisible="not min_purchase_lock_date_exception_for_everyone_id">
|
||||
For everyone:
|
||||
<field name="purchase_lock_date_for_everyone" nolabel="1" class="oe_inline"
|
||||
invisible="not purchase_lock_date_for_everyone"/>
|
||||
<a type="object" class="oe_link fw-bold"
|
||||
name="action_revoke_min_purchase_lock_date_exception_for_everyone">
|
||||
Revoke
|
||||
</a>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<label for="tax_lock_date"/>
|
||||
<div class="d-flex">
|
||||
<field name="tax_lock_date" placeholder="Not locked"
|
||||
class="oe_inline"
|
||||
decoration-info="exception_needed_fields and 'tax_lock_date' in exception_needed_fields"
|
||||
options="{'warning': 'future'}"/>
|
||||
<div class="text-muted dn_italic ms-2"
|
||||
invisible="min_tax_lock_date_exception_for_me_id or min_tax_lock_date_exception_for_everyone_id">
|
||||
after a tax closing
|
||||
</div>
|
||||
<span class="text-muted o_form_label"
|
||||
invisible="not min_tax_lock_date_exception_for_me_id">
|
||||
For me:
|
||||
<field name="tax_lock_date_for_me" nolabel="1" class="oe_inline"
|
||||
invisible="not tax_lock_date_for_me"/>
|
||||
<a type="object" class="oe_link fw-bold"
|
||||
name="action_revoke_min_tax_lock_date_exception_for_me">
|
||||
Revoke
|
||||
</a>
|
||||
</span>
|
||||
<span class="text-muted o_form_label dn_lock_sep"
|
||||
invisible="not min_tax_lock_date_exception_for_me_id
|
||||
or not min_tax_lock_date_exception_for_everyone_id"/>
|
||||
<span class="text-muted o_form_label"
|
||||
invisible="not min_tax_lock_date_exception_for_everyone_id">
|
||||
For everyone:
|
||||
<field name="tax_lock_date_for_everyone" nolabel="1" class="oe_inline"
|
||||
invisible="not tax_lock_date_for_everyone"/>
|
||||
<a type="object" class="oe_link fw-bold"
|
||||
name="action_revoke_min_tax_lock_date_exception_for_everyone">
|
||||
Revoke
|
||||
</a>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<label for="fiscalyear_lock_date"/>
|
||||
<div class="d-flex">
|
||||
<field name="fiscalyear_lock_date" placeholder="Not locked"
|
||||
class="oe_inline"
|
||||
decoration-info="exception_needed_fields and 'fiscalyear_lock_date' in exception_needed_fields"
|
||||
options="{'warning': 'future'}"/>
|
||||
<div class="text-muted dn_italic ms-2"
|
||||
invisible="min_fiscalyear_lock_date_exception_for_me_id or min_fiscalyear_lock_date_exception_for_everyone_id">
|
||||
but allow exceptions
|
||||
</div>
|
||||
<span class="text-muted o_form_label"
|
||||
invisible="not min_fiscalyear_lock_date_exception_for_me_id">
|
||||
For me:
|
||||
<field name="fiscalyear_lock_date_for_me" nolabel="1" class="oe_inline"
|
||||
invisible="not fiscalyear_lock_date_for_me"/>
|
||||
<a type="object" class="oe_link fw-bold"
|
||||
name="action_revoke_min_fiscalyear_lock_date_exception_for_me">
|
||||
Revoke
|
||||
</a>
|
||||
</span>
|
||||
<span class="text-muted o_form_label dn_lock_sep"
|
||||
invisible="not min_fiscalyear_lock_date_exception_for_me_id
|
||||
or not min_fiscalyear_lock_date_exception_for_everyone_id"/>
|
||||
<span class="text-muted o_form_label"
|
||||
invisible="not min_fiscalyear_lock_date_exception_for_everyone_id">
|
||||
For everyone:
|
||||
<field name="fiscalyear_lock_date_for_everyone" nolabel="1" class="oe_inline"
|
||||
invisible="not fiscalyear_lock_date_for_everyone"/>
|
||||
<a type="object" class="oe_link fw-bold"
|
||||
name="action_revoke_min_fiscalyear_lock_date_exception_for_everyone">
|
||||
Revoke
|
||||
</a>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<!-- Exception form. Only shown when the user is trying
|
||||
to move a lock date backwards: a plain forward
|
||||
move needs no justification, and showing the form
|
||||
anyway would suggest it does. -->
|
||||
<div class="alert alert-info ps-3 mt-2 mb-0 d-flex flex-wrap"
|
||||
role="alert" colspan="2" style="white-space: pre;"
|
||||
invisible="not exception_needed_fields">
|
||||
Exception
|
||||
<field name="exception_applies_to" class="oe_inline mx-3"/>
|
||||
<field name="exception_duration" class="oe_inline"/>
|
||||
<field name="exception_reason" placeholder="Reason..."
|
||||
class="oe_inline mx-3 flex-grow-1"
|
||||
widget="text"
|
||||
options="{'line_breaks': False}"
|
||||
invisible="exception_applies_to == 'everyone' and exception_duration == 'forever'"/>
|
||||
</div>
|
||||
|
||||
<div class="d-flex justify-content-start" colspan="2">
|
||||
<div class="alert alert-danger ps-3 mb-3" role="alert">
|
||||
<div>Need an irreversible lock to ensure inalterability, for all users?</div>
|
||||
<div class="d-flex">
|
||||
<label for="hard_lock_date"/>
|
||||
<field name="hard_lock_date" placeholder="Not locked"
|
||||
class="oe_inline mx-3"
|
||||
decoration-info="exception_needed_fields and 'hard_lock_date' in exception_needed_fields"
|
||||
options="{'warning': 'future'}"/>
|
||||
<div class="text-danger o_form_label dn_italic"
|
||||
invisible="hard_lock_date == current_hard_lock_date">
|
||||
This change is irreversible
|
||||
</div>
|
||||
<field name="current_hard_lock_date" invisible="1"/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Closing checklist. Not part of the enterprise
|
||||
dialog, but this module also owns the year-end
|
||||
closing, and locking a period whose result has
|
||||
not been transferred yet makes the closing entry
|
||||
impossible to book. -->
|
||||
<div class="text-muted mt-2 dn_italic" colspan="2">
|
||||
Checks before locking
|
||||
</div>
|
||||
<group colspan="2">
|
||||
<group>
|
||||
<field name="draft_move_count" readonly="1"/>
|
||||
<button name="action_show_draft_moves" type="object"
|
||||
string="Show Draft Entries" class="btn-link"
|
||||
colspan="2" invisible="draft_move_count == 0"/>
|
||||
</group>
|
||||
<group>
|
||||
<field name="unreconciled_count" readonly="1"/>
|
||||
<button name="action_show_unreconciled" type="object"
|
||||
string="Show Unreconciled Items" class="btn-link"
|
||||
colspan="2" invisible="unreconciled_count == 0"/>
|
||||
<field name="unreconciled_statement_count" readonly="1"/>
|
||||
<button name="action_show_unreconciled_statements" type="object"
|
||||
string="Show Unreconciled Bank Transactions" class="btn-link"
|
||||
colspan="2" invisible="unreconciled_statement_count == 0"/>
|
||||
</group>
|
||||
</group>
|
||||
<div class="alert alert-warning mb-0" role="alert" colspan="2"
|
||||
invisible="not has_pl_balance">
|
||||
The period still has a profit and loss balance. Run the year-end closing first, otherwise the closing entry cannot be booked into this period.
|
||||
</div>
|
||||
</group>
|
||||
</sheet>
|
||||
<footer>
|
||||
<button string="Save" name="action_apply" type="object"
|
||||
class="btn-primary" data-hotkey="q"/>
|
||||
<button class="btn-secondary" special="cancel" data-hotkey="x"/>
|
||||
</footer>
|
||||
</form>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
<!-- ============================ fiscal year registry -->
|
||||
<record id="view_dn_fiscal_year_list" model="ir.ui.view">
|
||||
<field name="name">dn.fiscal.year.list</field>
|
||||
<field name="model">dn.fiscal.year</field>
|
||||
<field name="arch" type="xml">
|
||||
<list decoration-success="state == 'closed'"
|
||||
decoration-warning="state == 'open' and locked">
|
||||
<field name="name"/>
|
||||
<field name="date_from"/>
|
||||
<field name="date_to"/>
|
||||
<field name="profit" sum="Total Period Result"/>
|
||||
<field name="state" widget="badge"
|
||||
decoration-success="state == 'closed'"
|
||||
decoration-info="state == 'open'"/>
|
||||
<field name="locked"/>
|
||||
<field name="closing_move_id"/>
|
||||
<field name="currency_id" column_invisible="1"/>
|
||||
<field name="company_id" groups="base.group_multi_company"/>
|
||||
<button name="action_open_closing_wizard" type="object"
|
||||
string="Close" icon="fa-calculator"
|
||||
invisible="state == 'closed'"/>
|
||||
</list>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
<record id="view_dn_fiscal_year_form" model="ir.ui.view">
|
||||
<field name="name">dn.fiscal.year.form</field>
|
||||
<field name="model">dn.fiscal.year</field>
|
||||
<field name="arch" type="xml">
|
||||
<form>
|
||||
<header>
|
||||
<button name="action_open_closing_wizard" type="object"
|
||||
string="Run Closing" class="oe_highlight"
|
||||
invisible="state == 'closed'"/>
|
||||
<button name="action_reopen" type="object"
|
||||
string="Mark as Open"
|
||||
invisible="state != 'closed'"
|
||||
confirm="This only resets the status flag; the closing entry is kept. Continue?"/>
|
||||
</header>
|
||||
<sheet>
|
||||
<div class="oe_title">
|
||||
<h1><field name="name" placeholder="e.g. Fiscal Year 2026"/></h1>
|
||||
</div>
|
||||
<group>
|
||||
<group>
|
||||
<field name="date_from"/>
|
||||
<field name="date_to"/>
|
||||
</group>
|
||||
<group>
|
||||
<field name="state"/>
|
||||
<field name="locked"/>
|
||||
<field name="profit"/>
|
||||
<field name="closing_move_id"/>
|
||||
<field name="currency_id" invisible="1"/>
|
||||
<field name="company_id" groups="base.group_multi_company"/>
|
||||
</group>
|
||||
</group>
|
||||
</sheet>
|
||||
</form>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
<!-- ============================ actions -->
|
||||
<record id="action_dn_fiscal_year_closing" model="ir.actions.act_window">
|
||||
<field name="name">Year-End Closing</field>
|
||||
<field name="res_model">dn.fiscal.year.closing</field>
|
||||
<field name="view_mode">form</field>
|
||||
<field name="target">current</field>
|
||||
<field name="context">{'create': True}</field>
|
||||
</record>
|
||||
|
||||
<record id="action_dn_lock_date_wizard" model="ir.actions.act_window">
|
||||
<field name="name">Lock Journal Entries</field>
|
||||
<field name="res_model">dn.lock.date.wizard</field>
|
||||
<field name="view_mode">form</field>
|
||||
<!-- `target=new` like the enterprise action: the dialog is a side
|
||||
step, the user should land back on the report or list they were
|
||||
looking at once the lock date is saved. -->
|
||||
<field name="target">new</field>
|
||||
<field name="context">{'create': True}</field>
|
||||
</record>
|
||||
|
||||
<record id="action_dn_fiscal_year" model="ir.actions.act_window">
|
||||
<field name="name">Fiscal Years</field>
|
||||
<field name="res_model">dn.fiscal.year</field>
|
||||
<field name="view_mode">list,form</field>
|
||||
</record>
|
||||
|
||||
<!-- ============================ menus -->
|
||||
<menuitem id="menu_dn_accounting_root" name="Closing & Locking"
|
||||
parent="account.menu_finance_entries"
|
||||
sequence="40"
|
||||
groups="account.group_account_manager"/>
|
||||
|
||||
<menuitem id="menu_dn_fiscal_year" name="Fiscal Years"
|
||||
parent="menu_dn_accounting_root"
|
||||
action="action_dn_fiscal_year" sequence="10"/>
|
||||
<!-- Same label as the enterprise menu item so a user migrating from
|
||||
enterprise finds it where they expect. -->
|
||||
<menuitem id="menu_dn_lock_date" name="Lock Dates…"
|
||||
parent="menu_dn_accounting_root"
|
||||
action="action_dn_lock_date_wizard" sequence="20"
|
||||
groups="account.group_account_manager"/>
|
||||
</odoo>
|
||||
241
accountant_cn/views/views__dn_audit_check_views.xml
Normal file
241
accountant_cn/views/views__dn_audit_check_views.xml
Normal file
@@ -0,0 +1,241 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<odoo>
|
||||
<!-- ============================================================
|
||||
Checks — kanban
|
||||
The check is worked through one at a time, so the card shows the
|
||||
description inline rather than hiding it behind a click: the whole
|
||||
point is that the reviewer reads the instruction.
|
||||
============================================================ -->
|
||||
<record id="view_dn_audit_check_kanban" model="ir.ui.view">
|
||||
<field name="name">dn.audit.check.kanban</field>
|
||||
<field name="model">dn.audit.check</field>
|
||||
<field name="arch" type="xml">
|
||||
<kanban default_group_by="result" records_draggable="1" create="1">
|
||||
<!-- `name` has to be declared even though the card prints it
|
||||
through `record.name.raw_value`: the record only carries
|
||||
the fields the view asks for, so reading a raw_value for
|
||||
an undeclared field is `undefined.raw_value` and blows the
|
||||
whole kanban up the moment a record is rendered. -->
|
||||
<field name="name"/>
|
||||
<field name="result"/>
|
||||
<field name="check_type"/>
|
||||
<field name="cycle_id"/>
|
||||
<field name="return_id"/>
|
||||
<field name="attachment_count"/>
|
||||
<templates>
|
||||
<t t-name="card" class="o_dn_audit_check_card">
|
||||
<div class="d-flex flex-column w-100">
|
||||
<div class="d-flex justify-content-between align-items-start gap-2">
|
||||
<strong><field name="name"/></strong>
|
||||
<span t-if="record.check_type.raw_value === 'file'"
|
||||
class="badge text-bg-secondary flex-shrink-0">Document</span>
|
||||
</div>
|
||||
<div t-if="record.cycle_id.raw_value" class="small text-muted mt-1">
|
||||
<field name="cycle_id"/>
|
||||
</div>
|
||||
<div class="small text-muted mt-1" t-if="record.attachment_count.raw_value">
|
||||
<i class="fa fa-paperclip me-1"/><field name="attachment_count"/>
|
||||
</div>
|
||||
</div>
|
||||
</t>
|
||||
<t t-name="menu">
|
||||
<a class="dropdown-item" type="object" name="action_open">Open</a>
|
||||
</t>
|
||||
</templates>
|
||||
</kanban>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
<record id="view_dn_audit_check_form" model="ir.ui.view">
|
||||
<field name="name">dn.audit.check.form</field>
|
||||
<field name="model">dn.audit.check</field>
|
||||
<field name="arch" type="xml">
|
||||
<form string="Check">
|
||||
<header>
|
||||
<!-- Direct method buttons rather than server actions: the
|
||||
whole job is a one-field write, and referencing a
|
||||
server action defined further down the same file
|
||||
resolves at load time, before that record exists. -->
|
||||
<button name="action_mark_done" type="object"
|
||||
string="Mark Done" class="btn-primary"
|
||||
invisible="result in ('done', 'na')"/>
|
||||
<button name="action_mark_na" type="object"
|
||||
string="Not Applicable" invisible="result in ('done', 'na')"/>
|
||||
<field name="result" widget="statusbar"
|
||||
statusbar_visible="todo,done,na,comment"/>
|
||||
</header>
|
||||
<sheet>
|
||||
<div class="oe_title">
|
||||
<label for="name"/>
|
||||
<h1><field name="name"/></h1>
|
||||
</div>
|
||||
<group>
|
||||
<group>
|
||||
<field name="return_id" readonly="1"/>
|
||||
<field name="cycle_id"/>
|
||||
<field name="check_type"/>
|
||||
</group>
|
||||
<group>
|
||||
<field name="user_id"/>
|
||||
<field name="date_review"/>
|
||||
<field name="date_from" invisible="1"/>
|
||||
<field name="date_to" invisible="1"/>
|
||||
</group>
|
||||
</group>
|
||||
<group string="Instructions">
|
||||
<field name="description" nolabel="1" colspan="2" readonly="1"/>
|
||||
</group>
|
||||
<group string="Review">
|
||||
<field name="comment" nolabel="1" colspan="2"
|
||||
placeholder="What did you check, and what did you find?"/>
|
||||
</group>
|
||||
<group string="Documents"
|
||||
invisible="check_type != 'file' and not attachment_ids">
|
||||
<field name="attachment_ids" nolabel="1" colspan="2"
|
||||
widget="many2many_binary"/>
|
||||
</group>
|
||||
</sheet>
|
||||
</form>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
<record id="view_dn_audit_check_list" model="ir.ui.view">
|
||||
<field name="name">dn.audit.check.list</field>
|
||||
<field name="model">dn.audit.check</field>
|
||||
<field name="arch" type="xml">
|
||||
<list string="Checks" decoration-danger="result == 'todo'"
|
||||
decoration-success="result in ('done', 'na')">
|
||||
<field name="return_id"/>
|
||||
<field name="name"/>
|
||||
<field name="cycle_id"/>
|
||||
<field name="check_type"/>
|
||||
<field name="result" widget="badge"
|
||||
decoration-danger="result == 'todo'"
|
||||
decoration-success="result in ('done', 'na')"
|
||||
decoration-warning="result == 'comment'"/>
|
||||
<field name="user_id"/>
|
||||
<field name="date_review"/>
|
||||
<field name="attachment_count"/>
|
||||
</list>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
<record id="view_dn_audit_check_search" model="ir.ui.view">
|
||||
<field name="name">dn.audit.check.search</field>
|
||||
<field name="model">dn.audit.check</field>
|
||||
<field name="arch" type="xml">
|
||||
<search>
|
||||
<field name="name"/>
|
||||
<field name="return_id"/>
|
||||
<field name="cycle_id"/>
|
||||
<filter name="todo" string="To Do" domain="[('result', '=', 'todo')]"/>
|
||||
<filter name="done" string="Done" domain="[('result', '=', 'done')]"/>
|
||||
<filter name="na" string="Not Applicable" domain="[('result', '=', 'na')]"/>
|
||||
<separator/>
|
||||
<filter name="mine" string="Assigned to Me"
|
||||
domain="[('user_id', '=', uid)]"/>
|
||||
<separator/>
|
||||
<filter name="group_cycle" string="Cycle" context="{'group_by': 'cycle_id'}"/>
|
||||
<filter name="group_result" string="Result" context="{'group_by': 'result'}"/>
|
||||
</search>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
<record id="action_dn_audit_check" model="ir.actions.act_window">
|
||||
<field name="name">Checks</field>
|
||||
<field name="res_model">dn.audit.check</field>
|
||||
<field name="view_mode">kanban,list,form</field>
|
||||
<field name="search_view_id" ref="view_dn_audit_check_search"/>
|
||||
<field name="context">{'search_default_todo': 1}</field>
|
||||
</record>
|
||||
|
||||
<!-- Small server actions, so the two statusbar buttons on the check form
|
||||
do not need a wizard just to write a selection value. -->
|
||||
<record id="action_dn_audit_check_set_done" model="ir.actions.server">
|
||||
<field name="name">Mark Check Done</field>
|
||||
<field name="model_id" ref="model_dn_audit_check"/>
|
||||
<field name="binding_model_id" ref="model_dn_audit_check"/>
|
||||
<field name="binding_view_types">form</field>
|
||||
<field name="state">code</field>
|
||||
<field name="code">records.action_set_result('done')</field>
|
||||
</record>
|
||||
<record id="action_dn_audit_check_set_na" model="ir.actions.server">
|
||||
<field name="name">Mark Check Not Applicable</field>
|
||||
<field name="model_id" ref="model_dn_audit_check"/>
|
||||
<field name="binding_model_id" ref="model_dn_audit_check"/>
|
||||
<field name="binding_view_types">form</field>
|
||||
<field name="state">code</field>
|
||||
<field name="code">records.action_set_result('na')</field>
|
||||
</record>
|
||||
|
||||
<!-- ============================================================
|
||||
Cycles and templates — configuration
|
||||
============================================================ -->
|
||||
<record id="view_dn_audit_cycle_list" model="ir.ui.view">
|
||||
<field name="name">dn.audit.cycle.list</field>
|
||||
<field name="model">dn.audit.cycle</field>
|
||||
<field name="arch" type="xml">
|
||||
<list editable="bottom" string="Audit Cycles">
|
||||
<field name="sequence" widget="handle"/>
|
||||
<field name="name"/>
|
||||
<field name="code"/>
|
||||
<field name="description"/>
|
||||
<field name="active" widget="boolean_toggle"/>
|
||||
</list>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
<record id="action_dn_audit_cycle" model="ir.actions.act_window">
|
||||
<field name="name">Audit Cycles</field>
|
||||
<field name="res_model">dn.audit.cycle</field>
|
||||
<field name="view_mode">list,form</field>
|
||||
</record>
|
||||
|
||||
<record id="view_dn_audit_check_template_list" model="ir.ui.view">
|
||||
<field name="name">dn.audit.check.template.list</field>
|
||||
<field name="model">dn.audit.check.template</field>
|
||||
<field name="arch" type="xml">
|
||||
<list editable="bottom" string="Check Templates">
|
||||
<field name="sequence" widget="handle"/>
|
||||
<field name="name"/>
|
||||
<field name="cycle_id"/>
|
||||
<field name="check_type"/>
|
||||
<field name="active" widget="boolean_toggle"/>
|
||||
</list>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
<record id="view_dn_audit_check_template_form" model="ir.ui.view">
|
||||
<field name="name">dn.audit.check.template.form</field>
|
||||
<field name="model">dn.audit.check.template</field>
|
||||
<field name="arch" type="xml">
|
||||
<form string="Check Template">
|
||||
<sheet>
|
||||
<div class="oe_title">
|
||||
<label for="name"/>
|
||||
<h1><field name="name"/></h1>
|
||||
</div>
|
||||
<group>
|
||||
<group>
|
||||
<field name="cycle_id"/>
|
||||
<field name="check_type"/>
|
||||
<field name="sequence"/>
|
||||
</group>
|
||||
<group>
|
||||
<field name="active"/>
|
||||
</group>
|
||||
</group>
|
||||
<group string="Instructions">
|
||||
<field name="description" nolabel="1" colspan="2"/>
|
||||
</group>
|
||||
</sheet>
|
||||
</form>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
<record id="action_dn_audit_check_template" model="ir.actions.act_window">
|
||||
<field name="name">Check Templates</field>
|
||||
<field name="res_model">dn.audit.check.template</field>
|
||||
<field name="view_mode">list,form</field>
|
||||
</record>
|
||||
</odoo>
|
||||
22
accountant_cn/views/views__dn_audit_menus.xml
Normal file
22
accountant_cn/views/views__dn_audit_menus.xml
Normal file
@@ -0,0 +1,22 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<odoo>
|
||||
<!-- Working Files replaces the stop-gap journal-item list that used to sit
|
||||
under Review > Audit. The xmlid `dn_account_full_menu.menu_action_working_files`
|
||||
is what the menu tree already points at, so the entry keeps its place
|
||||
(Review > Audit, sequence 10) and only its target changes. -->
|
||||
<record id="accountant_cn.menu_action_working_files" model="ir.ui.menu">
|
||||
<field name="name">Working Files</field>
|
||||
<field name="action" ref="action_dn_audit_return"/>
|
||||
</record>
|
||||
|
||||
<menuitem id="menu_dn_audit_config" name="Working Files"
|
||||
parent="account.menu_finance_configuration" sequence="95"
|
||||
groups="account.group_account_manager">
|
||||
<menuitem id="menu_dn_audit_cycle" name="Audit Cycles"
|
||||
action="action_dn_audit_cycle" sequence="10"/>
|
||||
<menuitem id="menu_dn_audit_check_template" name="Check Templates"
|
||||
action="action_dn_audit_check_template" sequence="20"/>
|
||||
<menuitem id="menu_dn_audit_all_returns" name="All Working Files"
|
||||
action="action_dn_audit_return_all" sequence="30"/>
|
||||
</menuitem>
|
||||
</odoo>
|
||||
242
accountant_cn/views/views__dn_audit_return_views.xml
Normal file
242
accountant_cn/views/views__dn_audit_return_views.xml
Normal file
@@ -0,0 +1,242 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<odoo>
|
||||
<!-- ============================================================
|
||||
Working file — kanban
|
||||
Grouped by review status, because that is the question a reviewer
|
||||
asks first ("what is still open?"), not "which period is this".
|
||||
============================================================ -->
|
||||
<record id="view_dn_audit_return_kanban" model="ir.ui.view">
|
||||
<field name="name">dn.audit.return.kanban</field>
|
||||
<field name="model">dn.audit.return</field>
|
||||
<field name="arch" type="xml">
|
||||
<kanban default_group_by="review_state" class="o_kanban_mobile"
|
||||
records_draggable="0" create="1">
|
||||
<field name="review_state"/>
|
||||
<field name="is_completed"/>
|
||||
<field name="is_late"/>
|
||||
<field name="check_count"/>
|
||||
<field name="resolved_check_count"/>
|
||||
<field name="progress"/>
|
||||
<templates>
|
||||
<t t-name="card" class="o_dn_audit_card">
|
||||
<div class="d-flex flex-column w-100 h-100">
|
||||
<div class="d-flex flex-row justify-content-between w-100 px-2 py-2 gap-2">
|
||||
<h5 class="text-truncate mb-0" t-att-title="record.name.raw_value">
|
||||
<field name="name"/>
|
||||
</h5>
|
||||
<span t-if="record.is_late.raw_value"
|
||||
class="badge rounded-pill text-bg-danger flex-shrink-0"
|
||||
title="Past its deadline">Late</span>
|
||||
</div>
|
||||
|
||||
<div class="d-flex flex-column w-100 px-2 gap-2">
|
||||
<div class="d-flex justify-content-between small text-muted">
|
||||
<span><field name="date_from"/></span>
|
||||
<span>→</span>
|
||||
<span><field name="date_to"/></span>
|
||||
</div>
|
||||
|
||||
<div class="w-100">
|
||||
<div class="d-flex justify-content-between small">
|
||||
<span>Checks</span>
|
||||
<span class="text-muted">
|
||||
<field name="resolved_check_count"/> / <field name="check_count"/>
|
||||
</span>
|
||||
</div>
|
||||
<div class="progress mt-1" style="height: 6px;">
|
||||
<div class="progress-bar bg-success" role="progressbar"
|
||||
t-att-style="'width: ' + record.progress.raw_value + '%'"
|
||||
t-att-aria-valuenow="record.progress.raw_value"
|
||||
aria-valuemin="0" aria-valuemax="100"/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="d-flex flex-row-reverse w-100 mt-auto px-2 py-2 align-items-center">
|
||||
<field name="activity_ids" widget="kanban_activity"/>
|
||||
</div>
|
||||
</div>
|
||||
</t>
|
||||
|
||||
<t t-name="menu">
|
||||
<a class="dropdown-item" type="object" name="action_pause"
|
||||
t-if="record.review_state.raw_value === 'ongoing'">Pause</a>
|
||||
<a class="dropdown-item" type="object" name="action_resume"
|
||||
t-if="record.review_state.raw_value === 'paused'">Resume</a>
|
||||
<a class="dropdown-item" type="object" name="action_mark_done"
|
||||
t-if="!record.is_completed.raw_value">Mark as Done</a>
|
||||
<a class="dropdown-item" type="object" name="action_reset_to_ongoing"
|
||||
t-if="record.is_completed.raw_value">Reset to Ongoing</a>
|
||||
<a class="dropdown-item" type="object" name="action_load_templates">Load Check Templates</a>
|
||||
<a class="dropdown-item" type="object" name="action_view_checks">Open Checks</a>
|
||||
</t>
|
||||
</templates>
|
||||
</kanban>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
<!-- ============================================================
|
||||
Working file — form
|
||||
============================================================ -->
|
||||
<record id="view_dn_audit_return_form" model="ir.ui.view">
|
||||
<field name="name">dn.audit.return.form</field>
|
||||
<field name="model">dn.audit.return</field>
|
||||
<field name="arch" type="xml">
|
||||
<form string="Working File">
|
||||
<header>
|
||||
<button name="action_mark_done" type="object"
|
||||
string="Mark as Done" class="btn-primary"
|
||||
invisible="is_completed"/>
|
||||
<button name="action_pause" type="object" string="Pause"
|
||||
invisible="review_state != 'ongoing'"/>
|
||||
<button name="action_resume" type="object" string="Resume"
|
||||
invisible="review_state != 'paused'"/>
|
||||
<button name="action_reset_to_ongoing" type="object"
|
||||
string="Reset to Ongoing" invisible="not is_completed"/>
|
||||
<button name="action_load_templates" type="object"
|
||||
string="Load Check Templates"/>
|
||||
<field name="review_state" widget="statusbar"
|
||||
statusbar_visible="ongoing,paused,done"/>
|
||||
</header>
|
||||
<sheet>
|
||||
<div class="oe_title">
|
||||
<label for="name"/>
|
||||
<h1><field name="name" placeholder="e.g. 2026-10 Close"/></h1>
|
||||
</div>
|
||||
<group>
|
||||
<group string="Period">
|
||||
<field name="date_from"/>
|
||||
<field name="date_to"/>
|
||||
<field name="date_deadline"/>
|
||||
</group>
|
||||
<group string="Organisation">
|
||||
<field name="company_id" groups="base.group_multi_company"/>
|
||||
<field name="currency_id" invisible="1"/>
|
||||
<field name="cycle_ids" widget="many2many_tags"
|
||||
options="{'no_create': True}"/>
|
||||
</group>
|
||||
</group>
|
||||
|
||||
<div class="d-flex gap-3 my-3">
|
||||
<div class="alert alert-info mb-0 flex-grow-1" role="status">
|
||||
<strong><field name="resolved_check_count"/> / <field name="check_count"/></strong>
|
||||
checks resolved —
|
||||
<strong><field name="unresolved_check_count"/></strong> outstanding.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<notebook>
|
||||
<page string="Checks" name="checks">
|
||||
<field name="check_ids" nolabel="1">
|
||||
<list editable="bottom" decoration-danger="result == 'todo'"
|
||||
decoration-success="result in ('done', 'na')">
|
||||
<field name="sequence" widget="handle"/>
|
||||
<field name="name"/>
|
||||
<field name="cycle_id"/>
|
||||
<field name="check_type"/>
|
||||
<field name="result"/>
|
||||
<field name="user_id"/>
|
||||
<field name="date_review"/>
|
||||
<field name="comment" optional="hide"/>
|
||||
</list>
|
||||
</field>
|
||||
</page>
|
||||
<page string="Notes" name="notes">
|
||||
<field name="notes" placeholder="Working notes for this period..."/>
|
||||
</page>
|
||||
</notebook>
|
||||
</sheet>
|
||||
<chatter/>
|
||||
</form>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
<!-- ============================================================
|
||||
Working file — list
|
||||
============================================================ -->
|
||||
<record id="view_dn_audit_return_list" model="ir.ui.view">
|
||||
<field name="name">dn.audit.return.list</field>
|
||||
<field name="model">dn.audit.return</field>
|
||||
<field name="arch" type="xml">
|
||||
<list string="Working Files"
|
||||
decoration-danger="is_late"
|
||||
decoration-muted="is_completed">
|
||||
<field name="name"/>
|
||||
<field name="date_from"/>
|
||||
<field name="date_to"/>
|
||||
<field name="date_deadline"/>
|
||||
<field name="review_state" widget="badge"
|
||||
decoration-info="review_state == 'ongoing'"
|
||||
decoration-warning="review_state == 'paused'"
|
||||
decoration-success="review_state == 'done'"/>
|
||||
<field name="check_count" string="Checks"/>
|
||||
<field name="unresolved_check_count" string="Issues"/>
|
||||
<field name="progress" widget="progressbar" optional="show"/>
|
||||
<field name="company_id" groups="base.group_multi_company" optional="hide"/>
|
||||
</list>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
<!-- ============================================================
|
||||
Working file — search
|
||||
============================================================ -->
|
||||
<record id="view_dn_audit_return_search" model="ir.ui.view">
|
||||
<field name="name">dn.audit.return.search</field>
|
||||
<field name="model">dn.audit.return</field>
|
||||
<field name="arch" type="xml">
|
||||
<search>
|
||||
<field name="name"/>
|
||||
<field name="date_from"/>
|
||||
<field name="date_to"/>
|
||||
<field name="date_deadline"/>
|
||||
<field name="cycle_ids"/>
|
||||
<filter name="ongoing" string="Ongoing"
|
||||
domain="[('review_state', '=', 'ongoing')]"/>
|
||||
<filter name="paused" string="Paused"
|
||||
domain="[('review_state', '=', 'paused')]"/>
|
||||
<filter name="done" string="Done"
|
||||
domain="[('review_state', '=', 'done')]"/>
|
||||
<separator/>
|
||||
<!-- `is_late` is a non-stored computed field, so it cannot be
|
||||
used in a search domain. The equivalent domain compares
|
||||
the deadline against today directly, which also keeps the
|
||||
semantics honest: a file is late because its deadline has
|
||||
passed, not because a cached flag says so. -->
|
||||
<filter name="late" string="Late"
|
||||
domain="[('date_deadline', '<', 'today'), ('is_completed', '=', False)]"/>
|
||||
<filter name="archived" string="Archived"
|
||||
domain="[('active', '=', False)]"/>
|
||||
<separator/>
|
||||
<filter name="group_cycle" string="Cycle"
|
||||
context="{'group_by': 'cycle_ids'}"/>
|
||||
<filter name="group_state" string="Review Status"
|
||||
context="{'group_by': 'review_state'}"/>
|
||||
<filter name="group_company" string="Company"
|
||||
context="{'group_by': 'company_id'}"
|
||||
groups="base.group_multi_company"/>
|
||||
</search>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
<!-- ============================================================
|
||||
Actions
|
||||
============================================================ -->
|
||||
<record id="action_dn_audit_return" model="ir.actions.act_window">
|
||||
<field name="name">Working Files</field>
|
||||
<field name="res_model">dn.audit.return</field>
|
||||
<field name="view_mode">kanban,list,form</field>
|
||||
<field name="search_view_id" ref="view_dn_audit_return_search"/>
|
||||
<field name="context">{'search_default_ongoing': 1, 'search_default_paused': 1}</field>
|
||||
<field name="help" type="html">
|
||||
<p class="o_view_nocontent_smiling_face">No pending working files</p>
|
||||
<p>Create a working file to start your next period review.</p>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
<record id="action_dn_audit_return_all" model="ir.actions.act_window">
|
||||
<field name="name">All Working Files</field>
|
||||
<field name="res_model">dn.audit.return</field>
|
||||
<field name="view_mode">kanban,list,form</field>
|
||||
<field name="search_view_id" ref="view_dn_audit_return_search"/>
|
||||
</record>
|
||||
</odoo>
|
||||
158
accountant_cn/views/views__dn_bank_rec_views.xml
Normal file
158
accountant_cn/views/views__dn_bank_rec_views.xml
Normal file
@@ -0,0 +1,158 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<odoo>
|
||||
<!-- ============================ reconciliation session form -->
|
||||
<record id="view_dn_bank_rec_wizard_form" model="ir.ui.view">
|
||||
<field name="name">dn.bank.rec.wizard.form</field>
|
||||
<field name="model">dn.bank.rec.wizard</field>
|
||||
<field name="arch" type="xml">
|
||||
<form string="Bank Reconciliation">
|
||||
<header>
|
||||
<button name="action_match_selected" type="object"
|
||||
string="Match Selected" class="oe_highlight"/>
|
||||
<button name="action_create_counterpart" type="object"
|
||||
string="Create Entry and Reconcile"/>
|
||||
<button name="action_apply_rules" type="object"
|
||||
string="Apply Rules"/>
|
||||
<button name="action_unreconcile" type="object"
|
||||
string="Undo Reconciliation"
|
||||
confirm="Undo the reconciliation of this bank transaction?"/>
|
||||
<button name="action_refresh_candidates" type="object"
|
||||
string="Recompute Suggestions" class="btn-link"/>
|
||||
</header>
|
||||
<sheet>
|
||||
<div class="oe_title">
|
||||
<h2><field name="payment_ref" readonly="1" placeholder="No label"/></h2>
|
||||
</div>
|
||||
|
||||
<group>
|
||||
<group string="Bank Transaction">
|
||||
<field name="date" readonly="1"/>
|
||||
<field name="journal_id" readonly="1"/>
|
||||
<field name="partner_id" readonly="1"/>
|
||||
<field name="amount" readonly="1"/>
|
||||
<field name="currency_id" invisible="1"/>
|
||||
<field name="company_id" invisible="1"/>
|
||||
</group>
|
||||
<group string="Progress">
|
||||
<field name="remaining_amount" readonly="1"/>
|
||||
<field name="suggestion_count" readonly="1"/>
|
||||
</group>
|
||||
</group>
|
||||
|
||||
<notebook>
|
||||
<page string="Suggested Matches" name="candidates">
|
||||
<field name="candidate_ids" nolabel="1">
|
||||
<list create="0" delete="0"
|
||||
decoration-success="selected">
|
||||
<field name="score" string="Score"/>
|
||||
<field name="reason" string="Why"/>
|
||||
<field name="date"/>
|
||||
<field name="move_name"/>
|
||||
<field name="label"/>
|
||||
<field name="partner_id"/>
|
||||
<field name="account_id"/>
|
||||
<field name="amount_residual" sum="Total"/>
|
||||
<field name="selected" widget="boolean_toggle"/>
|
||||
<field name="currency_id" column_invisible="True"/>
|
||||
<field name="move_line_id" column_invisible="True"/>
|
||||
</list>
|
||||
</field>
|
||||
<div class="text-muted small mt-2">
|
||||
Flag the rows to settle and press Match Selected. Several rows can be
|
||||
selected to split one bank transaction across multiple documents.
|
||||
</div>
|
||||
</page>
|
||||
|
||||
<page string="Manual Entry" name="manual">
|
||||
<group>
|
||||
<group string="Counterpart">
|
||||
<field name="counterpart_account_id"/>
|
||||
<field name="manual_label"/>
|
||||
<field name="manual_partner_id"/>
|
||||
</group>
|
||||
<group string="Amount and Tax">
|
||||
<field name="manual_amount"/>
|
||||
<field name="manual_tax_id"/>
|
||||
</group>
|
||||
</group>
|
||||
<div class="text-muted small">
|
||||
Fill this in and press Create Entry and Reconcile: a counterpart line
|
||||
is added to the bank transaction's entry and reconciled right away.
|
||||
</div>
|
||||
</page>
|
||||
</notebook>
|
||||
</sheet>
|
||||
</form>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
<!-- ============================ statement line workspace -->
|
||||
<record id="view_dn_statement_line_list" model="ir.ui.view">
|
||||
<field name="name">dn.statement.line.list</field>
|
||||
<field name="model">account.bank.statement.line</field>
|
||||
<field name="arch" type="xml">
|
||||
<list string="Bank Transactions" create="0" delete="0"
|
||||
decoration-success="is_reconciled"
|
||||
decoration-warning="not is_reconciled">
|
||||
<field name="date"/>
|
||||
<field name="journal_id"/>
|
||||
<field name="payment_ref"/>
|
||||
<field name="partner_id"/>
|
||||
<field name="amount" sum="Total"/>
|
||||
<field name="currency_id" column_invisible="True"/>
|
||||
<field name="is_reconciled" widget="boolean_toggle"/>
|
||||
<button name="action_open_dn_reconciliation" type="object"
|
||||
string="Reconcile" icon="fa-handshake-o"
|
||||
invisible="is_reconciled"/>
|
||||
</list>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
<record id="view_dn_statement_line_search" model="ir.ui.view">
|
||||
<field name="name">dn.statement.line.search</field>
|
||||
<field name="model">account.bank.statement.line</field>
|
||||
<field name="arch" type="xml">
|
||||
<search>
|
||||
<field name="payment_ref"/>
|
||||
<field name="partner_id"/>
|
||||
<field name="journal_id"/>
|
||||
<filter name="unreconciled" string="Unreconciled"
|
||||
domain="[('is_reconciled', '=', False)]"/>
|
||||
<filter name="reconciled" string="Reconciled"
|
||||
domain="[('is_reconciled', '=', True)]"/>
|
||||
<group>
|
||||
<filter name="group_journal" string="Journal"
|
||||
context="{'group_by': 'journal_id'}"/>
|
||||
<filter name="group_date" string="Date"
|
||||
context="{'group_by': 'date'}"/>
|
||||
</group>
|
||||
</search>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
<record id="action_dn_statement_line_workspace" model="ir.actions.act_window">
|
||||
<field name="name">Bank Transaction Matching</field>
|
||||
<field name="res_model">account.bank.statement.line</field>
|
||||
<field name="view_mode">list</field>
|
||||
<field name="search_view_id" ref="view_dn_statement_line_search"/>
|
||||
<field name="domain">[('is_reconciled', '=', False)]</field>
|
||||
</record>
|
||||
|
||||
<record id="action_dn_bank_rec_wizard" model="ir.actions.act_window">
|
||||
<field name="name">Bank Reconciliation</field>
|
||||
<field name="res_model">dn.bank.rec.wizard</field>
|
||||
<field name="view_mode">form</field>
|
||||
<field name="target">current</field>
|
||||
<field name="context">{'create': False}</field>
|
||||
</record>
|
||||
|
||||
<!-- ============================ menus -->
|
||||
<menuitem id="menu_dn_bank_rec_root" name="Bank Reconciliation"
|
||||
parent="account.menu_finance_entries"
|
||||
sequence="35"
|
||||
groups="account.group_account_user"/>
|
||||
|
||||
<menuitem id="menu_dn_bank_rec_workspace" name="Transactions to Match"
|
||||
parent="menu_dn_bank_rec_root"
|
||||
action="action_dn_statement_line_workspace" sequence="10"/>
|
||||
</odoo>
|
||||
132
accountant_cn/views/views__dn_fr_actions.xml
Normal file
132
accountant_cn/views/views__dn_fr_actions.xml
Normal file
@@ -0,0 +1,132 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<odoo>
|
||||
<!-- ============================ client actions, one per report -->
|
||||
<record id="action_dn_fr_view" model="ir.actions.client">
|
||||
<field name="name">Financial Report Preview</field>
|
||||
<field name="tag">dn_fr_view</field>
|
||||
</record>
|
||||
|
||||
<record id="action_dn_fr_tb" model="ir.actions.client">
|
||||
<field name="name">Trial Balance</field>
|
||||
<field name="tag">dn_fr_view</field>
|
||||
<field name="params" eval="{'report_code': 'DN_TB'}"/>
|
||||
</record>
|
||||
<record id="action_dn_fr_pl" model="ir.actions.client">
|
||||
<field name="name">Profit and Loss</field>
|
||||
<field name="tag">dn_fr_view</field>
|
||||
<field name="params" eval="{'report_code': 'DN_PL'}"/>
|
||||
</record>
|
||||
<record id="action_dn_fr_bs" model="ir.actions.client">
|
||||
<field name="name">Balance Sheet</field>
|
||||
<field name="tag">dn_fr_view</field>
|
||||
<field name="params" eval="{'report_code': 'DN_BS'}"/>
|
||||
</record>
|
||||
<record id="action_dn_fr_gl" model="ir.actions.client">
|
||||
<field name="name">General Ledger</field>
|
||||
<field name="tag">dn_fr_view</field>
|
||||
<field name="params" eval="{'report_code': 'DN_GL'}"/>
|
||||
</record>
|
||||
<record id="action_dn_fr_partner" model="ir.actions.client">
|
||||
<field name="name">Partner Ledger</field>
|
||||
<field name="tag">dn_fr_view</field>
|
||||
<field name="params" eval="{'report_code': 'DN_PARTNER'}"/>
|
||||
</record>
|
||||
<record id="action_dn_fr_ar" model="ir.actions.client">
|
||||
<field name="name">Aged Receivable</field>
|
||||
<field name="tag">dn_fr_view</field>
|
||||
<field name="params" eval="{'report_code': 'DN_AR'}"/>
|
||||
</record>
|
||||
<record id="action_dn_fr_ap" model="ir.actions.client">
|
||||
<field name="name">Aged Payable</field>
|
||||
<field name="tag">dn_fr_view</field>
|
||||
<field name="params" eval="{'report_code': 'DN_AP'}"/>
|
||||
</record>
|
||||
<record id="action_dn_fr_cf" model="ir.actions.client">
|
||||
<field name="name">Cash Flow Statement</field>
|
||||
<field name="tag">dn_fr_view</field>
|
||||
<field name="params" eval="{'report_code': 'DN_CF'}"/>
|
||||
</record>
|
||||
<record id="action_dn_fr_journal" model="ir.actions.client">
|
||||
<field name="name">Journal Audit</field>
|
||||
<field name="tag">dn_fr_view</field>
|
||||
<field name="params" eval="{'report_code': 'DN_JOURNAL'}"/>
|
||||
</record>
|
||||
<record id="action_dn_fr_tax" model="ir.actions.client">
|
||||
<field name="name">Tax Summary</field>
|
||||
<field name="tag">dn_fr_view</field>
|
||||
<field name="params" eval="{'report_code': 'DN_TAX'}"/>
|
||||
</record>
|
||||
<record id="action_dn_fr_sales" model="ir.actions.client">
|
||||
<field name="name">Sales Analysis</field>
|
||||
<field name="tag">dn_fr_view</field>
|
||||
<field name="params" eval="{'report_code': 'DN_SALES'}"/>
|
||||
</record>
|
||||
<record id="action_dn_fr_exec" model="ir.actions.client">
|
||||
<field name="name">Executive Summary</field>
|
||||
<field name="tag">dn_fr_view</field>
|
||||
<field name="params" eval="{'report_code': 'DN_EXEC'}"/>
|
||||
</record>
|
||||
<record id="action_dn_fr_open_items" model="ir.actions.client">
|
||||
<field name="name">Open Items</field>
|
||||
<field name="tag">dn_fr_view</field>
|
||||
<field name="params" eval="{'report_code': 'DN_OPEN_ITEMS'}"/>
|
||||
</record>
|
||||
<record id="action_dn_fr_statement" model="ir.actions.client">
|
||||
<field name="name">Customer Statement</field>
|
||||
<field name="tag">dn_fr_view</field>
|
||||
<field name="params" eval="{'report_code': 'DN_STATEMENT'}"/>
|
||||
</record>
|
||||
<record id="action_dn_fr_deferred" model="ir.actions.client">
|
||||
<field name="name">Deferred Revenues and Expenses</field>
|
||||
<field name="tag">dn_fr_view</field>
|
||||
<field name="params" eval="{'report_code': 'DN_DEFERRED'}"/>
|
||||
</record>
|
||||
<record id="action_dn_fr_deferred_revenue" model="ir.actions.client">
|
||||
<field name="name">Deferred Revenues</field>
|
||||
<field name="tag">dn_fr_view</field>
|
||||
<field name="params" eval="{'report_code': 'DN_DEFERRED_REV'}"/>
|
||||
</record>
|
||||
<record id="action_dn_fr_deferred_expense" model="ir.actions.client">
|
||||
<field name="name">Deferred Expenses</field>
|
||||
<field name="tag">dn_fr_view</field>
|
||||
<field name="params" eval="{'report_code': 'DN_DEFERRED_EXP'}"/>
|
||||
</record>
|
||||
<record id="action_dn_fr_fx" model="ir.actions.client">
|
||||
<field name="name">Unrealized Currency Gains and Losses</field>
|
||||
<field name="tag">dn_fr_view</field>
|
||||
<field name="params" eval="{'report_code': 'DN_FX'}"/>
|
||||
</record>
|
||||
<record id="action_dn_fr_interco" model="ir.actions.client">
|
||||
<field name="name">Intercompany Comparison</field>
|
||||
<field name="tag">dn_fr_view</field>
|
||||
<field name="params" eval="{'report_code': 'DN_INTERCO'}"/>
|
||||
</record>
|
||||
<record id="action_dn_fr_bankrec" model="ir.actions.client">
|
||||
<field name="name">Bank Reconciliation Status</field>
|
||||
<field name="tag">dn_fr_view</field>
|
||||
<field name="params" eval="{'report_code': 'DN_BANKREC'}"/>
|
||||
</record>
|
||||
<record id="action_dn_fr_annual" model="ir.actions.client">
|
||||
<field name="name">Annual Statements</field>
|
||||
<field name="tag">dn_fr_view</field>
|
||||
<field name="params" eval="{'report_code': 'DN_ANNUAL'}"/>
|
||||
</record>
|
||||
<record id="action_dn_fr_depreciation" model="ir.actions.client">
|
||||
<field name="name">Depreciation Schedule</field>
|
||||
<field name="tag">dn_fr_view</field>
|
||||
<field name="params" eval="{'report_code': 'DN_DEPRECIATION'}"/>
|
||||
</record>
|
||||
|
||||
<!-- ============================ windows -->
|
||||
<record id="action_dn_fr_config" model="ir.actions.act_window">
|
||||
<field name="name">Report Definitions</field>
|
||||
<field name="res_model">dn.fr</field>
|
||||
<field name="view_mode">list,form</field>
|
||||
</record>
|
||||
|
||||
<record id="action_dn_fr_external_value" model="ir.actions.act_window">
|
||||
<field name="name">Report Manual Values</field>
|
||||
<field name="res_model">dn.fr.external.value</field>
|
||||
<field name="view_mode">list,form</field>
|
||||
</record>
|
||||
</odoo>
|
||||
84
accountant_cn/views/views__dn_fr_menus.xml
Normal file
84
accountant_cn/views/views__dn_fr_menus.xml
Normal file
@@ -0,0 +1,84 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<odoo>
|
||||
<!--
|
||||
Report entries live under the Enterprise report groups, mounted by
|
||||
`dn_account_full_menu` (REPORTING > Statement Reports / Ledgers /
|
||||
Partner Reports / Taxes & Fiscal / Management / Review). The menus in
|
||||
this file are therefore kept only as a switchable "flat" alternative
|
||||
and are inactive by default, so a report never appears twice.
|
||||
|
||||
Action xmlids are unchanged: `dn_account_full_menu` points at them.
|
||||
-->
|
||||
<menuitem id="menu_dn_fr_root" name="DN Financial Reports (flat)"
|
||||
parent="account.menu_finance_reports"
|
||||
sequence="95"
|
||||
active="False"
|
||||
groups="account.group_account_readonly"/>
|
||||
|
||||
<menuitem id="menu_dn_fr_exec" name="Executive Summary" parent="menu_dn_fr_root"
|
||||
action="action_dn_fr_exec" sequence="5" active="False"/>
|
||||
|
||||
<menuitem id="menu_dn_fr_financial" name="Financial Statements"
|
||||
parent="menu_dn_fr_root" sequence="10" active="False"/>
|
||||
<menuitem id="menu_dn_fr_bs" name="Balance Sheet" parent="menu_dn_fr_financial"
|
||||
action="action_dn_fr_bs" sequence="10" active="False"/>
|
||||
<menuitem id="menu_dn_fr_pl" name="Profit and Loss" parent="menu_dn_fr_financial"
|
||||
action="action_dn_fr_pl" sequence="20" active="False"/>
|
||||
<menuitem id="menu_dn_fr_cf" name="Cash Flow Statement" parent="menu_dn_fr_financial"
|
||||
action="action_dn_fr_cf" sequence="30" active="False"/>
|
||||
<menuitem id="menu_dn_fr_tb" name="Trial Balance" parent="menu_dn_fr_financial"
|
||||
action="action_dn_fr_tb" sequence="40" active="False"/>
|
||||
<menuitem id="menu_dn_fr_annual" name="Annual Statements" parent="menu_dn_fr_financial"
|
||||
action="action_dn_fr_annual" sequence="50" active="False"/>
|
||||
|
||||
<menuitem id="menu_dn_fr_ledgers" name="Ledgers" parent="menu_dn_fr_root"
|
||||
sequence="20" active="False"/>
|
||||
<menuitem id="menu_dn_fr_gl" name="General Ledger" parent="menu_dn_fr_ledgers"
|
||||
action="action_dn_fr_gl" sequence="10" active="False"/>
|
||||
<menuitem id="menu_dn_fr_partner" name="Partner Ledger" parent="menu_dn_fr_ledgers"
|
||||
action="action_dn_fr_partner" sequence="20" active="False"/>
|
||||
<menuitem id="menu_dn_fr_journal" name="Journal Audit" parent="menu_dn_fr_ledgers"
|
||||
action="action_dn_fr_journal" sequence="30" active="False"/>
|
||||
|
||||
<menuitem id="menu_dn_fr_partner_reports" name="Receivables and Payables"
|
||||
parent="menu_dn_fr_root" sequence="30" active="False"/>
|
||||
<menuitem id="menu_dn_fr_ar" name="Aged Receivable" parent="menu_dn_fr_partner_reports"
|
||||
action="action_dn_fr_ar" sequence="10" active="False"/>
|
||||
<menuitem id="menu_dn_fr_ap" name="Aged Payable" parent="menu_dn_fr_partner_reports"
|
||||
action="action_dn_fr_ap" sequence="20" active="False"/>
|
||||
<menuitem id="menu_dn_fr_open_items" name="Open Items" parent="menu_dn_fr_partner_reports"
|
||||
action="action_dn_fr_open_items" sequence="30" active="False"/>
|
||||
<menuitem id="menu_dn_fr_statement" name="Customer Statement"
|
||||
parent="menu_dn_fr_partner_reports"
|
||||
action="action_dn_fr_statement" sequence="40" active="False"/>
|
||||
|
||||
<menuitem id="menu_dn_fr_tax_group" name="Taxes and Sales" parent="menu_dn_fr_root"
|
||||
sequence="40" active="False"/>
|
||||
<menuitem id="menu_dn_fr_tax" name="Tax Summary" parent="menu_dn_fr_tax_group"
|
||||
action="action_dn_fr_tax" sequence="10" active="False"/>
|
||||
<menuitem id="menu_dn_fr_sales" name="Sales Analysis" parent="menu_dn_fr_tax_group"
|
||||
action="action_dn_fr_sales" sequence="20" active="False"/>
|
||||
|
||||
<menuitem id="menu_dn_fr_adjust" name="Adjustments and Reconciliation"
|
||||
parent="menu_dn_fr_root" sequence="50" active="False"/>
|
||||
<menuitem id="menu_dn_fr_deferred" name="Deferred Revenues and Expenses"
|
||||
parent="menu_dn_fr_adjust"
|
||||
action="action_dn_fr_deferred" sequence="10" active="False"/>
|
||||
<menuitem id="menu_dn_fr_fx" name="Unrealized Currencies" parent="menu_dn_fr_adjust"
|
||||
action="action_dn_fr_fx" sequence="20" active="False"/>
|
||||
<menuitem id="menu_dn_fr_interco" name="Intercompany Comparison"
|
||||
parent="menu_dn_fr_adjust"
|
||||
action="action_dn_fr_interco" sequence="30" active="False"/>
|
||||
<menuitem id="menu_dn_fr_bankrec" name="Bank Reconciliation Status"
|
||||
parent="menu_dn_fr_adjust"
|
||||
action="action_dn_fr_bankrec" sequence="40" active="False"/>
|
||||
|
||||
<!-- Configuration, managers only: this one stays visible, it is the place
|
||||
where report definitions are edited. -->
|
||||
<menuitem id="menu_dn_fr_config" name="Report Definitions"
|
||||
parent="account.account_account_menu"
|
||||
action="action_dn_fr_config" sequence="95"/>
|
||||
<menuitem id="menu_dn_fr_external_value" name="Report Manual Values"
|
||||
parent="account.account_account_menu"
|
||||
action="action_dn_fr_external_value" sequence="96"/>
|
||||
</odoo>
|
||||
183
accountant_cn/views/views__dn_fr_views.xml
Normal file
183
accountant_cn/views/views__dn_fr_views.xml
Normal file
@@ -0,0 +1,183 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<odoo>
|
||||
<!-- ============================ report configuration -->
|
||||
<record id="view_dn_fr_list" model="ir.ui.view">
|
||||
<field name="name">dn.fr.list</field>
|
||||
<field name="model">dn.fr</field>
|
||||
<field name="arch" type="xml">
|
||||
<list>
|
||||
<field name="sequence" widget="handle"/>
|
||||
<field name="name"/>
|
||||
<field name="code"/>
|
||||
<field name="active"/>
|
||||
</list>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
<record id="view_dn_fr_form" model="ir.ui.view">
|
||||
<field name="name">dn.fr.form</field>
|
||||
<field name="model">dn.fr</field>
|
||||
<field name="arch" type="xml">
|
||||
<form>
|
||||
<header>
|
||||
<button name="action_open" type="object" string="Preview Report"
|
||||
class="oe_highlight"/>
|
||||
</header>
|
||||
<sheet>
|
||||
<div class="oe_title">
|
||||
<h1><field name="name" placeholder="Report Name"/></h1>
|
||||
</div>
|
||||
<group>
|
||||
<group string="Identification">
|
||||
<field name="code"/>
|
||||
<field name="sequence"/>
|
||||
<field name="active"/>
|
||||
</group>
|
||||
<group string="Default Period">
|
||||
<field name="default_date_from"/>
|
||||
<field name="default_date_to"/>
|
||||
</group>
|
||||
</group>
|
||||
<group string="Feature Toggles">
|
||||
<group>
|
||||
<field name="allow_comparison"/>
|
||||
<field name="allow_custom_periods"/>
|
||||
<field name="allow_hierarchy"/>
|
||||
<field name="allow_export"/>
|
||||
</group>
|
||||
<group>
|
||||
<field name="allow_unreconciled_only"/>
|
||||
<field name="allow_draft_entries"/>
|
||||
<field name="allow_journal_filter"/>
|
||||
<field name="allow_partner_filter"/>
|
||||
<field name="allow_multi_company"/>
|
||||
</group>
|
||||
</group>
|
||||
<group string="Display Options">
|
||||
<field name="hide_zero_lines"/>
|
||||
<field name="unfold_all_by_default"/>
|
||||
</group>
|
||||
<field name="description" placeholder="Report Description"/>
|
||||
<notebook>
|
||||
<page string="Report Lines" name="lines">
|
||||
<field name="line_ids" nolabel="1">
|
||||
<list editable="bottom">
|
||||
<field name="sequence" widget="handle"/>
|
||||
<field name="code"/>
|
||||
<field name="name"/>
|
||||
<field name="parent_id"/>
|
||||
<field name="is_total"/>
|
||||
<field name="figure_type"/>
|
||||
</list>
|
||||
</field>
|
||||
</page>
|
||||
</notebook>
|
||||
</sheet>
|
||||
</form>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
<record id="view_dn_fr_search" model="ir.ui.view">
|
||||
<field name="name">dn.fr.search</field>
|
||||
<field name="model">dn.fr</field>
|
||||
<field name="arch" type="xml">
|
||||
<search>
|
||||
<field name="name"/>
|
||||
<field name="code"/>
|
||||
<filter name="inactive" string="Archived" domain="[('active', '=', False)]"/>
|
||||
</search>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
<!-- ============================ line form -->
|
||||
<record id="view_dn_fr_line_form" model="ir.ui.view">
|
||||
<field name="name">dn.fr.line.form</field>
|
||||
<field name="model">dn.fr.line</field>
|
||||
<field name="arch" type="xml">
|
||||
<form>
|
||||
<sheet>
|
||||
<group>
|
||||
<group>
|
||||
<field name="report_id"/>
|
||||
<field name="parent_id"/>
|
||||
<field name="code"/>
|
||||
</group>
|
||||
<group>
|
||||
<field name="sequence"/>
|
||||
<field name="figure_type"/>
|
||||
<field name="is_total"/>
|
||||
<field name="hide_if_zero"/>
|
||||
</group>
|
||||
</group>
|
||||
<group>
|
||||
<field name="name"/>
|
||||
<field name="action_id"/>
|
||||
</group>
|
||||
<notebook>
|
||||
<page string="Expressions" name="expressions">
|
||||
<field name="expression_ids" nolabel="1">
|
||||
<list editable="bottom">
|
||||
<field name="sequence" widget="handle"/>
|
||||
<field name="label"/>
|
||||
<field name="engine"/>
|
||||
<field name="measure"/>
|
||||
<field name="sign"/>
|
||||
<field name="date_scope"/>
|
||||
<field name="formula"/>
|
||||
</list>
|
||||
</field>
|
||||
</page>
|
||||
</notebook>
|
||||
</sheet>
|
||||
</form>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
<!-- ============================ external values -->
|
||||
<record id="view_dn_fr_external_value_list" model="ir.ui.view">
|
||||
<field name="name">dn.fr.external.value.list</field>
|
||||
<field name="model">dn.fr.external.value</field>
|
||||
<field name="arch" type="xml">
|
||||
<list editable="bottom">
|
||||
<field name="date"/>
|
||||
<field name="name"/>
|
||||
<field name="expression_id"/>
|
||||
<field name="amount" sum="Total"/>
|
||||
<field name="company_id" groups="base.group_multi_company"/>
|
||||
<field name="currency_id" column_invisible="True"/>
|
||||
</list>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
<record id="view_dn_fr_external_value_form" model="ir.ui.view">
|
||||
<field name="name">dn.fr.external.value.form</field>
|
||||
<field name="model">dn.fr.external.value</field>
|
||||
<field name="arch" type="xml">
|
||||
<form>
|
||||
<sheet>
|
||||
<group>
|
||||
<field name="name"/>
|
||||
<field name="date"/>
|
||||
<field name="expression_id"/>
|
||||
<field name="amount"/>
|
||||
<field name="company_id" groups="base.group_multi_company"/>
|
||||
<field name="currency_id" invisible="1"/>
|
||||
</group>
|
||||
</sheet>
|
||||
</form>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
<record id="view_dn_fr_external_value_search" model="ir.ui.view">
|
||||
<field name="name">dn.fr.external.value.search</field>
|
||||
<field name="model">dn.fr.external.value</field>
|
||||
<field name="arch" type="xml">
|
||||
<search>
|
||||
<field name="name"/>
|
||||
<field name="expression_id"/>
|
||||
<filter name="this_year" string="This Year"
|
||||
domain="[('date', '>=', (context_today() + relativedelta(day=1, month=1)).strftime('%Y-%m-%d'))]"/>
|
||||
</search>
|
||||
</field>
|
||||
</record>
|
||||
</odoo>
|
||||
101
accountant_cn/views/views__dn_loan_line_views.xml
Normal file
101
accountant_cn/views/views__dn_loan_line_views.xml
Normal file
@@ -0,0 +1,101 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<odoo>
|
||||
|
||||
<!-- ==================================================================
|
||||
Amortization schedule analysis
|
||||
================================================================== -->
|
||||
|
||||
<record id="dn_loan_line_list_view" model="ir.ui.view">
|
||||
<field name="name">dn.loan.line.list</field>
|
||||
<field name="model">dn.loan.line</field>
|
||||
<field name="arch" type="xml">
|
||||
<list string="Installments" create="0"
|
||||
decoration-info="not is_payment_move_posted">
|
||||
<field name="currency_id" column_invisible="1"/>
|
||||
<field name="loan_id"/>
|
||||
<field name="sequence" optional="hide"/>
|
||||
<field name="date"/>
|
||||
<field name="principal" sum="Total Principal"/>
|
||||
<field name="interest" sum="Total Interest"/>
|
||||
<field name="payment" sum="Total Payment"/>
|
||||
<field name="outstanding_balance"/>
|
||||
<field name="long_term_theoretical_balance" optional="hide"/>
|
||||
<field name="short_term_theoretical_balance" optional="hide"/>
|
||||
</list>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
<record id="dn_loan_line_search_view" model="ir.ui.view">
|
||||
<field name="name">dn.loan.line.search</field>
|
||||
<field name="model">dn.loan.line</field>
|
||||
<field name="arch" type="xml">
|
||||
<search string="Search Installment">
|
||||
<field name="loan_name" string="Loan"
|
||||
filter_domain="[('loan_name', 'ilike', self)]"/>
|
||||
<filter string="Current" name="current"
|
||||
domain="[('loan_state', 'in', ('draft', 'running'))]"
|
||||
help="Installments of draft and running loans"/>
|
||||
<filter string="Closed" name="closed"
|
||||
domain="[('loan_state', '=', 'closed')]"/>
|
||||
<separator/>
|
||||
<filter string="Due Date" name="due_date" date="date"/>
|
||||
<group>
|
||||
<filter string="Loan" name="group_loan" domain="[]"
|
||||
context="{'group_by': 'loan_id'}"/>
|
||||
<filter string="Due Date" name="group_date" domain="[]"
|
||||
context="{'group_by': 'date'}"/>
|
||||
<filter string="Loan Status" name="group_state" domain="[]"
|
||||
context="{'group_by': 'loan_state'}"/>
|
||||
</group>
|
||||
</search>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
<record id="dn_loan_line_pivot_view" model="ir.ui.view">
|
||||
<field name="name">dn.loan.line.pivot</field>
|
||||
<field name="model">dn.loan.line</field>
|
||||
<field name="arch" type="xml">
|
||||
<pivot string="Loans Analysis" sample="1">
|
||||
<field name="date" interval="year" type="col"/>
|
||||
<field name="loan_id" type="row"/>
|
||||
<field name="principal" type="measure"/>
|
||||
<field name="interest" type="measure"/>
|
||||
<field name="payment" type="measure"/>
|
||||
</pivot>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
<record id="dn_loan_line_graph_view" model="ir.ui.view">
|
||||
<field name="name">dn.loan.line.graph</field>
|
||||
<field name="model">dn.loan.line</field>
|
||||
<field name="arch" type="xml">
|
||||
<graph type="bar" stacked="1" sample="1">
|
||||
<field name="date" interval="year"/>
|
||||
<field name="loan_id"/>
|
||||
<field name="principal" type="measure"/>
|
||||
<field name="interest" type="measure"/>
|
||||
</graph>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
<record id="action_dn_loan_line_analysis" model="ir.actions.act_window">
|
||||
<field name="name">Loans Analysis</field>
|
||||
<field name="res_model">dn.loan.line</field>
|
||||
<field name="search_view_id" ref="dn_loan_line_search_view"/>
|
||||
<field name="context">{'search_default_current': 1}</field>
|
||||
<field name="view_ids" eval="[(5, 0, 0),
|
||||
(0, 0, {'view_mode': 'pivot', 'view_id': ref('dn_loan_line_pivot_view')}),
|
||||
(0, 0, {'view_mode': 'graph', 'view_id': ref('dn_loan_line_graph_view')}),
|
||||
(0, 0, {'view_mode': 'list', 'view_id': ref('dn_loan_line_list_view')}),
|
||||
]"/>
|
||||
</record>
|
||||
|
||||
<!-- Under "Reporting > Management", beside the invoice and cashflow
|
||||
analyses: it answers the same question for the liability side. -->
|
||||
<menuitem id="menu_dn_loan_line_analysis"
|
||||
action="action_dn_loan_line_analysis"
|
||||
parent="account.account_reports_management_menu"
|
||||
sequence="30"
|
||||
groups="account.group_account_readonly"/>
|
||||
|
||||
</odoo>
|
||||
40
accountant_cn/views/views__dn_loan_move_views.xml
Normal file
40
accountant_cn/views/views__dn_loan_move_views.xml
Normal file
@@ -0,0 +1,40 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<odoo>
|
||||
|
||||
<!-- A dedicated list of the loan entries, ordered by date rather than by
|
||||
entry number: the loan is read chronologically, and the numbering of
|
||||
a journal says nothing about when an installment falls due. -->
|
||||
|
||||
<record id="dn_loan_move_list_view" model="ir.ui.view">
|
||||
<field name="name">dn.loan.move.list</field>
|
||||
<field name="model">account.move</field>
|
||||
<field name="inherit_id" ref="account.view_move_tree"/>
|
||||
<field name="mode">primary</field>
|
||||
<field name="arch" type="xml">
|
||||
<xpath expr="//list" position="attributes">
|
||||
<attribute name="default_order">date, name</attribute>
|
||||
</xpath>
|
||||
<xpath expr="//list" position="inside">
|
||||
<field name="is_loan_payment_move" optional="show"/>
|
||||
</xpath>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
<record id="dn_loan_move_form_view" model="ir.ui.view">
|
||||
<field name="name">dn.loan.move.form</field>
|
||||
<field name="model">account.move</field>
|
||||
<field name="inherit_id" ref="account.view_move_form"/>
|
||||
<field name="arch" type="xml">
|
||||
<xpath expr="//header" position="inside">
|
||||
<button name="action_open_dn_loan" string="Loan" type="object"
|
||||
class="btn-secondary"
|
||||
invisible="not dn_loan_id"
|
||||
groups="account.group_account_readonly"/>
|
||||
</xpath>
|
||||
<xpath expr="//sheet" position="inside">
|
||||
<field name="dn_loan_id" invisible="not dn_loan_id" readonly="1"/>
|
||||
</xpath>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
</odoo>
|
||||
315
accountant_cn/views/views__dn_loan_views.xml
Normal file
315
accountant_cn/views/views__dn_loan_views.xml
Normal file
@@ -0,0 +1,315 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<odoo>
|
||||
|
||||
<!-- ==================================================================
|
||||
Loans
|
||||
================================================================== -->
|
||||
|
||||
<record id="dn_loan_form_view" model="ir.ui.view">
|
||||
<field name="name">dn.loan.form</field>
|
||||
<field name="model">dn.loan</field>
|
||||
<field name="arch" type="xml">
|
||||
<form string="Loan">
|
||||
<header>
|
||||
<button name="action_confirm" string="Confirm" type="object"
|
||||
class="btn-primary" groups="account.group_account_invoice"
|
||||
invisible="state != 'draft'" data-hotkey="q"/>
|
||||
<button name="action_open_compute_wizard" string="Compute Schedule"
|
||||
type="object" class="btn-secondary"
|
||||
groups="account.group_account_manager"
|
||||
invisible="state != 'draft'"/>
|
||||
<button name="action_upload_amortization_schedule" string="Import"
|
||||
type="object" class="btn-secondary"
|
||||
groups="account.group_account_manager"
|
||||
invisible="state != 'draft'"/>
|
||||
<button name="action_reset_schedule" string="Clear Schedule"
|
||||
type="object" class="btn-secondary"
|
||||
groups="account.group_account_manager"
|
||||
invisible="state != 'draft' or not line_ids"
|
||||
confirm="This deletes the whole amortization schedule. Continue?"/>
|
||||
<button name="action_close" string="Close" type="object"
|
||||
class="btn-secondary" groups="account.group_account_manager"
|
||||
invisible="state != 'running'"/>
|
||||
<button name="action_cancel" string="Cancel" type="object"
|
||||
class="btn-secondary" groups="account.group_account_manager"
|
||||
invisible="state != 'running'"
|
||||
confirm="The generated entries will be reversed. Continue?"/>
|
||||
<button name="action_set_to_draft" string="Set to Draft" type="object"
|
||||
class="btn-secondary" groups="account.group_account_manager"
|
||||
invisible="state in ('draft', 'running')"/>
|
||||
<button name="action_reopen" string="Reopen" type="object"
|
||||
class="btn-secondary" groups="account.group_account_manager"
|
||||
invisible="state != 'closed'"/>
|
||||
<field name="state" widget="statusbar"
|
||||
statusbar_visible="draft,running,closed"/>
|
||||
</header>
|
||||
<sheet>
|
||||
<div class="oe_button_box" name="button_box">
|
||||
<button class="oe_stat_button" icon="fa-list-alt" type="object"
|
||||
name="action_open_loan_entries"
|
||||
invisible="state == 'draft'">
|
||||
<field string="Posted Entries" name="nb_posted_entries"
|
||||
widget="statinfo"/>
|
||||
</button>
|
||||
</div>
|
||||
<!-- Needed so the company and its currency are available
|
||||
when the record is still being created. -->
|
||||
<field name="company_id" invisible="1"/>
|
||||
<field name="currency_id" invisible="1"/>
|
||||
<field name="is_wrong_date" invisible="1"/>
|
||||
<field name="amount_borrowed_difference" invisible="1"/>
|
||||
<field name="interest_difference" invisible="1"/>
|
||||
<field name="duration_difference" invisible="1"/>
|
||||
<div class="oe_title">
|
||||
<label for="name"/>
|
||||
<h1>
|
||||
<field name="name" placeholder="Loan name"/>
|
||||
</h1>
|
||||
</div>
|
||||
<group>
|
||||
<group>
|
||||
<field name="amount_borrowed" widget="monetary"
|
||||
readonly="state != 'draft'"
|
||||
decoration-danger="amount_borrowed_difference != 0"/>
|
||||
<field name="interest" widget="monetary"
|
||||
readonly="state != 'draft'"
|
||||
decoration-danger="interest_difference != 0"/>
|
||||
<field name="outstanding_balance" widget="monetary"/>
|
||||
</group>
|
||||
<group>
|
||||
<field name="date" readonly="state != 'draft'"
|
||||
decoration-danger="is_wrong_date"/>
|
||||
<label for="duration"/>
|
||||
<div class="o_row">
|
||||
<field name="duration" readonly="state != 'draft'"
|
||||
decoration-danger="duration_difference != 0"
|
||||
class="oe_inline"/>
|
||||
<div class="text-muted ms-1 oe_inline"
|
||||
invisible="duration != 1">month</div>
|
||||
<div class="text-muted ms-1 oe_inline"
|
||||
invisible="duration == 1">months</div>
|
||||
</div>
|
||||
<field name="method" readonly="state != 'draft'"/>
|
||||
</group>
|
||||
</group>
|
||||
<field name="loan_properties" columns="2"/>
|
||||
<notebook>
|
||||
<page string="Amortization Schedule" name="schedule">
|
||||
<field name="line_ids" readonly="state != 'draft'"
|
||||
context="{'default_loan_id': id}">
|
||||
<list editable="bottom" limit="120"
|
||||
decoration-info="not is_payment_move_posted"
|
||||
decoration-muted="is_payment_move_posted">
|
||||
<field name="currency_id" column_invisible="1"/>
|
||||
<field name="sequence" width="40px"/>
|
||||
<field name="date"/>
|
||||
<field name="principal" sum="Total Principal"/>
|
||||
<field name="interest" sum="Total Interest"/>
|
||||
<field name="payment" sum="Total Payment"/>
|
||||
<field name="outstanding_balance"/>
|
||||
<field name="long_term_theoretical_balance"
|
||||
optional="show"/>
|
||||
<field name="short_term_theoretical_balance"
|
||||
optional="show"/>
|
||||
<field name="is_payment_move_posted"
|
||||
widget="boolean_toggle" optional="hide"/>
|
||||
</list>
|
||||
</field>
|
||||
</page>
|
||||
<page string="Settings" name="settings">
|
||||
<group>
|
||||
<group string="Accounts">
|
||||
<field name="long_term_account_id"
|
||||
readonly="state != 'draft'"
|
||||
options="{'no_create': True}"/>
|
||||
<field name="short_term_account_id"
|
||||
readonly="state != 'draft'"
|
||||
options="{'no_create': True}"/>
|
||||
<field name="expense_account_id"
|
||||
readonly="state != 'draft'"
|
||||
options="{'no_create': True}"/>
|
||||
</group>
|
||||
<group string="Booking">
|
||||
<field name="journal_id" readonly="state != 'draft'"
|
||||
options="{'no_create': True}"/>
|
||||
<field name="skip_until_date"
|
||||
readonly="state != 'draft'"
|
||||
placeholder="No installment skipped"/>
|
||||
<field name="analytic_distribution"
|
||||
widget="analytic_distribution"
|
||||
readonly="state != 'draft'"/>
|
||||
<field name="company_id" groups="base.group_multi_company"
|
||||
readonly="1" force_save="1"/>
|
||||
</group>
|
||||
</group>
|
||||
</page>
|
||||
</notebook>
|
||||
</sheet>
|
||||
<chatter/>
|
||||
</form>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
<record id="dn_loan_list_view" model="ir.ui.view">
|
||||
<field name="name">dn.loan.list</field>
|
||||
<field name="model">dn.loan</field>
|
||||
<field name="arch" type="xml">
|
||||
<list string="Loans"
|
||||
decoration-info="state == 'draft'"
|
||||
decoration-muted="state in ('closed', 'cancelled')">
|
||||
<field name="currency_id" column_invisible="1"/>
|
||||
<field name="name"/>
|
||||
<field name="date" string="Start Date"/>
|
||||
<field name="end_date"/>
|
||||
<field name="amount_borrowed" sum="Total Amounts Borrowed"/>
|
||||
<field name="outstanding_balance" sum="Total Outstanding Balance"/>
|
||||
<field name="state" widget="badge"
|
||||
decoration-info="state == 'draft'"
|
||||
decoration-success="state == 'running'"
|
||||
decoration-danger="state in ('closed', 'cancelled')"/>
|
||||
<field name="method" optional="hide"/>
|
||||
<field name="long_term_account_id" optional="hide"/>
|
||||
<field name="short_term_account_id" optional="hide"/>
|
||||
<field name="expense_account_id" optional="hide"/>
|
||||
<field name="company_id" groups="base.group_multi_company"
|
||||
optional="hide"/>
|
||||
</list>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
<record id="dn_loan_kanban_view" model="ir.ui.view">
|
||||
<field name="name">dn.loan.kanban</field>
|
||||
<field name="model">dn.loan</field>
|
||||
<field name="arch" type="xml">
|
||||
<kanban class="o_kanban_mobile" sample="1">
|
||||
<field name="currency_id"/>
|
||||
<templates>
|
||||
<t t-name="card">
|
||||
<div class="row mb-2">
|
||||
<field name="name" class="fw-bold fs-5 col-9"/>
|
||||
<div class="col-3 text-end">
|
||||
<field name="state" widget="label_selection"
|
||||
options="{'classes': {'draft': 'primary',
|
||||
'running': 'success',
|
||||
'closed': 'secondary',
|
||||
'cancelled': 'danger'}}"/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="col-6">
|
||||
<field name="amount_borrowed" widget="monetary"/>
|
||||
</div>
|
||||
<div class="col-6 text-end text-muted">
|
||||
<field name="date"/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row mt-1">
|
||||
<div class="col-12 text-muted">
|
||||
<div class="oe_inline">Outstanding: </div>
|
||||
<field name="outstanding_balance" widget="monetary"/>
|
||||
</div>
|
||||
</div>
|
||||
</t>
|
||||
</templates>
|
||||
</kanban>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
<record id="dn_loan_search_view" model="ir.ui.view">
|
||||
<field name="name">dn.loan.search</field>
|
||||
<field name="model">dn.loan</field>
|
||||
<field name="arch" type="xml">
|
||||
<search string="Search Loan">
|
||||
<field name="name" string="Loan"
|
||||
filter_domain="['|', ('name', 'ilike', self),
|
||||
('display_name', 'ilike', self)]"/>
|
||||
<field name="loan_properties"/>
|
||||
<filter string="Current" name="current"
|
||||
domain="[('state', 'in', ('draft', 'running'))]"
|
||||
help="Draft and running loans"/>
|
||||
<filter string="Running" name="running"
|
||||
domain="[('state', '=', 'running')]"/>
|
||||
<filter string="Closed" name="closed"
|
||||
domain="[('state', '=', 'closed')]"/>
|
||||
<separator/>
|
||||
<filter string="Loan Date" name="loan_date" date="date"/>
|
||||
<group>
|
||||
<filter string="Status" name="group_state" domain="[]"
|
||||
context="{'group_by': 'state'}"/>
|
||||
<filter string="Method" name="group_method" domain="[]"
|
||||
context="{'group_by': 'method'}"/>
|
||||
<filter string="Loan Date" name="group_date" domain="[]"
|
||||
context="{'group_by': 'date'}"/>
|
||||
</group>
|
||||
</search>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
<record id="dn_loan_pivot_view" model="ir.ui.view">
|
||||
<field name="name">dn.loan.pivot</field>
|
||||
<field name="model">dn.loan</field>
|
||||
<field name="arch" type="xml">
|
||||
<pivot sample="1">
|
||||
<field name="date" interval="year" type="col"/>
|
||||
<field name="name" type="row"/>
|
||||
<field name="amount_borrowed" type="measure"/>
|
||||
</pivot>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
<record id="dn_loan_graph_view" model="ir.ui.view">
|
||||
<field name="name">dn.loan.graph</field>
|
||||
<field name="model">dn.loan</field>
|
||||
<field name="arch" type="xml">
|
||||
<graph type="line" sample="1">
|
||||
<field name="date" interval="year"/>
|
||||
<field name="name"/>
|
||||
<field name="amount_borrowed" type="measure"/>
|
||||
<field name="interest" type="measure"/>
|
||||
</graph>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
<!-- ==================================================================
|
||||
Actions
|
||||
================================================================== -->
|
||||
|
||||
<record id="action_dn_loan" model="ir.actions.act_window">
|
||||
<field name="name">Loans</field>
|
||||
<field name="res_model">dn.loan</field>
|
||||
<field name="search_view_id" ref="dn_loan_search_view"/>
|
||||
<field name="context">{'search_default_current': 1}</field>
|
||||
<field name="view_ids" eval="[(5, 0, 0),
|
||||
(0, 0, {'view_mode': 'list', 'view_id': ref('dn_loan_list_view')}),
|
||||
(0, 0, {'view_mode': 'form', 'view_id': ref('dn_loan_form_view')}),
|
||||
(0, 0, {'view_mode': 'kanban', 'view_id': ref('dn_loan_kanban_view')}),
|
||||
(0, 0, {'view_mode': 'pivot', 'view_id': ref('dn_loan_pivot_view')}),
|
||||
(0, 0, {'view_mode': 'graph', 'view_id': ref('dn_loan_graph_view')}),
|
||||
]"/>
|
||||
<field name="help" type="html">
|
||||
<p class="o_view_nocontent_smiling_face">
|
||||
Record your first loan
|
||||
</p>
|
||||
<p>
|
||||
Enter the amount, the rate and the term, then let the schedule be
|
||||
computed: the interest and principal entries are posted
|
||||
automatically, and the part of the principal falling due within a
|
||||
year is reclassified to the short term account every month.
|
||||
</p>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
<!-- ==================================================================
|
||||
Menus
|
||||
================================================================== -->
|
||||
|
||||
<!-- Under "Assets & Liabilities", next to the assets: a loan is the mirror
|
||||
image of an asset, so it belongs in the same group. Sequence 62 is what
|
||||
Enterprise uses, leaving 60 for the asset register. -->
|
||||
<menuitem id="menu_dn_loan"
|
||||
action="action_dn_loan"
|
||||
parent="accountant_cn.account_assets_liabilities_menu"
|
||||
sequence="62"
|
||||
groups="account.group_account_readonly"/>
|
||||
|
||||
</odoo>
|
||||
34
accountant_cn/views/views__dn_report_actions.xml
Normal file
34
accountant_cn/views/views__dn_report_actions.xml
Normal file
@@ -0,0 +1,34 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<odoo>
|
||||
|
||||
<!--
|
||||
Client actions are declared in their own file, loaded before the views,
|
||||
because a form button may reference them by external id.
|
||||
-->
|
||||
|
||||
<!-- Generic viewer: the report is resolved from report_code / report_id -->
|
||||
<record id="action_dn_report_view" model="ir.actions.client">
|
||||
<field name="name">Report Preview</field>
|
||||
<field name="tag">dn_report_view</field>
|
||||
<field name="params" eval="{'report_id': False}"/>
|
||||
</record>
|
||||
|
||||
<record id="action_dn_report_tb" model="ir.actions.client">
|
||||
<field name="name">Trial Balance (DN)</field>
|
||||
<field name="tag">dn_report_view</field>
|
||||
<field name="params" eval="{'report_code': 'DN_TB'}"/>
|
||||
</record>
|
||||
|
||||
<record id="action_dn_report_pl" model="ir.actions.client">
|
||||
<field name="name">Profit and Loss (DN)</field>
|
||||
<field name="tag">dn_report_view</field>
|
||||
<field name="params" eval="{'report_code': 'DN_PL'}"/>
|
||||
</record>
|
||||
|
||||
<record id="action_dn_report_bs" model="ir.actions.client">
|
||||
<field name="name">Balance Sheet (DN)</field>
|
||||
<field name="tag">dn_report_view</field>
|
||||
<field name="params" eval="{'report_code': 'DN_BS'}"/>
|
||||
</record>
|
||||
|
||||
</odoo>
|
||||
49
accountant_cn/views/views__dn_report_menuitems.xml
Normal file
49
accountant_cn/views/views__dn_report_menuitems.xml
Normal file
@@ -0,0 +1,49 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<odoo>
|
||||
|
||||
<!--
|
||||
The three statements of this module overlap with the ones mounted by
|
||||
`dn_account_full_menu` under REPORTING > Statement Reports / Ledgers.
|
||||
Keeping both would show the same report twice, so the menu tree here is
|
||||
inactive by default; only the configuration entry stays reachable.
|
||||
|
||||
Set `active` to True (or use the list view with the "Archived" filter)
|
||||
if you prefer this lightweight engine as the only report source.
|
||||
-->
|
||||
<menuitem id="menu_dn_reporting_root"
|
||||
name="DN Financial Reports (Core)"
|
||||
parent="account.menu_finance_reports"
|
||||
sequence="96"
|
||||
active="False"
|
||||
groups="account.group_account_readonly"/>
|
||||
|
||||
<menuitem id="menu_dn_report_tb"
|
||||
name="Trial Balance"
|
||||
parent="menu_dn_reporting_root"
|
||||
action="action_dn_report_tb"
|
||||
sequence="10"
|
||||
active="False"/>
|
||||
|
||||
<menuitem id="menu_dn_report_pl"
|
||||
name="Profit and Loss"
|
||||
parent="menu_dn_reporting_root"
|
||||
action="action_dn_report_pl"
|
||||
sequence="20"
|
||||
active="False"/>
|
||||
|
||||
<menuitem id="menu_dn_report_bs"
|
||||
name="Balance Sheet"
|
||||
parent="menu_dn_reporting_root"
|
||||
action="action_dn_report_bs"
|
||||
sequence="30"
|
||||
active="False"/>
|
||||
|
||||
<!-- Configuration: Accounting > Configuration > DN Report Builder -->
|
||||
<menuitem id="menu_dn_report_config"
|
||||
name="DN Report Builder"
|
||||
parent="account.menu_account_config"
|
||||
action="action_dn_report_config"
|
||||
sequence="90"
|
||||
groups="account.group_account_manager"/>
|
||||
|
||||
</odoo>
|
||||
138
accountant_cn/views/views__dn_report_views.xml
Normal file
138
accountant_cn/views/views__dn_report_views.xml
Normal file
@@ -0,0 +1,138 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<odoo>
|
||||
|
||||
<!-- ================= Expression ================= -->
|
||||
<record id="view_dn_expression_list" model="ir.ui.view">
|
||||
<field name="name">dn.report.expression.list</field>
|
||||
<field name="model">dn.report.expression</field>
|
||||
<field name="arch" type="xml">
|
||||
<list editable="bottom">
|
||||
<field name="sequence" widget="handle"/>
|
||||
<field name="label"/>
|
||||
<field name="engine"/>
|
||||
<field name="formula"/>
|
||||
<field name="figure_type"/>
|
||||
</list>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
<!-- ================= Line ================= -->
|
||||
<record id="view_dn_line_form" model="ir.ui.view">
|
||||
<field name="name">dn.report.line.form</field>
|
||||
<field name="model">dn.report.line</field>
|
||||
<field name="arch" type="xml">
|
||||
<form>
|
||||
<sheet>
|
||||
<group>
|
||||
<group>
|
||||
<field name="name"/>
|
||||
<field name="code"/>
|
||||
<field name="parent_id"/>
|
||||
</group>
|
||||
<group>
|
||||
<field name="sequence"/>
|
||||
<field name="is_total"/>
|
||||
</group>
|
||||
</group>
|
||||
<notebook>
|
||||
<page string="Expressions" name="expressions">
|
||||
<field name="expression_ids" nolabel="1">
|
||||
<list editable="bottom">
|
||||
<field name="sequence" widget="handle"/>
|
||||
<field name="label"/>
|
||||
<field name="engine"/>
|
||||
<field name="formula"/>
|
||||
<field name="figure_type"/>
|
||||
</list>
|
||||
</field>
|
||||
<div class="text-muted small mt-2">
|
||||
Engine reference: domain = journal item domain;
|
||||
account_codes = comma separated account code prefixes (e.g. 60,62);
|
||||
aggregation = arithmetic over other expression labels (e.g. CA + RE);
|
||||
text = static label.
|
||||
</div>
|
||||
</page>
|
||||
</notebook>
|
||||
</sheet>
|
||||
</form>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
<record id="view_dn_line_list" model="ir.ui.view">
|
||||
<field name="name">dn.report.line.list</field>
|
||||
<field name="model">dn.report.line</field>
|
||||
<field name="arch" type="xml">
|
||||
<list>
|
||||
<field name="sequence" widget="handle"/>
|
||||
<field name="name"/>
|
||||
<field name="code"/>
|
||||
<field name="parent_id"/>
|
||||
<field name="is_total"/>
|
||||
</list>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
<!-- ================= Report ================= -->
|
||||
<record id="view_dn_report_form" model="ir.ui.view">
|
||||
<field name="name">dn.report.form</field>
|
||||
<field name="model">dn.report</field>
|
||||
<field name="arch" type="xml">
|
||||
<form>
|
||||
<header>
|
||||
<button name="%(action_dn_report_view)d" type="action"
|
||||
string="Preview Report" class="oe_highlight"
|
||||
context="{'active_id': id, 'report_id': id}"/>
|
||||
</header>
|
||||
<sheet>
|
||||
<div class="oe_title">
|
||||
<h1><field name="name" placeholder="Report Name"/></h1>
|
||||
</div>
|
||||
<group>
|
||||
<group>
|
||||
<field name="code"/>
|
||||
<field name="sequence"/>
|
||||
<field name="active"/>
|
||||
</group>
|
||||
<group>
|
||||
<field name="group_by_account"/>
|
||||
</group>
|
||||
</group>
|
||||
<field name="description" placeholder="Description"/>
|
||||
<notebook>
|
||||
<page string="Report Lines" name="lines">
|
||||
<field name="line_ids" nolabel="1">
|
||||
<list editable="bottom">
|
||||
<field name="sequence" widget="handle"/>
|
||||
<field name="name"/>
|
||||
<field name="code"/>
|
||||
<field name="parent_id"/>
|
||||
<field name="is_total"/>
|
||||
</list>
|
||||
</field>
|
||||
</page>
|
||||
</notebook>
|
||||
</sheet>
|
||||
</form>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
<record id="view_dn_report_list" model="ir.ui.view">
|
||||
<field name="name">dn.report.list</field>
|
||||
<field name="model">dn.report</field>
|
||||
<field name="arch" type="xml">
|
||||
<list>
|
||||
<field name="sequence" widget="handle"/>
|
||||
<field name="name"/>
|
||||
<field name="code"/>
|
||||
<field name="active"/>
|
||||
</list>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
<record id="action_dn_report_config" model="ir.actions.act_window">
|
||||
<field name="name">DN Report Configuration</field>
|
||||
<field name="res_model">dn.report</field>
|
||||
<field name="view_mode">list,form</field>
|
||||
</record>
|
||||
|
||||
</odoo>
|
||||
460
accountant_cn/views/views__menu.xml
Normal file
460
accountant_cn/views/views__menu.xml
Normal file
@@ -0,0 +1,460 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<odoo>
|
||||
|
||||
<menuitem id="menu_accounting"
|
||||
name="Accounting"
|
||||
groups="account.group_account_readonly,account.group_account_invoice"
|
||||
web_icon="dn_account_full_menu,static/description/icon.png"
|
||||
sequence="55"/>
|
||||
|
||||
<!-- ================== move the community branches ================== -->
|
||||
<record id="account.menu_board_journal_1" model="ir.ui.menu">
|
||||
<field name="parent_id" ref="menu_accounting"/>
|
||||
<field name="sequence">1</field>
|
||||
</record>
|
||||
|
||||
<record id="account.menu_finance_receivables" model="ir.ui.menu">
|
||||
<field name="parent_id" ref="menu_accounting"/>
|
||||
<field name="sequence">2</field>
|
||||
</record>
|
||||
|
||||
<record id="account.menu_finance_payables" model="ir.ui.menu">
|
||||
<field name="parent_id" ref="menu_accounting"/>
|
||||
<field name="sequence">3</field>
|
||||
</record>
|
||||
|
||||
<record id="account.menu_finance_entries" model="ir.ui.menu">
|
||||
<field name="parent_id" ref="menu_accounting"/>
|
||||
<field name="sequence">4</field>
|
||||
</record>
|
||||
|
||||
<record id="account.account_audit_menu" model="ir.ui.menu">
|
||||
<field name="parent_id" ref="menu_accounting"/>
|
||||
<field name="sequence">5</field>
|
||||
</record>
|
||||
|
||||
<record id="account.menu_finance_reports" model="ir.ui.menu">
|
||||
<field name="parent_id" ref="menu_accounting"/>
|
||||
<field name="sequence">6</field>
|
||||
</record>
|
||||
|
||||
<record id="account.menu_finance_configuration" model="ir.ui.menu">
|
||||
<field name="parent_id" ref="menu_accounting"/>
|
||||
<field name="sequence">7</field>
|
||||
</record>
|
||||
|
||||
<!-- The community "Invoicing" root is now empty: every branch it used to
|
||||
hold was re-parented above. Enterprise leaves it behind as a blank
|
||||
app tile; on a Community database that reads as a bug ("a second
|
||||
accounting app with nothing in it"), so we archive it. The menu record
|
||||
still exists, it is simply not rendered.
|
||||
|
||||
Re-activate it from Settings > Technical > User Interface > Menu Items
|
||||
if you ever want the flat Invoicing app back. -->
|
||||
<record id="account.menu_finance" model="ir.ui.menu">
|
||||
<field name="active" eval="False"/>
|
||||
</record>
|
||||
|
||||
|
||||
<!-- ============================================================= -->
|
||||
<!-- ACCOUNTING > ASSETS & LIABILITIES -->
|
||||
<!-- Enterprise: accountant/views/accountant_menuitem.xml -->
|
||||
<!-- ============================================================= -->
|
||||
<menuitem id="account_assets_liabilities_menu"
|
||||
name="Assets & Liabilities"
|
||||
parent="account.menu_finance_entries"
|
||||
sequence="10"/>
|
||||
|
||||
<!-- Enterprise fills this group from `account_asset` (a full asset register
|
||||
with a depreciation board per record), which does not exist in
|
||||
Community. Rather than pointing "Assets" at a miscellaneous journal
|
||||
(which shows every entry, not the assets), we expose the journal items
|
||||
that actually sit on a Fixed Assets account. It is the same population
|
||||
Enterprise's register posts to, and it keeps the menu where users
|
||||
expect it. Sequence 60 matches `account_asset/data/menuitems.xml`. -->
|
||||
<record id="action_dn_fixed_assets" model="ir.actions.act_window">
|
||||
<field name="name">Assets</field>
|
||||
<field name="res_model">account.move.line</field>
|
||||
<field name="path">assets</field>
|
||||
<field name="view_mode">list,pivot,graph</field>
|
||||
<field name="domain">[
|
||||
('display_type', 'not in', ('line_section', 'line_subsection', 'line_note')),
|
||||
('account_id.account_type', 'in', ('asset_fixed', 'asset_non_current')),
|
||||
]</field>
|
||||
<field name="context">{'search_default_group_by_account': 1, 'search_default_posted': 1}</field>
|
||||
<field name="help" type="html">
|
||||
<p class="o_view_nocontent_smiling_face">No asset entries yet</p>
|
||||
<p>Every journal item booked on a Fixed Assets account shows up here,
|
||||
together with the depreciation charged against it.</p>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
<menuitem id="menu_assets_fixed"
|
||||
name="Assets"
|
||||
parent="account_assets_liabilities_menu"
|
||||
action="action_dn_fixed_assets"
|
||||
sequence="60"/>
|
||||
|
||||
|
||||
<!-- ============================================================= -->
|
||||
<!-- REPORTING > STATEMENT REPORTS -->
|
||||
<!-- Enterprise: accountant_menuitem.xml + account_asset/data/menuitems.xml -->
|
||||
<!-- ============================================================= -->
|
||||
<menuitem id="menu_report_balance_sheet"
|
||||
name="Balance Sheet"
|
||||
parent="account.account_reports_legal_statements_menu"
|
||||
action="accountant_cn.action_dn_fr_bs"
|
||||
groups="account.group_account_readonly,account.group_account_basic"
|
||||
sequence="10"/>
|
||||
|
||||
<menuitem id="menu_report_profit_loss"
|
||||
name="Profit and Loss"
|
||||
parent="account.account_reports_legal_statements_menu"
|
||||
action="accountant_cn.action_dn_fr_pl"
|
||||
groups="account.group_account_readonly,account.group_account_basic"
|
||||
sequence="15"/>
|
||||
|
||||
<menuitem id="menu_report_depreciation"
|
||||
name="Depreciation Schedule"
|
||||
parent="account.account_reports_legal_statements_menu"
|
||||
action="accountant_cn.action_dn_fr_depreciation"
|
||||
groups="account.group_account_readonly"
|
||||
sequence="20"/>
|
||||
|
||||
<menuitem id="menu_report_cash_flow"
|
||||
name="Cash Flow Statement"
|
||||
parent="account.account_reports_legal_statements_menu"
|
||||
action="accountant_cn.action_dn_fr_cf"
|
||||
groups="account.group_account_readonly,account.group_account_basic"
|
||||
sequence="30"/>
|
||||
|
||||
<menuitem id="menu_report_annual"
|
||||
name="Annual Statements"
|
||||
parent="account.account_reports_legal_statements_menu"
|
||||
action="accountant_cn.action_dn_fr_annual"
|
||||
groups="account.group_account_readonly,account.group_account_basic"
|
||||
sequence="40"/>
|
||||
|
||||
|
||||
<!-- ============================================================= -->
|
||||
<!-- REPORTING > LEDGERS -->
|
||||
<!-- Enterprise: accountant_menuitem.xml, `account_reports_audit_menu` -->
|
||||
<!-- Only two entries: Journal Audit lives under Review > Control. -->
|
||||
<!-- ============================================================= -->
|
||||
<menuitem id="account_reports_audit_menu"
|
||||
name="Ledgers"
|
||||
parent="account.menu_finance_reports"
|
||||
sequence="2">
|
||||
|
||||
<menuitem id="menu_report_trial_balance"
|
||||
name="Trial Balance"
|
||||
action="accountant_cn.action_dn_fr_tb"
|
||||
groups="account.group_account_readonly,account.group_account_basic"
|
||||
sequence="10"/>
|
||||
|
||||
<menuitem id="menu_report_general_ledger"
|
||||
name="General Ledger"
|
||||
action="accountant_cn.action_dn_fr_gl"
|
||||
groups="account.group_account_readonly,account.group_account_basic"
|
||||
sequence="20"/>
|
||||
|
||||
</menuitem>
|
||||
|
||||
|
||||
<!-- ============================================================= -->
|
||||
<!-- REPORTING > PARTNER REPORTS (was an empty group) -->
|
||||
<!-- ============================================================= -->
|
||||
<menuitem id="menu_report_partner_ledger"
|
||||
name="Partner Ledger"
|
||||
parent="account.account_reports_partners_reports_menu"
|
||||
action="accountant_cn.action_dn_fr_partner"
|
||||
groups="account.group_account_readonly,account.group_account_basic"
|
||||
sequence="10"/>
|
||||
|
||||
<menuitem id="menu_report_customer_statement"
|
||||
name="Customer Statement"
|
||||
parent="account.account_reports_partners_reports_menu"
|
||||
action="accountant_cn.action_dn_fr_statement"
|
||||
groups="account.group_account_readonly,account.group_account_basic"
|
||||
sequence="20"/>
|
||||
|
||||
<menuitem id="menu_report_aged_receivable"
|
||||
name="Aged Receivable"
|
||||
parent="account.account_reports_partners_reports_menu"
|
||||
action="accountant_cn.action_dn_fr_ar"
|
||||
groups="account.group_account_readonly,account.group_account_basic"
|
||||
sequence="30"/>
|
||||
|
||||
<menuitem id="menu_report_aged_payable"
|
||||
name="Aged Payable"
|
||||
parent="account.account_reports_partners_reports_menu"
|
||||
action="accountant_cn.action_dn_fr_ap"
|
||||
groups="account.group_account_readonly,account.group_account_basic"
|
||||
sequence="40"/>
|
||||
|
||||
<menuitem id="menu_report_open_items"
|
||||
name="Open Items"
|
||||
parent="account.account_reports_partners_reports_menu"
|
||||
action="accountant_cn.action_dn_fr_open_items"
|
||||
groups="account.group_account_readonly,account.group_account_basic"
|
||||
sequence="50"/>
|
||||
|
||||
|
||||
<!-- ============================================================= -->
|
||||
<!-- REPORTING > TAXES & FISCAL (was an empty group) -->
|
||||
<!-- ============================================================= -->
|
||||
<menuitem id="menu_report_tax"
|
||||
name="Tax Report"
|
||||
parent="account.account_reports_taxes_and_fiscal_menu"
|
||||
action="accountant_cn.action_dn_fr_tax"
|
||||
groups="account.group_account_readonly,account.group_account_basic"
|
||||
sequence="10"/>
|
||||
|
||||
<menuitem id="menu_report_sales"
|
||||
name="Sales Analysis"
|
||||
parent="account.account_reports_taxes_and_fiscal_menu"
|
||||
action="accountant_cn.action_dn_fr_sales"
|
||||
groups="account.group_account_readonly,account.group_account_basic"
|
||||
sequence="20"/>
|
||||
|
||||
|
||||
<!-- ============================================================= -->
|
||||
<!-- REPORTING > MANAGEMENT (adds to the community entries) -->
|
||||
<!-- ============================================================= -->
|
||||
<menuitem id="menu_report_exec_summary"
|
||||
name="Executive Summary"
|
||||
parent="account.account_reports_management_menu"
|
||||
action="accountant_cn.action_dn_fr_exec"
|
||||
groups="account.group_account_readonly,account.group_account_basic"
|
||||
sequence="1"/>
|
||||
|
||||
<menuitem id="menu_report_interco"
|
||||
name="Intercompany Comparison"
|
||||
parent="account.account_reports_management_menu"
|
||||
action="accountant_cn.action_dn_fr_interco"
|
||||
groups="account.group_account_readonly,account.group_account_basic"
|
||||
sequence="40"/>
|
||||
|
||||
|
||||
<!-- ============================================================= -->
|
||||
<!-- REVIEW -->
|
||||
<!-- Enterprise: account_menuitem.xml (Control) -->
|
||||
<!-- account_reports/data/menuitems.xml (the rest) -->
|
||||
<!-- ============================================================= -->
|
||||
|
||||
<!-- Review > Control. Journal Audit is a control report, not a ledger:
|
||||
Enterprise keeps it here (account_reports/data/menuitems.xml:18) with
|
||||
sequence 10, next to the audit trail. The audit trail itself has no
|
||||
sequence in Enterprise, which makes it sort last; we give it an
|
||||
explicit 20 so the order does not depend on the creation id. -->
|
||||
<menuitem id="menu_report_journal_audit"
|
||||
name="Journal Audit"
|
||||
parent="account.account_audit_control_menu"
|
||||
action="accountant_cn.action_dn_fr_journal"
|
||||
groups="account.group_account_readonly"
|
||||
sequence="10"/>
|
||||
|
||||
<record id="account.account_audit_trail_menu" model="ir.ui.menu">
|
||||
<field name="sequence">20</field>
|
||||
</record>
|
||||
|
||||
<!-- Review > Audit > Working Files.
|
||||
Enterprise backs this with `account.return` (period review files with a
|
||||
full state machine). Community has no such model and the review
|
||||
workflow is a separate feature, so the menu is created here to keep the
|
||||
tree identical, and it opens the journal items that still need a
|
||||
decision. That is the entry point people actually need from this group:
|
||||
what is left to look at before closing the period. -->
|
||||
<record id="action_dn_working_files" model="ir.actions.act_window">
|
||||
<field name="name">Working Files</field>
|
||||
<field name="res_model">account.move.line</field>
|
||||
<field name="view_mode">list,pivot</field>
|
||||
<field name="domain">[
|
||||
('parent_state', '=', 'posted'),
|
||||
('display_type', 'not in', ('line_section', 'line_subsection', 'line_note')),
|
||||
('account_id.account_type', 'in', (
|
||||
'asset_receivable', 'liability_payable',
|
||||
'asset_cash', 'liability_credit_card',
|
||||
)),
|
||||
('full_reconcile_id', '=', False),
|
||||
]</field>
|
||||
<field name="context">{'search_default_group_by_account': 1}</field>
|
||||
<field name="help" type="html">
|
||||
<p class="o_view_nocontent_smiling_face">Nothing left to review</p>
|
||||
<p>Journal items still open on a reconciliation account show up here:
|
||||
receivables, payables and cash that have not been matched yet.</p>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
<menuitem id="account_audit_working_file_menu"
|
||||
parent="account.account_audit_menu"
|
||||
name="Audit"
|
||||
sequence="30"
|
||||
groups="account.group_account_readonly">
|
||||
<menuitem id="menu_action_working_files"
|
||||
name="Working Files"
|
||||
action="action_dn_working_files"/>
|
||||
</menuitem>
|
||||
|
||||
<!-- Review > Inventory. Enterprise fills this group with "Inventory
|
||||
Valuation" (account_reports); the community `account` module already
|
||||
ships that report as a client action, so we mount it directly. -->
|
||||
<menuitem id="account_audit_inventory_entries_menu"
|
||||
parent="account.account_audit_menu"
|
||||
name="Inventory"
|
||||
sequence="40"
|
||||
groups="account.group_account_readonly">
|
||||
|
||||
<menuitem id="menu_report_stock_valuation"
|
||||
name="Inventory Valuation"
|
||||
action="account.action_report_stock_valuation"
|
||||
groups="account.group_account_readonly"
|
||||
sequence="10"/>
|
||||
|
||||
</menuitem>
|
||||
|
||||
<!-- Review > Regularization Entries.
|
||||
Enterprise has exactly three entries here: Unrealized Currencies,
|
||||
Deferred Revenues and Deferred Expenses. We used to ship a combined
|
||||
"Deferred Revenues and Expenses" report (one menu entry instead of two)
|
||||
and an extra "Bank Reconciliation Status" that Enterprise does not have
|
||||
in this group at all, so both are corrected. -->
|
||||
<menuitem id="account_audit_regularization_entries_menu"
|
||||
parent="account.account_audit_menu"
|
||||
name="Regularization Entries"
|
||||
sequence="50"
|
||||
groups="account.group_account_readonly">
|
||||
|
||||
<menuitem id="menu_report_fx"
|
||||
name="Unrealized Currencies"
|
||||
action="accountant_cn.action_dn_fr_fx"
|
||||
groups="account.group_account_readonly"
|
||||
sequence="10"/>
|
||||
|
||||
<menuitem id="menu_report_deferred_revenue"
|
||||
name="Deferred Revenues"
|
||||
action="accountant_cn.action_dn_fr_deferred_revenue"
|
||||
groups="account.group_account_readonly"
|
||||
sequence="20"/>
|
||||
|
||||
<menuitem id="menu_report_deferred_expense"
|
||||
name="Deferred Expenses"
|
||||
action="accountant_cn.action_dn_fr_deferred_expense"
|
||||
groups="account.group_account_readonly"
|
||||
sequence="30"/>
|
||||
|
||||
</menuitem>
|
||||
|
||||
|
||||
<!-- ============================================================= -->
|
||||
<!-- ACCOUNTING > CLOSING -->
|
||||
<!-- Enterprise: account_menuitem.xml creates the group empty and -->
|
||||
<!-- these modules fill it: -->
|
||||
<!-- account_accountant Reconcile seq 65 -->
|
||||
<!-- account_reports Tax Returns seq 67 -->
|
||||
<!-- account_accountant Lock Dates… seq 70 -->
|
||||
<!-- account Secure Entries seq 80 -->
|
||||
<!-- Community already ships "Secure Entries" there. -->
|
||||
<!-- ============================================================= -->
|
||||
|
||||
<!-- Reconcile: the journal items still open on a reconciliation account.
|
||||
Enterprise opens its full reconciliation widget from here; Community
|
||||
has the same model but no matching widget, so this lists exactly the
|
||||
items that widget would show. -->
|
||||
<record id="action_dn_reconcile" model="ir.actions.act_window">
|
||||
<field name="name">Journal Items to reconcile</field>
|
||||
<field name="res_model">account.move.line</field>
|
||||
<field name="view_mode">list</field>
|
||||
<field name="domain">[
|
||||
('display_type', 'not in', ('line_section', 'line_subsection', 'line_note')),
|
||||
('account_id.reconcile', '=', True),
|
||||
('full_reconcile_id', '=', False),
|
||||
('parent_state', '=', 'posted'),
|
||||
]</field>
|
||||
<field name="context">{'search_default_group_by_account': 1, 'search_default_group_by_partner': 1}</field>
|
||||
<field name="help" type="html">
|
||||
<p class="o_view_nocontent_smiling_face">Everything is reconciled</p>
|
||||
<p>Posted journal items on a reconciliation account that still have no
|
||||
matching number show up here.</p>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
<menuitem id="menu_account_reconcile"
|
||||
name="Reconcile"
|
||||
parent="account.account_closing_menu"
|
||||
action="action_dn_reconcile"
|
||||
sequence="65"
|
||||
groups="account.group_account_user"/>
|
||||
|
||||
<!-- Lock Dates…: the period locking wizard of dn_accounting, which is the
|
||||
Community equivalent of Enterprise's `account.change.lock.date`. -->
|
||||
<menuitem id="menu_dn_lock_date_in_closing"
|
||||
name="Lock Dates…"
|
||||
parent="account.account_closing_menu"
|
||||
action="accountant_cn.action_dn_lock_date_wizard"
|
||||
sequence="70"
|
||||
groups="account.group_account_manager"/>
|
||||
|
||||
<!-- The two period-management groups belong under Closing, not under
|
||||
Accounting: Enterprise has no separate top-level entries for them, and
|
||||
closing the period is literally what they do. -->
|
||||
<record id="accountant_cn.menu_dn_bank_rec_root" model="ir.ui.menu">
|
||||
<field name="parent_id" ref="account.account_closing_menu"/>
|
||||
<field name="sequence">35</field>
|
||||
</record>
|
||||
|
||||
<record id="accountant_cn.menu_dn_accounting_root" model="ir.ui.menu">
|
||||
<field name="parent_id" ref="account.account_closing_menu"/>
|
||||
<field name="sequence">40</field>
|
||||
</record>
|
||||
|
||||
|
||||
<!-- Two menu records from the previous layout are gone for good. They are
|
||||
deleted rather than reassigned because keeping them would leave a
|
||||
duplicate entry in the tree: Odoo never removes an `ir.ui.menu` whose
|
||||
XML declaration disappears, it only stops updating it.
|
||||
* `menu_report_deferred` — replaced by the two separate Deferred
|
||||
Revenues / Deferred Expenses entries Enterprise ships.
|
||||
* `menu_report_bankrec_status` — Enterprise has no such entry under
|
||||
Regularization Entries; the reconciliation workspace lives under
|
||||
Closing > Bank Reconciliation instead. -->
|
||||
<delete model="ir.ui.menu" id="menu_report_deferred"/>
|
||||
<delete model="ir.ui.menu" id="menu_report_bankrec_status"/>
|
||||
|
||||
|
||||
<!-- ============================================================= -->
|
||||
<!-- CONFIGURATION -->
|
||||
<!-- ============================================================= -->
|
||||
<menuitem id="account.menu_account_config"
|
||||
name="Settings"
|
||||
parent="account.menu_finance_configuration"
|
||||
sequence="0"
|
||||
groups="base.group_system"/>
|
||||
|
||||
<!-- Community creates `account_report_folder` ("Reporting") under
|
||||
Configuration > Accounting but never puts anything in it: Enterprise
|
||||
uses it for the report designer and the report line definitions.
|
||||
We park our own report configuration there, which also removes the two
|
||||
entries that used to sit flat next to "Taxes" and "Journals". -->
|
||||
<record id="account.account_report_folder" model="ir.ui.menu">
|
||||
<field name="name">Reporting</field>
|
||||
<field name="sequence">4</field>
|
||||
</record>
|
||||
|
||||
<record id="accountant_cn.menu_dn_fr_config" model="ir.ui.menu">
|
||||
<field name="parent_id" ref="account.account_report_folder"/>
|
||||
<field name="sequence">10</field>
|
||||
</record>
|
||||
|
||||
<record id="accountant_cn.menu_dn_fr_external_value" model="ir.ui.menu">
|
||||
<field name="parent_id" ref="account.account_report_folder"/>
|
||||
<field name="sequence">20</field>
|
||||
</record>
|
||||
|
||||
<record id="accountant_cn.menu_dn_report_config" model="ir.ui.menu">
|
||||
<field name="parent_id" ref="account.account_report_folder"/>
|
||||
<field name="name">DN Report Builder</field>
|
||||
<field name="sequence">30</field>
|
||||
</record>
|
||||
|
||||
</odoo>
|
||||
28
accountant_cn/views/wizard__dn_loan_close_wizard_views.xml
Normal file
28
accountant_cn/views/wizard__dn_loan_close_wizard_views.xml
Normal file
@@ -0,0 +1,28 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<odoo>
|
||||
|
||||
<record id="dn_loan_close_wizard_view" model="ir.ui.view">
|
||||
<field name="name">dn.loan.close.wizard.form</field>
|
||||
<field name="model">dn.loan.close.wizard</field>
|
||||
<field name="arch" type="xml">
|
||||
<form string="Close Loan">
|
||||
<field name="currency_id" invisible="1"/>
|
||||
<group>
|
||||
<field name="loan_id" readonly="1" force_save="1"/>
|
||||
<field name="date"/>
|
||||
</group>
|
||||
<div class="alert alert-info mb-0" role="alert">
|
||||
Draft entries dated after the close date are deleted. Posted
|
||||
entries are kept: they are already in the ledger and have to be
|
||||
reversed deliberately if they are no longer wanted.
|
||||
</div>
|
||||
<footer>
|
||||
<button name="action_save" string="Close Loan" type="object"
|
||||
class="btn-primary"/>
|
||||
<button string="Cancel" class="btn-secondary" special="cancel"/>
|
||||
</footer>
|
||||
</form>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
</odoo>
|
||||
38
accountant_cn/views/wizard__dn_loan_compute_wizard_views.xml
Normal file
38
accountant_cn/views/wizard__dn_loan_compute_wizard_views.xml
Normal file
@@ -0,0 +1,38 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<odoo>
|
||||
|
||||
<record id="dn_loan_compute_wizard_view" model="ir.ui.view">
|
||||
<field name="name">dn.loan.compute.wizard.form</field>
|
||||
<field name="model">dn.loan.compute.wizard</field>
|
||||
<field name="arch" type="xml">
|
||||
<form string="Compute Loan">
|
||||
<field name="currency_id" invisible="1"/>
|
||||
<field name="company_id" invisible="1"/>
|
||||
<group>
|
||||
<group string="Loan">
|
||||
<field name="loan_id" readonly="1" force_save="1"/>
|
||||
<field name="loan_amount" widget="monetary"/>
|
||||
<field name="interest_rate" widget="percentage"/>
|
||||
<field name="method"/>
|
||||
</group>
|
||||
<group string="Schedule">
|
||||
<field name="loan_term"/>
|
||||
<field name="payments_per_year"/>
|
||||
<field name="start_date"/>
|
||||
<field name="first_payment_date"/>
|
||||
<field name="day_count"/>
|
||||
</group>
|
||||
</group>
|
||||
<separator string="Preview"/>
|
||||
<field name="preview" readonly="1" nolabel="1"
|
||||
class="text-monospace small"/>
|
||||
<footer>
|
||||
<button name="action_save" string="Save Schedule" type="object"
|
||||
class="btn-primary"/>
|
||||
<button string="Cancel" class="btn-secondary" special="cancel"/>
|
||||
</footer>
|
||||
</form>
|
||||
</field>
|
||||
</record>
|
||||
|
||||
</odoo>
|
||||
2
accountant_cn/wizard/__init__.py
Normal file
2
accountant_cn/wizard/__init__.py
Normal file
@@ -0,0 +1,2 @@
|
||||
from . import dn_loan_compute_wizard
|
||||
from . import dn_loan_close_wizard
|
||||
43
accountant_cn/wizard/dn_loan_close_wizard.py
Normal file
43
accountant_cn/wizard/dn_loan_close_wizard.py
Normal file
@@ -0,0 +1,43 @@
|
||||
from odoo import _, fields, models
|
||||
from odoo.tools import format_date
|
||||
|
||||
|
||||
class DnLoanCloseWizard(models.TransientModel):
|
||||
_name = 'dn.loan.close.wizard'
|
||||
_description = 'Close Loan Wizard'
|
||||
|
||||
loan_id = fields.Many2one('dn.loan', string='Loan', required=True,
|
||||
ondelete='cascade')
|
||||
currency_id = fields.Many2one(related='loan_id.currency_id')
|
||||
date = fields.Date(
|
||||
string='Close Date', required=True, default=fields.Date.context_today,
|
||||
help="Draft entries dated after this day are deleted, because the loan "
|
||||
"will not run past it. Entries already posted are kept: they are "
|
||||
"in the ledger and can only be reversed, not removed.",
|
||||
)
|
||||
|
||||
def action_save(self):
|
||||
"""Stop the loan: drop the future drafts, keep what is already booked.
|
||||
|
||||
Only draft entries are removed. A posted entry may have been reported
|
||||
already, so deleting it silently would misstate a closed period; it has
|
||||
to be reversed deliberately, by whoever owns the ledger.
|
||||
"""
|
||||
self.ensure_one()
|
||||
dropped = self.loan_id.move_ids.filtered(
|
||||
lambda m: m.state == 'draft' and m.date > self.date)
|
||||
kept = self.loan_id.move_ids.filtered(
|
||||
lambda m: m.state == 'posted' and m.date > self.date)
|
||||
dropped.unlink()
|
||||
|
||||
self.loan_id.state = 'closed'
|
||||
body = _("Closed on the %(date)s.", date=format_date(self.env, self.date))
|
||||
if dropped:
|
||||
body += " " + _("%(count)s draft entries scheduled after that date "
|
||||
"were removed.", count=len(dropped))
|
||||
if kept:
|
||||
body += " " + _("%(count)s posted entries after that date were kept "
|
||||
"and must be reversed manually if needed.",
|
||||
count=len(kept))
|
||||
self.loan_id.message_post(body=body)
|
||||
return {'type': 'ir.actions.act_window_close'}
|
||||
194
accountant_cn/wizard/dn_loan_compute_wizard.py
Normal file
194
accountant_cn/wizard/dn_loan_compute_wizard.py
Normal file
@@ -0,0 +1,194 @@
|
||||
from dateutil.relativedelta import relativedelta
|
||||
|
||||
from odoo import _, api, fields, models
|
||||
from odoo.exceptions import ValidationError
|
||||
|
||||
from ..lib.amortization import Schedule
|
||||
|
||||
|
||||
class DnLoanComputeWizard(models.TransientModel):
|
||||
_name = 'dn.loan.compute.wizard'
|
||||
_description = 'Loan Schedule Wizard'
|
||||
|
||||
loan_id = fields.Many2one('dn.loan', string='Loan', required=True,
|
||||
ondelete='cascade')
|
||||
currency_id = fields.Many2one(related='loan_id.currency_id')
|
||||
company_id = fields.Many2one(related='loan_id.company_id')
|
||||
|
||||
loan_amount = fields.Monetary(string='Loan Amount', required=True)
|
||||
interest_rate = fields.Float(
|
||||
string='Annual Interest Rate', required=True, digits=(12, 6),
|
||||
help="Percentage per year, for example 5 for 5%.",
|
||||
)
|
||||
loan_term = fields.Integer(
|
||||
string='Installments', required=True, default=12,
|
||||
help="Number of installments, not years.",
|
||||
)
|
||||
payments_per_year = fields.Selection(
|
||||
selection=[('12', 'Monthly'), ('4', 'Quarterly'),
|
||||
('2', 'Semi-annually'), ('1', 'Annually')],
|
||||
string='Frequency', default='12', required=True,
|
||||
)
|
||||
method = fields.Selection(
|
||||
selection=[('annuity', 'Annuity'), ('linear', 'Linear'),
|
||||
('interest_only', 'Interest Only')],
|
||||
string='Repayment Method', default='annuity', required=True,
|
||||
)
|
||||
start_date = fields.Date(
|
||||
string='Start Date', required=True, default=fields.Date.context_today,
|
||||
)
|
||||
first_payment_date = fields.Date(
|
||||
string='First Payment', required=True,
|
||||
default=lambda self: fields.Date.context_today(self).replace(day=1)
|
||||
+ relativedelta(months=1),
|
||||
)
|
||||
day_count = fields.Selection(
|
||||
selection=[('30E/360', '30E/360'), ('A/360', 'A/360'),
|
||||
('A/365F', 'A/365F')],
|
||||
string='Day Count', default='30E/360', required=True,
|
||||
help="How the interest of a period is prorated. 30E/360 treats every "
|
||||
"month as thirty days, which is the usual convention for corporate "
|
||||
"loans; the actual/actual variants follow the calendar.",
|
||||
)
|
||||
preview = fields.Text(string='Preview', compute='_compute_preview')
|
||||
|
||||
# -- validation -------------------------------------------------------
|
||||
|
||||
@api.constrains('loan_amount', 'interest_rate', 'loan_term', 'start_date',
|
||||
'first_payment_date')
|
||||
def _check_values(self):
|
||||
for wizard in self:
|
||||
if wizard.loan_amount <= 0:
|
||||
raise ValidationError(_("The loan amount must be positive."))
|
||||
if not 0 <= wizard.interest_rate <= 100:
|
||||
raise ValidationError(_("The interest rate must be between 0 and 100."))
|
||||
if wizard.loan_term <= 0:
|
||||
raise ValidationError(_("The number of installments must be positive."))
|
||||
if (wizard.first_payment_date and wizard.start_date
|
||||
and wizard.first_payment_date <= wizard.start_date):
|
||||
raise ValidationError(_(
|
||||
"The first payment must come after the start date."))
|
||||
|
||||
@api.onchange('start_date')
|
||||
def _onchange_start_date(self):
|
||||
"""Keep the first payment one month after the start date."""
|
||||
if self.start_date:
|
||||
self.first_payment_date = self.start_date.replace(day=1) \
|
||||
+ relativedelta(months=1)
|
||||
|
||||
# -- computation ------------------------------------------------------
|
||||
|
||||
def _get_schedule(self):
|
||||
"""Build the engine for the current values.
|
||||
|
||||
Kept separate from the preview so the saved schedule and the previewed
|
||||
one can never come from different code paths.
|
||||
"""
|
||||
self.ensure_one()
|
||||
return Schedule(
|
||||
amount=self.loan_amount,
|
||||
annual_rate=self.interest_rate,
|
||||
term=self.loan_term,
|
||||
start_date=self.start_date,
|
||||
first_payment_date=self.first_payment_date,
|
||||
method=self.method,
|
||||
payments_per_year=int(self.payments_per_year),
|
||||
day_count=self.day_count,
|
||||
)
|
||||
|
||||
@api.depends('loan_amount', 'interest_rate', 'loan_term', 'start_date',
|
||||
'first_payment_date', 'method', 'payments_per_year', 'day_count')
|
||||
def _compute_preview(self):
|
||||
"""Show the first and last five installments plus the totals.
|
||||
|
||||
A full sixty-row schedule would not fit in a wizard and could not be
|
||||
read anyway. What matters before saving is whether the first payments
|
||||
and the final balance look right.
|
||||
"""
|
||||
for wizard in self:
|
||||
if not (wizard.loan_amount and wizard.loan_term and wizard.start_date):
|
||||
wizard.preview = ''
|
||||
continue
|
||||
try:
|
||||
rows = wizard._get_schedule().installments()
|
||||
except ValueError as error:
|
||||
wizard.preview = str(error)
|
||||
continue
|
||||
|
||||
# `%Ns` right-aligns strings in Python's %-formatting, which is what
|
||||
# the currency columns need; `%-Ns` left-aligns the date column.
|
||||
header = "%-12s%15s%15s%15s%15s" % (
|
||||
_("Date"), _("Principal"), _("Interest"), _("Payment"),
|
||||
_("Balance"))
|
||||
body = [header]
|
||||
|
||||
def money(amount):
|
||||
"""`res.currency.format()` adds 0.0 to its argument, so it only
|
||||
accepts floats while the engine works with Decimals."""
|
||||
return wizard.currency_id.format(float(amount))
|
||||
|
||||
def row(installment):
|
||||
return "%-12s%15s%15s%15s%15s" % (
|
||||
installment.date.strftime('%Y-%m-%d'),
|
||||
money(installment.principal),
|
||||
money(installment.interest),
|
||||
money(installment.payment),
|
||||
money(installment.balance),
|
||||
)
|
||||
|
||||
for installment in rows[:5]:
|
||||
body.append(row(installment))
|
||||
if len(rows) > 10:
|
||||
body.append("%-12s%15s%15s%15s%15s" % (
|
||||
'...', '...', '...', '...', '...'))
|
||||
if len(rows) > 5:
|
||||
for installment in rows[-5:]:
|
||||
body.append(row(installment))
|
||||
|
||||
principal = sum(r.principal for r in rows)
|
||||
interest = sum(r.interest for r in rows)
|
||||
body.append('')
|
||||
body.append(_("Installments: %(count)s", count=len(rows)))
|
||||
body.append(_("Total principal: %(amount)s",
|
||||
amount=money(principal)))
|
||||
body.append(_("Total interest: %(amount)s",
|
||||
amount=money(interest)))
|
||||
wizard.preview = "\n".join(body)
|
||||
|
||||
# -- actions ----------------------------------------------------------
|
||||
|
||||
def action_save(self):
|
||||
"""Replace the loan's schedule with the computed one."""
|
||||
self.ensure_one()
|
||||
rows = self._get_schedule().installments()
|
||||
|
||||
self.loan_id.line_ids.unlink()
|
||||
self.env['dn.loan.line'].create([{
|
||||
'loan_id': self.loan_id.id,
|
||||
'date': installment.date,
|
||||
'principal': float(installment.principal),
|
||||
'interest': float(installment.interest),
|
||||
} for installment in rows])
|
||||
|
||||
self.loan_id.write({
|
||||
'date': self.start_date,
|
||||
'amount_borrowed': self.loan_amount,
|
||||
'interest': sum(r.interest for r in rows),
|
||||
'duration': len(rows),
|
||||
'method': self.method,
|
||||
})
|
||||
self.loan_id.message_post(body=_(
|
||||
"Amortization schedule computed: %(count)s installments, "
|
||||
"%(interest)s of total interest.",
|
||||
count=len(rows),
|
||||
interest=self.currency_id.format(float(sum(r.interest for r in rows))),
|
||||
))
|
||||
|
||||
return {
|
||||
'name': self.loan_id.display_name,
|
||||
'res_id': self.loan_id.id,
|
||||
'type': 'ir.actions.act_window',
|
||||
'res_model': 'dn.loan',
|
||||
'target': 'current',
|
||||
'views': [[False, 'form']],
|
||||
}
|
||||
Reference in New Issue
Block a user