Compare commits
8 Commits
0bc5044fbc
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 88b4fe3d59 | |||
| 5fc4382687 | |||
| 9b924747c5 | |||
| 7526a5fe4d | |||
| 3b5af1e3a6 | |||
| 974a1fb10b | |||
| 28bba64611 | |||
| 53b7d22429 |
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']],
|
||||
}
|
||||
18
dn_ai/__init__.py
Normal file
18
dn_ai/__init__.py
Normal file
@@ -0,0 +1,18 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import logging
|
||||
|
||||
from . import models
|
||||
from . import controllers
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def post_init_hook(env):
|
||||
"""Give the built-in agent a partner so it can post in Discuss."""
|
||||
agent = env.ref('dn_ai.ai_default_agent', raise_if_not_found=False)
|
||||
if agent and not agent.partner_id:
|
||||
agent.partner_id = env['res.partner'].create({
|
||||
'name': agent.name or 'AI Assistant',
|
||||
'is_company': False,
|
||||
})
|
||||
_logger.info("dn_ai: post-install ready (agent=%s)", agent.name if agent else 'none')
|
||||
124
dn_ai/__manifest__.py
Normal file
124
dn_ai/__manifest__.py
Normal file
@@ -0,0 +1,124 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
{
|
||||
'name': 'DN AI',
|
||||
'version': '20.0.1.0.0',
|
||||
'category': 'Productivity/AI',
|
||||
'summary': 'Open-source AI assistant for Odoo Community — agents, skills, tools, agentic loop (LGPL-3)',
|
||||
'description': """
|
||||
DN AI
|
||||
=====
|
||||
|
||||
An open-source re-implementation of the Odoo Enterprise AI assistant for
|
||||
Odoo 20 Community.
|
||||
|
||||
Core capabilities
|
||||
-----------------
|
||||
* **Agents** — configurable assistants with a system prompt and skills.
|
||||
* **Skills** — bundles of instructions plus tools that teach the assistant a
|
||||
workflow (search the database, create/update records, navigate the UI, ...).
|
||||
* **Tools** — any server action can be exposed to the model with a name,
|
||||
description and JSON schema. 20 built-in tools ship with the module.
|
||||
* **Agentic loop** — a resumable, persisted state machine that keeps calling
|
||||
the model, executes tool calls, pauses for user confirmation or answers, and
|
||||
streams progress back into the chat.
|
||||
* **Chat panel** — a dedicated ``AI Chat`` client action, and the same
|
||||
conversation is listed in Discuss (its ``ai_chat`` channel type is registered
|
||||
with the mail store) so the transcript is stored as regular messages.
|
||||
* **Attachments** — pick, paste or drag files into the chat. Text, CSV, Word,
|
||||
Excel, PowerPoint and OpenDocument files are parsed server-side (standard
|
||||
library only); images and PDFs are sent as multimodal content when the
|
||||
provider supports vision.
|
||||
* **Provider layer** — DeepSeek and Alibaba Qwen out of the box, plus any
|
||||
OpenAI-compatible endpoint (Ollama, vLLM, ...). No IAP credits required.
|
||||
|
||||
Not yet implemented (planned for phase 2): knowledge sources / RAG, and the
|
||||
per-business-app extension modules.
|
||||
|
||||
License: LGPL-3. No Odoo Enterprise source code is used, copied or derived.
|
||||
""",
|
||||
'author': 'DN Community',
|
||||
'website': '',
|
||||
'license': 'LGPL-3',
|
||||
'application': True,
|
||||
'installable': True,
|
||||
'auto_install': False,
|
||||
'depends': [
|
||||
'mail',
|
||||
'base_setup',
|
||||
],
|
||||
'external_dependencies': {
|
||||
# PyMuPDF is optional: it only powers local PDF text extraction when a
|
||||
# provider has neither a Files API nor vision. The importer degrades
|
||||
# gracefully when it is absent, so do not make it a hard requirement.
|
||||
'python': [],
|
||||
},
|
||||
'data': [
|
||||
# ---- security first
|
||||
'security/ai_security.xml',
|
||||
'security/ir.access.csv',
|
||||
|
||||
# ---- views
|
||||
'views/ai_agent_views.xml',
|
||||
'views/ai_skill_views.xml',
|
||||
'views/ai_tool_views.xml',
|
||||
'views/ai_composer_views.xml',
|
||||
'views/ai_prompt_button_views.xml',
|
||||
'views/templates.xml',
|
||||
'views/res_config_settings_views.xml',
|
||||
'views/ai_menus.xml',
|
||||
|
||||
# ---- server actions (tools) then skills then the default agent
|
||||
'data/ir_actions_server_data.xml',
|
||||
'data/ai_skill_data.xml',
|
||||
'data/ai_agent_data.xml',
|
||||
'data/ir_cron.xml',
|
||||
],
|
||||
'assets': {
|
||||
'web.assets_backend': [
|
||||
# Order matters: the store model must be registered before the
|
||||
# channel patch declares a relation to it.
|
||||
'dn_ai/static/src/ai_agent_model.js',
|
||||
'dn_ai/static/src/discuss_channel_patch.js',
|
||||
# Client-side tool runner: the server returns `client_tool` payloads
|
||||
# for navigation, but only the browser can honour them.
|
||||
'dn_ai/static/src/client_tools.js',
|
||||
# Patches that make the AI payload usable by the Community views.
|
||||
# `SearchModel.applyAISearch` does not exist here, so these supply
|
||||
# the equivalent (see web/search_model_patch.js).
|
||||
'dn_ai/static/src/web/search_model_patch.js',
|
||||
'dn_ai/static/src/web/search_bar_patch.js',
|
||||
'dn_ai/static/src/web/view_patch.js',
|
||||
# The AI conversation is rendered by Odoo's own chat window, so the
|
||||
# agent loop is wired into the native send path (`Thread.post`)
|
||||
# instead of a bespoke RPC from a custom panel.
|
||||
'dn_ai/static/src/thread_patch.js',
|
||||
'dn_ai/static/src/composer_patch.js',
|
||||
'dn_ai/static/src/pending_request.js',
|
||||
'dn_ai/static/src/pending_request.xml',
|
||||
'dn_ai/static/src/pending_request.scss',
|
||||
# Opens a conversation in the native window; shared by the floating
|
||||
# button, the chatter action and the AI menu entry.
|
||||
'dn_ai/static/src/ai_chat_launcher.js',
|
||||
# `dn_ai.chat` client action: opens the conversation in the native
|
||||
# window instead of rendering a page of its own.
|
||||
'dn_ai/static/src/chat_action.js',
|
||||
'dn_ai/static/src/chat_action.xml',
|
||||
# Floating bottom-right entry point (main_components). Replaces the
|
||||
# former navbar systray item, which used FontAwesome (removed in
|
||||
# Odoo 20, so the icon never rendered) and collapsed into the burger
|
||||
# menu on small screens.
|
||||
'dn_ai/static/src/assistant.js',
|
||||
'dn_ai/static/src/assistant.xml',
|
||||
'dn_ai/static/src/assistant.scss',
|
||||
'dn_ai/static/src/chatter_ai_button.js',
|
||||
],
|
||||
# Pivot and graph are only loaded on demand (they live in web's lazy
|
||||
# bundle), so their controllers must be patched there — patching them in
|
||||
# `assets_backend` would import the module eagerly and defeat the point.
|
||||
'web.assets_backend_lazy': [
|
||||
'dn_ai/static/src/web/pivot_controller_patch.js',
|
||||
'dn_ai/static/src/web/graph_controller_patch.js',
|
||||
],
|
||||
},
|
||||
'post_init_hook': 'post_init_hook',
|
||||
}
|
||||
2
dn_ai/controllers/__init__.py
Normal file
2
dn_ai/controllers/__init__.py
Normal file
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from . import ai
|
||||
201
dn_ai/controllers/ai.py
Normal file
201
dn_ai/controllers/ai.py
Normal file
@@ -0,0 +1,201 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import logging
|
||||
|
||||
from odoo import http
|
||||
from odoo.exceptions import AccessError, MissingError, UserError
|
||||
from odoo.http import request
|
||||
|
||||
from ..utils.ai_attachment_tools import format_size, guess_kind
|
||||
from ..utils.ai_utils import get_text_from_parts, markdown_format
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
# Refused before a single byte reaches the filestore. Generous enough for a
|
||||
# scanned PDF or a photo, small enough that the request cannot be used to fill
|
||||
# the disk.
|
||||
MAX_UPLOAD_BYTES = 32 * 1024 * 1024
|
||||
|
||||
|
||||
class AIController(http.Controller):
|
||||
|
||||
def _get_channel(self, channel_id):
|
||||
channel = request.env['discuss.channel'].sudo().browse(channel_id).exists()
|
||||
if not channel or channel.channel_type != 'ai_chat':
|
||||
raise MissingError(request.env._("This AI conversation does not exist."))
|
||||
channel.check_access('read')
|
||||
return channel
|
||||
|
||||
def _get_session(self, channel):
|
||||
session = request.env['ai.session'].sudo()._get_channel_session(channel)
|
||||
if not session:
|
||||
raise MissingError(request.env._("This AI conversation has no session."))
|
||||
return session
|
||||
|
||||
@http.route('/dn_ai/start_session', type='jsonrpc', auth='user', methods=['POST'])
|
||||
def start_session(self, channel_id, body, current_view_info=None):
|
||||
"""Post a user message and run the agent until it needs input."""
|
||||
channel = self._get_channel(channel_id)
|
||||
session = self._get_session(channel)
|
||||
if not session.agent_id._is_user_access_allowed():
|
||||
raise AccessError(request.env._("You are not allowed to use this agent."))
|
||||
|
||||
# The user message lives in the chatter, like any other message.
|
||||
message = channel.sudo().message_post(
|
||||
body=body or '',
|
||||
author_id=request.env.user.partner_id.id,
|
||||
message_type='comment',
|
||||
subtype_xmlid='mail.mt_comment',
|
||||
)
|
||||
parts = [{'type': 'text', 'text': body or ''}]
|
||||
context = dict(request.env.context)
|
||||
state = session.submit_message(parts, context=context)
|
||||
return self._session_payload(session, message.id)
|
||||
|
||||
@http.route('/dn_ai/start_session_advance', type='jsonrpc', auth='user', methods=['POST'])
|
||||
def start_session_advance(self, channel_id, mail_message_id, current_view_info=None):
|
||||
"""Run the agent on a message the native mail composer already posted.
|
||||
|
||||
The native chat window (``mail.ChatWindow``) posts through
|
||||
``message_post`` itself, so unlike ``/dn_ai/start_session`` the message
|
||||
is already stored and rendered when this route is called. All that is
|
||||
left to do is handing it to the agent loop.
|
||||
"""
|
||||
channel = self._get_channel(channel_id)
|
||||
if not channel.sudo().ai_agent_id:
|
||||
raise MissingError(request.env._("This AI chat has no agent attached."))
|
||||
payload = request.env['ai.session'].dn_ai_submit_message(
|
||||
channel.id, mail_message_id, context=dict(request.env.context))
|
||||
return payload
|
||||
|
||||
@http.route('/dn_ai/resume', type='jsonrpc', auth='user', methods=['POST'])
|
||||
def resume(self, session_id, response):
|
||||
session = request.env['ai.session'].sudo().browse(session_id).exists()
|
||||
if not session:
|
||||
raise MissingError(request.env._("This AI conversation does not exist."))
|
||||
session._root_session().channel_id.check_access('read')
|
||||
state = session.resume_interaction(response)
|
||||
return self._session_payload(session)
|
||||
|
||||
@http.route('/dn_ai/poll', type='jsonrpc', auth='user', methods=['POST'])
|
||||
def poll(self, session_id):
|
||||
"""Drain the browser actions queued by the tools of the current turn."""
|
||||
session = request.env['ai.session'].sudo().browse(session_id).exists()
|
||||
if not session:
|
||||
raise MissingError(request.env._("This AI conversation does not exist."))
|
||||
session._root_session().channel_id.check_access('read')
|
||||
return session.dn_ai_poll()
|
||||
|
||||
@http.route('/dn_ai/direct_response', type='jsonrpc', auth='user', methods=['POST'])
|
||||
def direct_response(self, prompt, interface_key='chatter_ai_button',
|
||||
res_model=None, res_id=None, as_html=True):
|
||||
"""One-shot answer used by composer buttons (no chat session)."""
|
||||
agent = request.env['ai.composer']._get_agent(res_model, interface_key)
|
||||
if not agent:
|
||||
raise MissingError(request.env._("No AI agent is configured."))
|
||||
parts = [{'type': 'text', 'text': prompt}]
|
||||
response = agent._generate_single_response(parts)
|
||||
text = get_text_from_parts(response)
|
||||
return markdown_format(text) if as_html else text
|
||||
|
||||
def _session_payload(self, session, message_id=None):
|
||||
return {
|
||||
'session_id': session.id,
|
||||
'loop_state': session.loop_state,
|
||||
'resume_token': session.resume_token if session.loop_state != 'ready' else False,
|
||||
'pending': (session.pending_tool_call or {}).get('request') or {},
|
||||
'client_tools': session.client_tool_queue or [],
|
||||
'message_id': message_id,
|
||||
}
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# attachments
|
||||
# ------------------------------------------------------------------
|
||||
@http.route('/dn_ai/upload_attachment', type='http', auth='user', methods=['POST'],
|
||||
csrf=True)
|
||||
def upload_attachment(self, ufile=None, channel_id=None):
|
||||
"""Store one file for an AI conversation.
|
||||
|
||||
Kept as a plain HTTP route rather than a JSON-RPC one because the
|
||||
browser has to post ``multipart/form-data``; JSON-RPC bodies cannot
|
||||
carry binary. The response mirrors ``/web/binary/upload_attachment``
|
||||
so the client-side code looks familiar.
|
||||
|
||||
The attachment is *not* bound to a message yet: it is created as a
|
||||
pending upload (``res_model='mail.compose.message'``) and only promoted
|
||||
to a real message attachment when the user actually sends, which is why
|
||||
abandoned drafts leave nothing behind in the conversation.
|
||||
"""
|
||||
if not ufile:
|
||||
return request.make_json_response({'error': request.env._("No file was uploaded.")})
|
||||
channel = request.env['discuss.channel'].sudo().browse(
|
||||
int(channel_id or 0)).exists()
|
||||
if not channel or channel.channel_type != 'ai_chat':
|
||||
return request.make_json_response(
|
||||
{'error': request.env._("This AI conversation does not exist.")})
|
||||
try:
|
||||
channel.check_access('read')
|
||||
except AccessError:
|
||||
return request.make_json_response(
|
||||
{'error': request.env._("You are not allowed to use this conversation.")})
|
||||
|
||||
data = ufile.read()
|
||||
filename = ufile.filename or 'file'
|
||||
if not data:
|
||||
return request.make_json_response({'error': request.env._("The file is empty.")})
|
||||
if len(data) > MAX_UPLOAD_BYTES:
|
||||
return request.make_json_response({
|
||||
'error': request.env._(
|
||||
"The file is too large (%(size)s). The limit is %(limit)s.",
|
||||
size=format_size(len(data)), limit=format_size(MAX_UPLOAD_BYTES)),
|
||||
})
|
||||
|
||||
attachment = request.env['ir.attachment'].sudo().create({
|
||||
'name': filename,
|
||||
'raw': data,
|
||||
'mimetype': ufile.content_type or None,
|
||||
# Pending-upload convention from mail: linked to a real record only
|
||||
# when `message_post(attachment_ids=...)` runs on send.
|
||||
'res_model': 'mail.compose.message',
|
||||
'res_id': 0,
|
||||
})
|
||||
kind = guess_kind(attachment.mimetype, filename)
|
||||
return request.make_json_response({
|
||||
'id': attachment.id,
|
||||
'name': attachment.name,
|
||||
'mimetype': attachment.mimetype or '',
|
||||
'size': attachment.file_size or 0,
|
||||
# Rendered as a hint under the chip: the model reads text formats
|
||||
# natively, while an image/PDF is only understood when the provider
|
||||
# supports vision — and the user deserves to know which case applies.
|
||||
'kind': kind,
|
||||
'readable': kind != 'unsupported',
|
||||
})
|
||||
|
||||
@http.route('/dn_ai/attachment_preview', type='jsonrpc', auth='user', methods=['POST'])
|
||||
def attachment_preview(self, attachment_id):
|
||||
"""Show what the model will actually receive for a file.
|
||||
|
||||
Useful when a question comes back wrong: the answer is almost always
|
||||
that the extraction found nothing (scanned PDF, legacy .doc, exotic
|
||||
encoding), and this makes that visible instead of mysterious.
|
||||
"""
|
||||
attachment = request.env['ir.attachment'].browse(int(attachment_id)).exists()
|
||||
if not attachment:
|
||||
raise MissingError(request.env._("This attachment does not exist."))
|
||||
if attachment.create_uid != request.env.user and not request.env.is_admin():
|
||||
raise AccessError(request.env._("You are not allowed to read this attachment."))
|
||||
parts = attachment._dn_ai_read()
|
||||
texts = []
|
||||
for part in parts:
|
||||
if part.get('type') == 'text':
|
||||
texts.append(part.get('text') or '')
|
||||
else:
|
||||
texts.append(request.env._(
|
||||
"[binary content, %(mimetype)s]", mimetype=part.get('mimetype')))
|
||||
return {
|
||||
'id': attachment.id,
|
||||
'name': attachment.name,
|
||||
'mimetype': attachment.mimetype or '',
|
||||
'size': attachment.file_size or 0,
|
||||
'content': '\n'.join(texts)[:5000],
|
||||
}
|
||||
44
dn_ai/data/ai_agent_data.xml
Normal file
44
dn_ai/data/ai_agent_data.xml
Normal file
@@ -0,0 +1,44 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<odoo>
|
||||
<record id="ai_default_agent" model="ai.agent">
|
||||
<field name="name">Odoo AI</field>
|
||||
<field name="subtitle">I'm your Odoo sidekick for most day-to-day tasks.</field>
|
||||
<field name="sequence">1</field>
|
||||
<field name="is_system_agent" eval="True"/>
|
||||
<field name="skill_ids" eval="[(6, 0, [
|
||||
ref('ai_skill_information_retrieval_query'),
|
||||
ref('ai_skill_natural_language_query'),
|
||||
ref('ai_skill_update_records'),
|
||||
ref('ai_skill_create_records'),
|
||||
])]"/>
|
||||
<field name="system_prompt">You are the main Odoo AI Assistant. Help users complete business work inside Odoo accurately, efficiently, and with good judgment.
|
||||
|
||||
## Working Style
|
||||
- Be practical, concise, and action-oriented. Prefer making progress when the user's intent is clear.
|
||||
- Ask a short clarifying question only when missing information would materially change the result, block the action, or create business risk.
|
||||
- Use a professional, supportive tone. Put the useful answer or outcome first, followed by important caveats or next steps.
|
||||
|
||||
## Collaboration
|
||||
- Adapt to the user's intent.
|
||||
- For information requests, answer from the available evidence.
|
||||
- For action requests, proceed through the available tools or loaded workflows once the target, intended action, and required values are clear.
|
||||
- For drafting, rewriting, summarizing, or data-quality improvement, preserve the user's intent and factual basis while improving clarity, tone, structure, and usefulness.
|
||||
- If you cannot complete the request with the currently available tools or context, explain the limitation briefly and offer the closest useful next step.</field>
|
||||
</record>
|
||||
|
||||
<record id="ai_composer_chatter" model="ai.composer">
|
||||
<field name="name">Chatter AI button</field>
|
||||
<field name="interface_key">chatter_ai_button</field>
|
||||
<field name="ai_agent_id" ref="ai_default_agent"/>
|
||||
<field name="is_system_default" eval="True"/>
|
||||
<field name="default_prompt">The user opened the AI assistant from the chatter of the current record.</field>
|
||||
</record>
|
||||
|
||||
<record id="ai_composer_systray" model="ai.composer">
|
||||
<field name="name">Systray AI button</field>
|
||||
<field name="interface_key">systray_ai_button</field>
|
||||
<field name="ai_agent_id" ref="ai_default_agent"/>
|
||||
<field name="is_system_default" eval="True"/>
|
||||
<field name="default_prompt">The user opened the AI assistant from the top bar, without focusing any record.</field>
|
||||
</record>
|
||||
</odoo>
|
||||
124
dn_ai/data/ai_skill_data.xml
Normal file
124
dn_ai/data/ai_skill_data.xml
Normal file
@@ -0,0 +1,124 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<odoo>
|
||||
<!-- ============ Search Database ============ -->
|
||||
<record id="ai_skill_information_retrieval_query" model="ai.skill">
|
||||
<field name="name">Search Database</field>
|
||||
<field name="sequence">10</field>
|
||||
<field name="is_native_skill" eval="True"/>
|
||||
<field name="description">Read data from any Odoo record: search, filter, aggregate and read field values.</field>
|
||||
<field name="instructions">## Search Database
|
||||
|
||||
You can retrieve information from any Odoo record.
|
||||
|
||||
### Workflow
|
||||
1. If you do not know the technical model name, call `get_models`.
|
||||
2. Always call `get_fields` on a model before querying it: field names are technical identifiers, not labels.
|
||||
3. Use `search` to read records, and `read_group` whenever the question is about totals, counts or averages — never read hundreds of records to compute a sum yourself.
|
||||
4. When filtering on a date, compute the boundary with `compute_date`. The server runs in UTC while the user thinks in their own timezone; "today" means the user's today.
|
||||
|
||||
### Rules
|
||||
- Never invent records, ids or field values. If a search returns nothing, say so and propose a broader search.
|
||||
- Never guess a field name. If `get_fields` does not list it, it does not exist.
|
||||
- Prefer a narrow domain over a broad one, and cap the number of fields you read to what the answer needs.
|
||||
- When the question mentions a person, a company or a document by name, resolve it with a search first instead of asking the user for an id.
|
||||
- Summarise the result in business terms. Do not paste raw ORM output.</field>
|
||||
<field name="tool_ids" eval="[(6, 0, [
|
||||
ref('ir_actions_server_get_models'),
|
||||
ref('ir_actions_server_get_fields'),
|
||||
ref('ir_actions_server_search'),
|
||||
ref('ir_actions_server_read_group'),
|
||||
ref('ir_actions_server_compute_date'),
|
||||
ref('ir_actions_server_preview_records'),
|
||||
])]"/>
|
||||
</record>
|
||||
|
||||
<!-- ============ Shape View ============ -->
|
||||
<record id="ai_skill_natural_language_query" model="ai.skill">
|
||||
<field name="name">Shape View</field>
|
||||
<field name="sequence">20</field>
|
||||
<field name="is_native_skill" eval="True"/>
|
||||
<field name="description">Navigate the user in the UI and shape the view: open a menu, filter, group, chart, pivot.</field>
|
||||
<field name="instructions">## Shape View
|
||||
|
||||
You can navigate the user in the interface and interact with the current view.
|
||||
Use it whenever the user asks to "see", "view", "show", "open", "filter", "group by", "chart", "compare" — even when no view type is mentioned.
|
||||
|
||||
### Workflow
|
||||
1. Call `get_menus` to find the menu the user means. Pick the most specific match, not the first one.
|
||||
2. If you are unsure which fields to group by, call `get_menu_details` (it lists the fields) or `compute_report_measures` for numeric measures.
|
||||
3. Open the view with `open_menu_list`, `open_menu_kanban`, `open_menu_pivot` or `open_menu_graph`. Pass a domain when the user asked for a subset.
|
||||
4. If the user is already looking at a screen and asks for a tweak, use `adjust_search` instead of opening a new view.
|
||||
|
||||
### Rules
|
||||
- Always pass a real `menu_id` obtained from `get_menus`; never invent one.
|
||||
- Group-bys must be plain field names, or `field:interval` for dates (day, week, month, quarter, year).
|
||||
- Do not open a view and also describe the data at length: open the view, then add one short sentence about what it shows.
|
||||
- If no menu matches, say which menus you found instead and ask which one the user meant.</field>
|
||||
<field name="tool_ids" eval="[(6, 0, [
|
||||
ref('ir_actions_server_get_models'),
|
||||
ref('ir_actions_server_get_menus'),
|
||||
ref('ir_actions_server_get_menu_details'),
|
||||
ref('ir_actions_server_get_fields'),
|
||||
ref('ir_actions_server_compute_date'),
|
||||
ref('ir_actions_server_adjust_search'),
|
||||
ref('ir_actions_server_open_menu_list'),
|
||||
ref('ir_actions_server_open_menu_kanban'),
|
||||
ref('ir_actions_server_open_menu_pivot'),
|
||||
ref('ir_actions_server_open_menu_graph'),
|
||||
ref('ir_actions_server_compute_report_measures'),
|
||||
ref('ir_actions_server_run_view_action'),
|
||||
])]"/>
|
||||
</record>
|
||||
|
||||
<!-- ============ Update Records ============ -->
|
||||
<record id="ai_skill_update_records" model="ai.skill">
|
||||
<field name="name">Update Records</field>
|
||||
<field name="sequence">30</field>
|
||||
<field name="is_native_skill" eval="True"/>
|
||||
<field name="description">Modify field values on existing records.</field>
|
||||
<field name="instructions">## Update Records
|
||||
|
||||
You can update existing records.
|
||||
|
||||
### Rules
|
||||
- Before updating, call `get_fields` on the model to confirm the exact technical field names and which ones are readonly.
|
||||
- Build a precise domain that targets exactly the records the user meant. Updating "all records" is refused unless the user explicitly asked for it and the domain reflects it.
|
||||
- Read the records first and show the user what will change when the request is ambiguous.
|
||||
- Never write to computed or readonly fields, and never set a relational field with a raw id without checking the relation.
|
||||
- The runtime shows a confirmation card before executing. Do not ask for confirmation in chat.
|
||||
- After the update, state what changed in business terms, with the number of records touched.</field>
|
||||
<field name="tool_ids" eval="[(6, 0, [
|
||||
ref('ir_actions_server_get_models'),
|
||||
ref('ir_actions_server_get_fields'),
|
||||
ref('ir_actions_server_search'),
|
||||
ref('ir_actions_server_compute_date'),
|
||||
ref('ir_actions_server_update_records'),
|
||||
])]"/>
|
||||
</record>
|
||||
|
||||
<!-- ============ Create Records ============ -->
|
||||
<record id="ai_skill_create_records" model="ai.skill">
|
||||
<field name="name">Create Records</field>
|
||||
<field name="sequence">40</field>
|
||||
<field name="is_native_skill" eval="True"/>
|
||||
<field name="description">Create new records from the conversation.</field>
|
||||
<field name="instructions">## Create Records
|
||||
|
||||
You can create records.
|
||||
|
||||
### Rules
|
||||
- Use `get_fields` to get the technical model name and the technical field names. Required fields must always be provided.
|
||||
- Gather every mandatory value before creating. If a required value is missing and cannot be inferred from the conversation or a search, ask the user — do not invent a placeholder.
|
||||
- Many2one values must be existing record ids. Resolve a name with `search` first.
|
||||
- Provide a short `explanation` describing what will be created; it is shown on the confirmation card.
|
||||
- Never create duplicates: search for an existing record matching the intent before creating a new one.
|
||||
- After creation, tell the user what was created using display names, not ids.</field>
|
||||
<field name="tool_ids" eval="[(6, 0, [
|
||||
ref('ir_actions_server_get_models'),
|
||||
ref('ir_actions_server_get_fields'),
|
||||
ref('ir_actions_server_search'),
|
||||
ref('ir_actions_server_compute_date'),
|
||||
ref('ir_actions_server_create_records'),
|
||||
])]"/>
|
||||
</record>
|
||||
</odoo>
|
||||
487
dn_ai/data/ir_actions_server_data.xml
Normal file
487
dn_ai/data/ir_actions_server_data.xml
Normal file
@@ -0,0 +1,487 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<odoo>
|
||||
<!--
|
||||
Every tool is a `code` server action exposing an ai.tool method.
|
||||
The JSON schema drives argument validation and is what the model sees.
|
||||
-->
|
||||
|
||||
<!-- ================= read: models & schema ================= -->
|
||||
<record id="ir_actions_server_get_models" model="ir.actions.server">
|
||||
<field name="name">AI Tool: Get Models</field>
|
||||
<field name="model_id" ref="model_ai_tool"/>
|
||||
<field name="state">code</field>
|
||||
<field name="use_in_ai" eval="True"/>
|
||||
<field name="ai_tool_name">get_models</field>
|
||||
<field name="ai_tool_thinking_text">Looking up available models</field>
|
||||
<field name="ai_tool_description">List every database model the current user is allowed to read. Call this first when you do not know the technical name of a model.</field>
|
||||
<field name="ai_tool_schema">{
|
||||
"type": "object",
|
||||
"properties": {},
|
||||
"required": []
|
||||
}</field>
|
||||
<field name="code">ai["result"] = record._ai_tool_get_models()</field>
|
||||
</record>
|
||||
|
||||
<record id="ir_actions_server_get_fields" model="ir.actions.server">
|
||||
<field name="name">AI Tool: Get Fields</field>
|
||||
<field name="model_id" ref="model_ai_tool"/>
|
||||
<field name="state">code</field>
|
||||
<field name="use_in_ai" eval="True"/>
|
||||
<field name="ai_tool_name">get_fields</field>
|
||||
<field name="ai_tool_thinking_text">Inspecting the fields of the model</field>
|
||||
<field name="ai_tool_description">Return the technical fields of a model: name, type, label, relations, selection values. Always call this before searching, grouping or writing on a model you have not inspected yet.</field>
|
||||
<field name="ai_tool_schema">{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"model_name": {"type": "string", "description": "Technical model name, e.g. res.partner"},
|
||||
"include_description": {"type": "boolean", "description": "Include the help text of each field"}
|
||||
},
|
||||
"required": ["model_name"]
|
||||
}</field>
|
||||
<field name="code">ai["result"] = record._ai_tool_get_fields(model_name, include_description)</field>
|
||||
</record>
|
||||
|
||||
<!-- ================= menus ================= -->
|
||||
<record id="ir_actions_server_get_menus" model="ir.actions.server">
|
||||
<field name="name">AI Tool: Get Menus</field>
|
||||
<field name="model_id" ref="model_ai_tool"/>
|
||||
<field name="state">code</field>
|
||||
<field name="use_in_ai" eval="True"/>
|
||||
<field name="ai_tool_name">get_menus</field>
|
||||
<field name="ai_tool_thinking_text">Reading the menu tree</field>
|
||||
<field name="ai_tool_description">List the menus the current user can open, with their action, model and available view types. Use it to navigate the user to the right screen.</field>
|
||||
<field name="ai_tool_schema">{
|
||||
"type": "object",
|
||||
"properties": {},
|
||||
"required": []
|
||||
}</field>
|
||||
<field name="code">ai["result"] = record._ai_tool_get_menus()</field>
|
||||
</record>
|
||||
|
||||
<record id="ir_actions_server_get_menu_details" model="ir.actions.server">
|
||||
<field name="name">AI Tool: Get Menu Details</field>
|
||||
<field name="model_id" ref="model_ai_tool"/>
|
||||
<field name="state">code</field>
|
||||
<field name="use_in_ai" eval="True"/>
|
||||
<field name="ai_tool_name">get_menu_details</field>
|
||||
<field name="ai_tool_thinking_text">Inspecting the selected menus</field>
|
||||
<field name="ai_tool_description">Return the action, model and fields behind one or more menus.</field>
|
||||
<field name="ai_tool_schema">{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"menu_ids": {"type": "array", "items": {"type": "integer"}, "description": "Menu ids returned by get_menus"},
|
||||
"include_model_fields": {"type": "boolean", "description": "Also list the fields of the target model"}
|
||||
},
|
||||
"required": ["menu_ids"]
|
||||
}</field>
|
||||
<field name="code">ai["result"] = record._ai_tool_get_menu_details(menu_ids, include_model_fields)</field>
|
||||
</record>
|
||||
|
||||
<!-- ================= data ================= -->
|
||||
<record id="ir_actions_server_search" model="ir.actions.server">
|
||||
<field name="name">AI Tool: Search</field>
|
||||
<field name="model_id" ref="model_ai_tool"/>
|
||||
<field name="state">code</field>
|
||||
<field name="use_in_ai" eval="True"/>
|
||||
<field name="ai_tool_name">search</field>
|
||||
<field name="ai_tool_thinking_text">Searching records</field>
|
||||
<field name="ai_tool_description">Search and read records of a model. Provide an Odoo domain as JSON (e.g. [["name","ilike","Acme"]]) and the exact field names to read.</field>
|
||||
<field name="ai_tool_schema">{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"model_name": {"type": "string"},
|
||||
"domain": {"type": "string", "description": "Odoo domain as a JSON string. Use [] for all records."},
|
||||
"fields": {"type": "array", "items": {"type": "string"}, "description": "Field names to read"},
|
||||
"offset": {"type": "integer"},
|
||||
"limit": {"type": "integer", "description": "Max 200, default 40"},
|
||||
"order": {"type": "string", "description": "e.g. create_date desc"}
|
||||
},
|
||||
"required": ["model_name", "fields"]
|
||||
}</field>
|
||||
<field name="code">ai["result"] = record._ai_tool_search(model_name, domain, fields, offset, limit, order)</field>
|
||||
</record>
|
||||
|
||||
<record id="ir_actions_server_read_group" model="ir.actions.server">
|
||||
<field name="name">AI Tool: Read Group</field>
|
||||
<field name="model_id" ref="model_ai_tool"/>
|
||||
<field name="state">code</field>
|
||||
<field name="use_in_ai" eval="True"/>
|
||||
<field name="ai_tool_name">read_group</field>
|
||||
<field name="ai_tool_thinking_text">Aggregating records</field>
|
||||
<field name="ai_tool_description">Group records and compute aggregates. Use it for counts, sums and averages instead of reading every record.</field>
|
||||
<field name="ai_tool_schema">{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"model_name": {"type": "string"},
|
||||
"domain": {"type": "string", "description": "Odoo domain as JSON"},
|
||||
"groupby": {"type": "array", "items": {"type": "string"}, "description": "e.g. [\"partner_id\", \"create_date:month\"]"},
|
||||
"aggregates": {"type": "array", "items": {"type": "string"}, "description": "e.g. [\"__count\", \"amount_total:sum\"]"}
|
||||
},
|
||||
"required": ["model_name", "domain", "groupby"]
|
||||
}</field>
|
||||
<field name="code">ai["result"] = record._ai_tool_read_group(model_name, domain, groupby, aggregates)</field>
|
||||
</record>
|
||||
|
||||
<record id="ir_actions_server_compute_date" model="ir.actions.server">
|
||||
<field name="name">AI Tool: Compute Date</field>
|
||||
<field name="model_id" ref="model_ai_tool"/>
|
||||
<field name="state">code</field>
|
||||
<field name="use_in_ai" eval="True"/>
|
||||
<field name="ai_tool_name">compute_date</field>
|
||||
<field name="ai_tool_thinking_text">Computing the date</field>
|
||||
<field name="ai_tool_description">Turn a relative expression ("next Monday", "start of last quarter") into an absolute date or datetime in the user's timezone. Use it whenever a domain filters on a date, because "today" on the server is UTC.</field>
|
||||
<field name="ai_tool_schema">{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"model_name": {"type": "string", "description": "Model owning the date field"},
|
||||
"field_name": {"type": "string", "description": "Date or datetime field name"},
|
||||
"operations": {
|
||||
"type": "array",
|
||||
"description": "Ordered operations. navigate moves by a period, find_next/find_previous jump to a weekday (0=Monday).",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"type": {"type": "string", "enum": ["navigate", "find_next", "find_previous"]},
|
||||
"period": {"type": "string", "enum": ["minute", "hour", "day", "week", "month", "quarter", "year"]},
|
||||
"offset": {"type": "integer", "description": "-100 to 100"},
|
||||
"boundary": {"type": "string", "enum": ["start", "end"]},
|
||||
"weekday": {"type": "integer", "description": "0=Monday … 6=Sunday"}
|
||||
}
|
||||
}
|
||||
},
|
||||
"pin": {
|
||||
"type": "object",
|
||||
"description": "Final anchoring: day (1-31 or {weekday, occurrence}) and time (HH:MM)",
|
||||
"properties": {
|
||||
"day": {},
|
||||
"time": {"type": "string"}
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": ["model_name", "field_name"]
|
||||
}</field>
|
||||
<field name="code">ai["result"] = record._ai_tool_compute_date(model_name, field_name, operations, pin)</field>
|
||||
</record>
|
||||
|
||||
<!-- ================= navigation ================= -->
|
||||
<record id="ir_actions_server_open_menu_list" model="ir.actions.server">
|
||||
<field name="name">AI Tool: Open Menu List</field>
|
||||
<field name="model_id" ref="model_ai_tool"/>
|
||||
<field name="state">code</field>
|
||||
<field name="use_in_ai" eval="True"/>
|
||||
<field name="ai_tool_name">open_menu_list</field>
|
||||
<field name="ai_tool_thinking_text">Opening the list view</field>
|
||||
<field name="ai_tool_description">Open the list view of a menu in the user's browser, optionally filtered by a domain.</field>
|
||||
<field name="ai_tool_schema">{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"menu_id": {"type": "integer"},
|
||||
"model_name": {"type": "string"},
|
||||
"custom_domain": {"type": "string", "description": "Extra domain as JSON"},
|
||||
"selected_filters": {"type": "array", "items": {"type": "string"}, "description": "Search filter xml ids to activate"},
|
||||
"selected_groupbys": {"type": "array", "items": {"type": "string"}, "description": "Group by fields"},
|
||||
"search": {"type": "string", "description": "Free text search term"}
|
||||
},
|
||||
"required": ["menu_id", "model_name"]
|
||||
}</field>
|
||||
<field name="code">ai["result"] = record._ai_tool_open_menu_list(menu_id, model_name, selected_filters, selected_groupbys, search, custom_domain)</field>
|
||||
</record>
|
||||
|
||||
<record id="ir_actions_server_open_menu_kanban" model="ir.actions.server">
|
||||
<field name="name">AI Tool: Open Menu Kanban</field>
|
||||
<field name="model_id" ref="model_ai_tool"/>
|
||||
<field name="state">code</field>
|
||||
<field name="use_in_ai" eval="True"/>
|
||||
<field name="ai_tool_name">open_menu_kanban</field>
|
||||
<field name="ai_tool_thinking_text">Opening the kanban view</field>
|
||||
<field name="ai_tool_description">Open the kanban view of a menu in the user's browser.</field>
|
||||
<field name="ai_tool_schema">{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"menu_id": {"type": "integer"},
|
||||
"model_name": {"type": "string"},
|
||||
"custom_domain": {"type": "string"},
|
||||
"selected_filters": {"type": "array", "items": {"type": "string"}},
|
||||
"selected_groupbys": {"type": "array", "items": {"type": "string"}},
|
||||
"search": {"type": "string"}
|
||||
},
|
||||
"required": ["menu_id", "model_name"]
|
||||
}</field>
|
||||
<field name="code">ai["result"] = record._ai_tool_open_menu_kanban(menu_id, model_name, selected_filters, selected_groupbys, search, custom_domain)</field>
|
||||
</record>
|
||||
|
||||
<record id="ir_actions_server_open_menu_pivot" model="ir.actions.server">
|
||||
<field name="name">AI Tool: Open Menu Pivot</field>
|
||||
<field name="model_id" ref="model_ai_tool"/>
|
||||
<field name="state">code</field>
|
||||
<field name="use_in_ai" eval="True"/>
|
||||
<field name="ai_tool_name">open_menu_pivot</field>
|
||||
<field name="ai_tool_thinking_text">Building the pivot view</field>
|
||||
<field name="ai_tool_description">Open a pivot view for a menu with the given rows, columns and measures.</field>
|
||||
<field name="ai_tool_schema">{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"menu_id": {"type": "integer"},
|
||||
"model_name": {"type": "string"},
|
||||
"row_groupbys": {"type": "array", "items": {"type": "string"}},
|
||||
"col_groupbys": {"type": "array", "items": {"type": "string"}},
|
||||
"measures": {"type": "array", "items": {"type": "string"}},
|
||||
"selected_filters": {"type": "array", "items": {"type": "string"}},
|
||||
"selected_groupbys": {"type": "array", "items": {"type": "string"}},
|
||||
"search": {"type": "string"},
|
||||
"custom_domain": {"type": "string"}
|
||||
},
|
||||
"required": ["menu_id", "model_name"]
|
||||
}</field>
|
||||
<field name="code">ai["result"] = record._ai_tool_open_menu_pivot(menu_id, model_name, selected_filters, selected_groupbys, row_groupbys, col_groupbys, measures, search, custom_domain)</field>
|
||||
</record>
|
||||
|
||||
<record id="ir_actions_server_open_menu_graph" model="ir.actions.server">
|
||||
<field name="name">AI Tool: Open Menu Graph</field>
|
||||
<field name="model_id" ref="model_ai_tool"/>
|
||||
<field name="state">code</field>
|
||||
<field name="use_in_ai" eval="True"/>
|
||||
<field name="ai_tool_name">open_menu_graph</field>
|
||||
<field name="ai_tool_thinking_text">Drawing the chart</field>
|
||||
<field name="ai_tool_description">Open a graph view for a menu. Choose the chart type, the group by and the measures.</field>
|
||||
<field name="ai_tool_schema">{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"menu_id": {"type": "integer"},
|
||||
"model_name": {"type": "string"},
|
||||
"row_groupbys": {"type": "array", "items": {"type": "string"}},
|
||||
"measures": {"type": "array", "items": {"type": "string"}},
|
||||
"chart_type": {"type": "string", "enum": ["bar", "line", "pie"]},
|
||||
"selected_filters": {"type": "array", "items": {"type": "string"}},
|
||||
"selected_groupbys": {"type": "array", "items": {"type": "string"}},
|
||||
"search": {"type": "string"},
|
||||
"custom_domain": {"type": "string"}
|
||||
},
|
||||
"required": ["menu_id", "model_name"]
|
||||
}</field>
|
||||
<field name="code">ai["result"] = record._ai_tool_open_menu_graph(menu_id, model_name, selected_filters, selected_groupbys, row_groupbys, measures, chart_type, search, custom_domain)</field>
|
||||
</record>
|
||||
|
||||
<record id="ir_actions_server_adjust_search" model="ir.actions.server">
|
||||
<field name="name">AI Tool: Adjust Search</field>
|
||||
<field name="model_id" ref="model_ai_tool"/>
|
||||
<field name="state">code</field>
|
||||
<field name="use_in_ai" eval="True"/>
|
||||
<field name="ai_tool_name">adjust_search</field>
|
||||
<field name="ai_tool_thinking_text">Refining the current view</field>
|
||||
<field name="ai_tool_description">Modify the view the user is currently looking at: add or remove filters, change group by, switch view type.</field>
|
||||
<field name="ai_tool_schema">{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"model_name": {"type": "string"},
|
||||
"remove_facets": {"type": "array", "items": {"type": "integer"}, "description": "Search item group ids to deactivate"},
|
||||
"toggle_filters": {"type": "array", "items": {"type": "string"}, "description": "Filter names or xml ids to toggle"},
|
||||
"toggle_groupbys": {"type": "array", "items": {"type": "string"}, "description": "Group by field names to toggle"},
|
||||
"apply_searches": {
|
||||
"type": "array",
|
||||
"description": "Simulates typing into the search bar, e.g. [{\"search_field\": \"name\", \"value\": \"SO001\"}]",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"search_field": {"type": "string"},
|
||||
"value": {"type": "string"}
|
||||
},
|
||||
"required": ["search_field", "value"]
|
||||
}
|
||||
},
|
||||
"measures": {"type": "array", "items": {"type": "string"}},
|
||||
"mode": {"type": "string", "enum": ["reset", "add", "remove"], "description": "Pivot/graph display mode"},
|
||||
"order": {"type": "string", "enum": ["ASC", "DESC"]},
|
||||
"stacked": {"type": "boolean", "description": "Graph only: stack the bars"},
|
||||
"cumulated": {"type": "boolean", "description": "Graph only, line mode: cumulative values"},
|
||||
"custom_domain": {"type": "string", "description": "Extra domain as JSON"},
|
||||
"switch_view_type": {"type": "string", "enum": ["list", "kanban", "pivot", "graph"]}
|
||||
},
|
||||
"required": ["model_name"]
|
||||
}</field>
|
||||
<field name="code">ai["result"] = record._ai_tool_adjust_search(model_name, remove_facets, toggle_filters, toggle_groupbys, apply_searches, measures, mode, order, stacked, cumulated, custom_domain, switch_view_type)</field>
|
||||
</record>
|
||||
|
||||
<record id="ir_actions_server_compute_report_measures" model="ir.actions.server">
|
||||
<field name="name">AI Tool: Compute Report Measures</field>
|
||||
<field name="model_id" ref="model_ai_tool"/>
|
||||
<field name="state">code</field>
|
||||
<field name="use_in_ai" eval="True"/>
|
||||
<field name="ai_tool_name">compute_report_measures</field>
|
||||
<field name="ai_tool_thinking_text">Listing the available measures</field>
|
||||
<field name="ai_tool_description">List the numeric fields that can be used as measures in a pivot or graph view.</field>
|
||||
<field name="ai_tool_schema">{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"action_id": {"type": "integer"},
|
||||
"model": {"type": "string"}
|
||||
},
|
||||
"required": ["model"]
|
||||
}</field>
|
||||
<field name="code">ai["result"] = record._ai_tool_compute_report_measures(action_id, model)</field>
|
||||
</record>
|
||||
|
||||
<record id="ir_actions_server_run_view_action" model="ir.actions.server">
|
||||
<field name="name">AI Tool: Run View Action</field>
|
||||
<field name="model_id" ref="model_ai_tool"/>
|
||||
<field name="state">code</field>
|
||||
<field name="use_in_ai" eval="True"/>
|
||||
<field name="ai_tool_name">run_view_action</field>
|
||||
<field name="ai_tool_thinking_text">Opening the view</field>
|
||||
<field name="ai_tool_description">Open a menu using its default action and view type.</field>
|
||||
<field name="ai_tool_schema">{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"menu_id": {"type": "integer"},
|
||||
"action_type": {"type": "string", "enum": ["list", "kanban", "form", "pivot", "graph"]}
|
||||
},
|
||||
"required": ["menu_id", "action_type"]
|
||||
}</field>
|
||||
<field name="code">ai["result"] = record._ai_tool_run_view_action(menu_id, action_type)</field>
|
||||
</record>
|
||||
|
||||
<!-- ================= previews & writes ================= -->
|
||||
<record id="ir_actions_server_preview_records" model="ir.actions.server">
|
||||
<field name="name">AI Tool: Prepare Record Previews</field>
|
||||
<field name="model_id" ref="model_ai_tool"/>
|
||||
<field name="state">code</field>
|
||||
<field name="use_in_ai" eval="True"/>
|
||||
<field name="ai_tool_name">prepare_record_previews</field>
|
||||
<field name="ai_tool_thinking_text">Preparing the preview</field>
|
||||
<field name="ai_tool_description">Prepare clickable previews of records so the user can open them from the chat.</field>
|
||||
<field name="ai_tool_schema">{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"model_name": {"type": "string"},
|
||||
"record_ids": {"type": "array", "items": {"type": "integer"}},
|
||||
"preview_label": {"type": "string"}
|
||||
},
|
||||
"required": ["model_name", "record_ids"]
|
||||
}</field>
|
||||
<field name="code">ai["result"] = record._ai_tool_prepare_record_previews(model_name, record_ids, preview_label)</field>
|
||||
</record>
|
||||
|
||||
<record id="ir_actions_server_read_binary_content" model="ir.actions.server">
|
||||
<field name="name">AI Tool: Read Binary Content</field>
|
||||
<field name="model_id" ref="model_ai_tool"/>
|
||||
<field name="state">code</field>
|
||||
<field name="use_in_ai" eval="True"/>
|
||||
<field name="ai_tool_name">read_binary_content</field>
|
||||
<field name="ai_tool_thinking_text">Reading the attached file</field>
|
||||
<field name="ai_tool_description">Read the text content of a binary field (PDF, image, attachment) linked to a record.</field>
|
||||
<field name="ai_tool_schema">{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"model_name": {"type": "string"},
|
||||
"record_ids": {"type": "array", "items": {"type": "integer"}},
|
||||
"field_name": {"type": "string"}
|
||||
},
|
||||
"required": ["model_name", "record_ids"]
|
||||
}</field>
|
||||
<field name="code">ai["result"] = record._ai_tool_read_binary_content(model_name, record_ids, field_name)</field>
|
||||
</record>
|
||||
|
||||
<record id="ir_actions_server_create_records" model="ir.actions.server">
|
||||
<field name="name">AI Tool: Create Records</field>
|
||||
<field name="model_id" ref="model_ai_tool"/>
|
||||
<field name="state">code</field>
|
||||
<field name="use_in_ai" eval="True"/>
|
||||
<field name="ai_tool_name">create_records</field>
|
||||
<field name="ai_tool_thinking_text">Creating the record</field>
|
||||
<field name="ai_tool_requires_confirmation" eval="True"/>
|
||||
<field name="ai_tool_description">Create one or more records. The user is asked to confirm before anything is written.</field>
|
||||
<field name="ai_tool_schema">{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"explanation": {"type": "string", "description": "One sentence shown to the user explaining what will be created"},
|
||||
"preview_menu_id": {"type": "integer"},
|
||||
"model_name": {"type": "string"},
|
||||
"values": {"type": "object", "description": "Field values, using exact technical field names"}
|
||||
},
|
||||
"required": ["explanation", "model_name", "values"]
|
||||
}</field>
|
||||
<field name="code">ai["result"] = record._ai_tool_create_records(ai, explanation, preview_menu_id, model_name, values)</field>
|
||||
</record>
|
||||
|
||||
<record id="ir_actions_server_update_records" model="ir.actions.server">
|
||||
<field name="name">AI Tool: Update Records</field>
|
||||
<field name="model_id" ref="model_ai_tool"/>
|
||||
<field name="state">code</field>
|
||||
<field name="use_in_ai" eval="True"/>
|
||||
<field name="ai_tool_name">update_records</field>
|
||||
<field name="ai_tool_thinking_text">Updating the records</field>
|
||||
<field name="ai_tool_requires_confirmation" eval="True"/>
|
||||
<field name="ai_tool_description">Update fields on existing records. Always pass a precise domain; updating every record is refused. The user confirms first.</field>
|
||||
<field name="ai_tool_schema">{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"explanation": {"type": "string"},
|
||||
"preview_menus": {"type": "array", "items": {"type": "integer"}},
|
||||
"updates": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"model_name": {"type": "string"},
|
||||
"domain": {"type": "string"},
|
||||
"changes": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"field": {"type": "string"},
|
||||
"value": {}
|
||||
},
|
||||
"required": ["field", "value"]
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": ["model_name", "domain", "changes"]
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": ["explanation", "updates"]
|
||||
}</field>
|
||||
<field name="code">ai["result"] = record._ai_tool_update_records(ai, explanation, preview_menus, updates)</field>
|
||||
</record>
|
||||
|
||||
<!-- ================= interaction & skills ================= -->
|
||||
<record id="ir_actions_server_ask_user_question" model="ir.actions.server">
|
||||
<field name="name">AI Tool: Ask User Question</field>
|
||||
<field name="model_id" ref="model_ai_tool"/>
|
||||
<field name="state">code</field>
|
||||
<field name="use_in_ai" eval="True"/>
|
||||
<field name="ai_tool_name">ask_user_question</field>
|
||||
<field name="ai_tool_thinking_text">Asking you a question</field>
|
||||
<field name="ai_tool_description">Ask the user a question and wait. Use it only when the answer cannot be resolved by searching the database.</field>
|
||||
<field name="ai_tool_schema">{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"question": {"type": "string"},
|
||||
"choices": {"type": "array", "items": {"type": "string"}},
|
||||
"multi_select": {"type": "boolean"},
|
||||
"allow_free_text": {"type": "boolean"}
|
||||
},
|
||||
"required": ["question"]
|
||||
}</field>
|
||||
<field name="code">ai["result"] = record._ai_tool_ask_user_question(ai, question, choices, multi_select, allow_free_text)</field>
|
||||
</record>
|
||||
|
||||
<record id="ir_actions_server_load_skills" model="ir.actions.server">
|
||||
<field name="name">AI Tool: Load Skills</field>
|
||||
<field name="model_id" ref="model_ai_tool"/>
|
||||
<field name="state">code</field>
|
||||
<field name="use_in_ai" eval="True"/>
|
||||
<field name="ai_tool_name">load_skills</field>
|
||||
<field name="ai_tool_thinking_text">Loading the relevant skill</field>
|
||||
<field name="ai_tool_description">Load one or more skills by id. Their instructions are returned and their tools become available. Call it at most once per request.</field>
|
||||
<field name="ai_tool_schema">{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"skill_ids": {"type": "array", "items": {"type": "integer"}}
|
||||
},
|
||||
"required": ["skill_ids"]
|
||||
}</field>
|
||||
<field name="code">ai["result"] = record._ai_tool_load_skills(ai, skill_ids)</field>
|
||||
</record>
|
||||
</odoo>
|
||||
14
dn_ai/data/ir_cron.xml
Normal file
14
dn_ai/data/ir_cron.xml
Normal file
@@ -0,0 +1,14 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<odoo>
|
||||
<!-- Housekeeping: drop AI conversations nobody touched for 30 days. -->
|
||||
<record id="ir_cron_ai_vacuum" model="ir.cron">
|
||||
<field name="name">DN AI: vacuum idle AI conversations</field>
|
||||
<field name="model_id" ref="model_discuss_channel"/>
|
||||
<field name="state">code</field>
|
||||
<field name="code">model._remove_ai_chat_channels()</field>
|
||||
<field name="user_id" ref="base.user_root"/>
|
||||
<field name="interval_number">1</field>
|
||||
<field name="interval_type">days</field>
|
||||
<field name="priority">9</field>
|
||||
</record>
|
||||
</odoo>
|
||||
2294
dn_ai/i18n/zh_CN.po
Normal file
2294
dn_ai/i18n/zh_CN.po
Normal file
File diff suppressed because it is too large
Load Diff
12
dn_ai/models/__init__.py
Normal file
12
dn_ai/models/__init__.py
Normal file
@@ -0,0 +1,12 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from . import ai_provider
|
||||
from . import ai_agent
|
||||
from . import ai_skill
|
||||
from . import ai_tool
|
||||
from . import ai_session
|
||||
from . import ai_composer
|
||||
from . import ai_prompt_button
|
||||
from . import ir_actions_server
|
||||
from . import discuss_channel
|
||||
from . import ir_attachment
|
||||
from . import res_config_settings
|
||||
224
dn_ai/models/ai_agent.py
Normal file
224
dn_ai/models/ai_agent.py
Normal file
@@ -0,0 +1,224 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import logging
|
||||
|
||||
from odoo import api, fields, models
|
||||
from odoo.exceptions import AccessError, UserError
|
||||
|
||||
from ..utils.agent_instructions_prompts import (
|
||||
DEFAULT_SYSTEM_PROMPT,
|
||||
SKILLS_PROTOCOL,
|
||||
get_global_protocol,
|
||||
)
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class AIAgent(models.Model):
|
||||
_name = 'ai.agent'
|
||||
_description = "AI Agent"
|
||||
_order = 'sequence, name'
|
||||
_inherit = ['mail.thread']
|
||||
|
||||
active = fields.Boolean(default=True)
|
||||
sequence = fields.Integer(
|
||||
default=10,
|
||||
help="Built-in agents ship with a sequence below 10 to be listed first.",
|
||||
)
|
||||
name = fields.Char(string="Agent Name", required=True)
|
||||
subtitle = fields.Char(string="Description")
|
||||
system_prompt = fields.Text(
|
||||
string="System Prompt",
|
||||
help="Customize to control relevance and formatting.",
|
||||
)
|
||||
image_128 = fields.Image("Image", max_width=128, max_height=128)
|
||||
partner_id = fields.Many2one(
|
||||
'res.partner', required=True, ondelete='cascade', index=True,
|
||||
help="Identity used by the agent when it posts messages in Discuss.",
|
||||
)
|
||||
is_system_agent = fields.Boolean('System Agent', default=False)
|
||||
skill_ids = fields.Many2many(
|
||||
'ai.skill', 'ai_agent_skill_rel', 'agent_id', 'skill_id', string="Skills",
|
||||
)
|
||||
restrict_to_sources = fields.Boolean(
|
||||
"Restrict to Sources",
|
||||
help="When enabled the agent only answers from its knowledge sources.",
|
||||
)
|
||||
embedding_model = fields.Char()
|
||||
allowed_agent_ids = fields.Many2many(
|
||||
'ai.agent', 'ai_agent_delegation_rel', 'parent_id', 'child_id',
|
||||
string="Allowed Agents",
|
||||
help="Agents this agent may delegate work to.",
|
||||
)
|
||||
|
||||
_agent_name_uniq = models.Constraint(
|
||||
'UNIQUE(name)', "An agent with this name already exists.",
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# lifecycle
|
||||
# ------------------------------------------------------------------
|
||||
@api.model_create_multi
|
||||
def create(self, vals_list):
|
||||
for vals in vals_list:
|
||||
if not vals.get('partner_id'):
|
||||
vals['partner_id'] = self.env['res.partner'].create({
|
||||
'name': vals.get('name') or self.env._("AI Assistant"),
|
||||
'is_company': False,
|
||||
}).id
|
||||
return super().create(vals_list)
|
||||
|
||||
def write(self, vals):
|
||||
# Data files legitimately (re)assert is_system_agent / active during an
|
||||
# install or upgrade; only interactive writes are guarded.
|
||||
if not self.env.context.get('install_mode'):
|
||||
for agent in self:
|
||||
if agent.is_system_agent and set(vals) & {'active', 'is_system_agent'}:
|
||||
raise UserError(self.env._("The built-in agent cannot be archived."))
|
||||
if 'name' in vals:
|
||||
self.mapped('partner_id').sudo().write({'name': vals['name']})
|
||||
return super().write(vals)
|
||||
|
||||
def unlink(self):
|
||||
if not self.env.context.get('install_mode'):
|
||||
if any(agent.is_system_agent for agent in self):
|
||||
raise UserError(self.env._("The built-in agent cannot be deleted."))
|
||||
partners = self.mapped('partner_id')
|
||||
result = super().unlink()
|
||||
partners.sudo().unlink()
|
||||
return result
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# instructions
|
||||
# ------------------------------------------------------------------
|
||||
def _get_instructions(self, extra_instructions=None):
|
||||
"""Build the layered system prompt, same sectioning as enterprise."""
|
||||
self.ensure_one()
|
||||
|
||||
def section(name, content):
|
||||
content = (content or '').strip()
|
||||
if not content:
|
||||
return ''
|
||||
return f"<{name}>\n{content}\n</{name}>\n\n"
|
||||
|
||||
instructions = "[[START OF INSTRUCTIONS]]\n\n"
|
||||
instructions += section('global_protocol', get_global_protocol(
|
||||
self.env.context.get('debug'), self.env.tz))
|
||||
instructions += section('agent_protocol', self.system_prompt or DEFAULT_SYSTEM_PROMPT)
|
||||
if extra_instructions:
|
||||
instructions += section('usage_context', extra_instructions)
|
||||
|
||||
skills = self.skill_ids
|
||||
if skills:
|
||||
instructions += section('skills_protocol', SKILLS_PROTOCOL)
|
||||
instructions += section(
|
||||
'available_skills',
|
||||
"\n".join(
|
||||
f'<skill id="{skill.id}" name="{skill.name}" type="{skill.type}">{skill.description or ""}</skill>'
|
||||
for skill in skills
|
||||
),
|
||||
)
|
||||
instructions += "[[END OF INSTRUCTIONS]]"
|
||||
return instructions
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# tools & skills
|
||||
# ------------------------------------------------------------------
|
||||
def _get_default_tools(self):
|
||||
"""Tools always available, regardless of the loaded skills."""
|
||||
self.ensure_one()
|
||||
tools = self.env['ir.actions.server']
|
||||
for xmlid in DEFAULT_TOOL_XMLIDS:
|
||||
if tool := self.env.ref(xmlid, raise_if_not_found=False):
|
||||
tools |= tool
|
||||
return tools
|
||||
|
||||
def _get_available_skills(self):
|
||||
self.ensure_one()
|
||||
return self.skill_ids
|
||||
|
||||
def _get_usage_string(self):
|
||||
self.ensure_one()
|
||||
meta = self.get_metadata()[0] if self.get_metadata() else {}
|
||||
return f"agent:{meta.get('xmlid') or 'custom'}"
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# discuss store
|
||||
# ------------------------------------------------------------------
|
||||
def _store_agent_fields(self, res):
|
||||
"""Fields exposed to the Discuss store for an AI chat's agent.
|
||||
|
||||
Referenced by name from ``discuss.channel._store_channel_fields``
|
||||
(``res.one("ai_agent_id", "_store_agent_fields", ...)``), so it must be
|
||||
defined on this model.
|
||||
"""
|
||||
res.attr("name")
|
||||
res.attr("subtitle")
|
||||
res.attr("image_128", predicate=lambda agent: bool(agent.image_128))
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# chat entry points
|
||||
# ------------------------------------------------------------------
|
||||
def _is_user_access_allowed(self):
|
||||
self.ensure_one()
|
||||
return self.env.user._is_internal()
|
||||
|
||||
def action_launch_ai_chat(self):
|
||||
"""Open (or reuse) the AI chat conversation for this agent."""
|
||||
self.ensure_one()
|
||||
if not self._is_user_access_allowed():
|
||||
raise AccessError(self.env._("You are not allowed to chat with this agent."))
|
||||
channel = self.env['ai.session']._get_or_create_chat_channel(self)
|
||||
return {
|
||||
'type': 'ir.actions.client',
|
||||
'tag': 'dn_ai.chat',
|
||||
'params': {'channel_id': channel.id},
|
||||
'name': self.env._("AI Chat"),
|
||||
}
|
||||
|
||||
@api.model
|
||||
def dn_ai_get_default_channel(self):
|
||||
"""Resolve (creating it on first use) the default agent's chat channel."""
|
||||
# sudo: the built-in agent is a system resource; a plain internal user
|
||||
# may not be allowed to search ai.agent.
|
||||
agent = self.sudo().search([('is_system_agent', '=', True)], limit=1)
|
||||
if not agent:
|
||||
agent = self.sudo().search([], limit=1)
|
||||
if not agent:
|
||||
raise UserError(self.env._(
|
||||
"No AI agent is configured. Create one in the AI application first."
|
||||
))
|
||||
if not agent._is_user_access_allowed():
|
||||
raise AccessError(self.env._("You are not allowed to chat with this agent."))
|
||||
channel = self.env['ai.session']._get_or_create_chat_channel(agent)
|
||||
session = self.env['ai.session'].sudo()._get_channel_session(channel)
|
||||
return {
|
||||
'channel_id': channel.id,
|
||||
'agent_id': agent.id,
|
||||
'agent_name': agent.name,
|
||||
'session_id': session.id if session else False,
|
||||
}
|
||||
|
||||
def _generate_single_response(self, message_parts, extra_instructions=None, schema=None):
|
||||
"""One-shot completion using this agent's configuration."""
|
||||
self.ensure_one()
|
||||
return self.env['ai.session']._get_direct_response(
|
||||
instructions=self._get_instructions(extra_instructions),
|
||||
message=message_parts,
|
||||
tools=self._get_default_tools(),
|
||||
agent_id=self.id,
|
||||
schema=schema,
|
||||
)
|
||||
|
||||
|
||||
DEFAULT_TOOL_XMLIDS = (
|
||||
'dn_ai.ir_actions_server_get_models',
|
||||
'dn_ai.ir_actions_server_get_menus',
|
||||
'dn_ai.ir_actions_server_get_menu_details',
|
||||
'dn_ai.ir_actions_server_get_fields',
|
||||
'dn_ai.ir_actions_server_search',
|
||||
'dn_ai.ir_actions_server_read_group',
|
||||
'dn_ai.ir_actions_server_compute_date',
|
||||
'dn_ai.ir_actions_server_load_skills',
|
||||
'dn_ai.ir_actions_server_ask_user_question',
|
||||
'dn_ai.ir_actions_server_preview_records',
|
||||
)
|
||||
65
dn_ai/models/ai_composer.py
Normal file
65
dn_ai/models/ai_composer.py
Normal file
@@ -0,0 +1,65 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from odoo import api, fields, models
|
||||
|
||||
INTERFACE_KEYS = [
|
||||
('chatter_ai_button', "Chatter AI button"),
|
||||
('systray_ai_button', "Systray AI button"),
|
||||
('html_field_ai', "HTML field assistant"),
|
||||
('email_composer_ai', "Email composer assistant"),
|
||||
('chatter_summarize', "Chatter summarize"),
|
||||
]
|
||||
|
||||
|
||||
class AIComposer(models.Model):
|
||||
_name = 'ai.composer'
|
||||
_description = "AI Composer"
|
||||
_explanation = (
|
||||
"Maps a UI entry point (a button, a field widget) to an agent plus a "
|
||||
"default context prompt."
|
||||
)
|
||||
|
||||
name = fields.Char(required=True, translate=True)
|
||||
active = fields.Boolean(default=True)
|
||||
interface_key = fields.Selection(selection=INTERFACE_KEYS, string="Action", required=True)
|
||||
focused_model_id = fields.Many2one('ir.model', string="Model", ondelete='cascade')
|
||||
ai_agent_id = fields.Many2one('ai.agent', string="Agent", required=True)
|
||||
default_prompt = fields.Text("Context", translate=True)
|
||||
is_system_default = fields.Boolean(
|
||||
'System default', default=False, readonly=True, copy=False)
|
||||
available_prompt_ids = fields.One2many(
|
||||
'ai.prompt.button', 'composer_id', string="Suggested prompts")
|
||||
|
||||
_composer_uniq = models.Constraint(
|
||||
'UNIQUE(interface_key, focused_model_id)',
|
||||
"A composer already exists for this action and model.",
|
||||
)
|
||||
|
||||
@api.model
|
||||
def _get_composer(self, interface_key, res_model=None):
|
||||
"""Find the most specific composer for an entry point."""
|
||||
domain = [('interface_key', '=', interface_key), ('active', '=', True)]
|
||||
if res_model:
|
||||
model = self.env['ir.model']._get(res_model)
|
||||
composer = self.search(domain + [('focused_model_id', '=', model.id)], limit=1)
|
||||
if composer:
|
||||
return composer
|
||||
return self.search(domain + [('focused_model_id', '=', False)], limit=1)
|
||||
|
||||
@api.model
|
||||
def _get_agent(self, res_model=None, interface_key=None):
|
||||
composer = self._get_composer(interface_key or 'chatter_ai_button', res_model)
|
||||
return composer.ai_agent_id or self.env.ref('dn_ai.ai_default_agent', raise_if_not_found=False)
|
||||
|
||||
def _get_initial_context(self, res_model=None, res_id=None):
|
||||
self.ensure_one()
|
||||
parts = []
|
||||
if self.default_prompt:
|
||||
parts.append(self.default_prompt)
|
||||
if res_model and res_id:
|
||||
record = self.env[res_model].browse(res_id).exists()
|
||||
if record:
|
||||
parts.append(self.env['ir.qweb']._render(
|
||||
'dn_ai.ai_record_context',
|
||||
{'record': record},
|
||||
))
|
||||
return '\n'.join(str(part) for part in parts if part)
|
||||
44
dn_ai/models/ai_prompt_button.py
Normal file
44
dn_ai/models/ai_prompt_button.py
Normal file
@@ -0,0 +1,44 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from odoo import api, fields, models
|
||||
|
||||
|
||||
class AIPromptButton(models.Model):
|
||||
_name = "ai.prompt.button"
|
||||
_inherit = ["mail.render.mixin"]
|
||||
_description = "Suggested prompt shown above the chat input"
|
||||
_order = 'sequence, id'
|
||||
|
||||
name = fields.Char(required=True, translate=True)
|
||||
sequence = fields.Integer(default=10)
|
||||
prompt = fields.Html(
|
||||
required=True, translate=True,
|
||||
help="Prompt sent to the agent. QWeb expressions such as "
|
||||
"{{object.name}} are rendered against the record.",
|
||||
)
|
||||
composer_id = fields.Many2one("ai.composer", index='btree_not_null', ondelete='cascade')
|
||||
|
||||
def _compute_render_model(self):
|
||||
for button in self:
|
||||
button.render_model = (button.composer_id.focused_model_id.model
|
||||
or 'res.partner')
|
||||
|
||||
def _render_prompt(self, rendering_record_id=None):
|
||||
"""Return the prompt as an AI message part list."""
|
||||
self.ensure_one()
|
||||
model = self.render_model
|
||||
body = self.prompt or ''
|
||||
if rendering_record_id and model and model in self.env:
|
||||
record = self.env[model].browse(rendering_record_id).exists()
|
||||
if record:
|
||||
body = self.env['ir.qweb']._render(
|
||||
'dn_ai.ai_prompt_button_render',
|
||||
{'button': self, 'record': record},
|
||||
)
|
||||
text = self.env['mail.render.mixin']._render_template(
|
||||
body, model or 'res.partner',
|
||||
[rendering_record_id] if rendering_record_id else [],
|
||||
engine='inline_template',
|
||||
) if rendering_record_id else body
|
||||
if isinstance(text, dict):
|
||||
text = next(iter(text.values()), '')
|
||||
return [{'type': 'text', 'text': str(text)}]
|
||||
128
dn_ai/models/ai_provider.py
Normal file
128
dn_ai/models/ai_provider.py
Normal file
@@ -0,0 +1,128 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Read / write the LLM provider configuration.
|
||||
|
||||
All settings live in ``ir.config_parameter`` so they can be changed without a
|
||||
module upgrade, and so other modules can override them per company later.
|
||||
"""
|
||||
import logging
|
||||
|
||||
from odoo import api, models
|
||||
|
||||
from ..utils.openai_client import PROVIDER_PRESETS
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
PARAM_PROVIDER = 'dn_ai.provider'
|
||||
PARAM_BASE_URL = 'dn_ai.base_url'
|
||||
PARAM_API_KEY = 'dn_ai.api_key'
|
||||
PARAM_MODEL = 'dn_ai.model'
|
||||
PARAM_TEMPERATURE = 'dn_ai.temperature'
|
||||
PARAM_MAX_TOKENS = 'dn_ai.max_tokens'
|
||||
PARAM_EMB_BASE_URL = 'dn_ai.embedding_base_url'
|
||||
PARAM_EMB_API_KEY = 'dn_ai.embedding_api_key'
|
||||
PARAM_EMB_MODEL = 'dn_ai.embedding_model'
|
||||
PARAM_MAX_ROUNDS = 'dn_ai.max_rounds'
|
||||
PARAM_MAX_TOOLS_PER_CALL = 'dn_ai.max_tools_per_call'
|
||||
PARAM_TIMEOUT = 'dn_ai.timeout'
|
||||
PARAM_VISION = 'dn_ai.vision'
|
||||
|
||||
DEFAULT_MAX_ROUNDS = 20
|
||||
DEFAULT_MAX_TOOLS_PER_CALL = 20
|
||||
DEFAULT_TIMEOUT = 120
|
||||
|
||||
|
||||
class DNaiProvider(models.AbstractModel):
|
||||
"""Stateless helper exposing the resolved provider configuration."""
|
||||
_name = 'dn.ai.provider'
|
||||
_description = 'DN AI Provider Configuration'
|
||||
|
||||
@api.model
|
||||
def _params(self):
|
||||
return self.env['ir.config_parameter'].sudo()
|
||||
|
||||
@api.model
|
||||
def get_provider(self):
|
||||
return self._params().get_str(PARAM_PROVIDER) or 'deepseek'
|
||||
|
||||
@api.model
|
||||
def get_preset(self, provider=None):
|
||||
provider = provider or self.get_provider()
|
||||
return PROVIDER_PRESETS.get(provider) or PROVIDER_PRESETS['custom']
|
||||
|
||||
@api.model
|
||||
def get_config(self):
|
||||
"""Resolved chat configuration for the current company."""
|
||||
params = self._params()
|
||||
preset = self.get_preset()
|
||||
base_url = params.get_str(PARAM_BASE_URL) or preset['base_url']
|
||||
model = params.get_str(PARAM_MODEL) or preset['model']
|
||||
# `res.config.settings` stores 0 for a cleared float/integer field, so
|
||||
# treat 0 as "not set" rather than "temperature 0".
|
||||
temperature = params.get_float(PARAM_TEMPERATURE, 0.0) or None
|
||||
max_tokens = params.get_int(PARAM_MAX_TOKENS, 0) or None
|
||||
timeout = params.get_int(PARAM_TIMEOUT, 0) or DEFAULT_TIMEOUT
|
||||
return {
|
||||
'provider': self.get_provider(),
|
||||
'base_url': base_url,
|
||||
'api_key': params.get_str(PARAM_API_KEY),
|
||||
'model': model,
|
||||
'temperature': temperature,
|
||||
'max_tokens': max_tokens,
|
||||
'timeout': timeout,
|
||||
'vision': self.get_vision(),
|
||||
'file_api': bool(preset.get('file_api')),
|
||||
}
|
||||
|
||||
@api.model
|
||||
def get_vision(self):
|
||||
"""Whether uploaded images/PDFs may be sent as multimodal content.
|
||||
|
||||
Tri-state on purpose: an unset parameter falls back to the provider
|
||||
preset, so switching to a text-only provider (DeepSeek, a custom
|
||||
endpoint) stops sending image blocks that would be rejected with an
|
||||
HTTP 400 — while still letting the admin override it per installation.
|
||||
"""
|
||||
raw = self._params().get_str(PARAM_VISION)
|
||||
if raw in ('true', 'false'):
|
||||
return raw == 'true'
|
||||
return bool(self.get_preset().get('vision'))
|
||||
|
||||
@api.model
|
||||
def get_embedding_config(self):
|
||||
params = self._params()
|
||||
preset = self.get_preset()
|
||||
chat = self.get_config()
|
||||
return {
|
||||
'base_url': params.get_str(PARAM_EMB_BASE_URL) or chat['base_url'],
|
||||
'api_key': params.get_str(PARAM_EMB_API_KEY) or chat['api_key'],
|
||||
'embedding_model': params.get_str(PARAM_EMB_MODEL) or preset['embedding_model'],
|
||||
}
|
||||
|
||||
@api.model
|
||||
def is_configured(self):
|
||||
cfg = self.get_config()
|
||||
return bool(cfg['base_url'] and cfg['model'] and cfg['api_key'])
|
||||
|
||||
@api.model
|
||||
def get_max_rounds(self):
|
||||
return self._params().get_int(PARAM_MAX_ROUNDS) or DEFAULT_MAX_ROUNDS
|
||||
|
||||
@api.model
|
||||
def get_max_tools_per_call(self):
|
||||
return self._params().get_int(PARAM_MAX_TOOLS_PER_CALL) or DEFAULT_MAX_TOOLS_PER_CALL
|
||||
|
||||
@api.model
|
||||
def action_test_connection(self):
|
||||
"""Called from the settings page; returns a notification action."""
|
||||
from ..utils.openai_client import probe
|
||||
ok, message = probe(self.get_config())
|
||||
return {
|
||||
'type': 'ir.actions.client',
|
||||
'tag': 'display_notification',
|
||||
'params': {
|
||||
'title': self.env._("Connection successful") if ok else self.env._("Connection failed"),
|
||||
'message': message,
|
||||
'type': 'success' if ok else 'danger',
|
||||
'sticky': not ok,
|
||||
},
|
||||
}
|
||||
1040
dn_ai/models/ai_session.py
Normal file
1040
dn_ai/models/ai_session.py
Normal file
File diff suppressed because it is too large
Load Diff
71
dn_ai/models/ai_skill.py
Normal file
71
dn_ai/models/ai_skill.py
Normal file
@@ -0,0 +1,71 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from odoo import api, fields, models
|
||||
from odoo.exceptions import UserError
|
||||
|
||||
|
||||
class AISkill(models.Model):
|
||||
_name = 'ai.skill'
|
||||
_description = "AI Skill"
|
||||
_explanation = (
|
||||
"A skill bundles instructions and tools so the assistant can handle a "
|
||||
"specific kind of task."
|
||||
)
|
||||
_order = 'sequence, name'
|
||||
|
||||
name = fields.Char(string="Title", required=True, translate=True)
|
||||
sequence = fields.Integer(default=10)
|
||||
description = fields.Text(
|
||||
string="Description", translate=True,
|
||||
help="Shown to the model to decide whether this skill is relevant.",
|
||||
)
|
||||
instructions = fields.Text(
|
||||
string="Instructions", translate=True,
|
||||
help="Injected in full once the skill is loaded.",
|
||||
)
|
||||
tool_ids = fields.Many2many(
|
||||
'ir.actions.server', 'ai_skill_tool_rel', 'skill_id', 'tool_id',
|
||||
string="AI Tools",
|
||||
domain="[('use_in_ai', '=', True)]",
|
||||
groups='base.group_system',
|
||||
)
|
||||
type = fields.Char(string="Type", compute="_compute_type")
|
||||
is_native_skill = fields.Boolean(
|
||||
default=False, readonly=True, copy=False,
|
||||
help="Built-in skill with fixed behavior that cannot be edited.",
|
||||
)
|
||||
|
||||
_skill_name_uniq = models.Constraint(
|
||||
'UNIQUE(name)', "A skill with this title already exists.",
|
||||
)
|
||||
|
||||
@api.depends('tool_ids')
|
||||
def _compute_type(self):
|
||||
for skill in self:
|
||||
skill.type = 'executable' if skill.tool_ids else 'guidance'
|
||||
|
||||
@api.model_create_multi
|
||||
def create(self, vals_list):
|
||||
return super().create(vals_list)
|
||||
|
||||
def _is_install_mode(self):
|
||||
"""Data files are allowed to (re)write built-in skills when installing
|
||||
or upgrading the module; the UI is not."""
|
||||
return bool(self.env.context.get('install_mode'))
|
||||
|
||||
def write(self, vals):
|
||||
if (not self._is_install_mode()
|
||||
and set(vals) & {'name', 'instructions', 'tool_ids'}
|
||||
and any(skill.is_native_skill for skill in self)):
|
||||
raise UserError(self.env._(
|
||||
"Built-in skills cannot be modified. Duplicate the skill to customize it."
|
||||
))
|
||||
return super().write(vals)
|
||||
|
||||
def unlink(self):
|
||||
if not self._is_install_mode() and any(skill.is_native_skill for skill in self):
|
||||
raise UserError(self.env._("Built-in skills cannot be deleted."))
|
||||
return super().unlink()
|
||||
|
||||
def _get_instructions(self):
|
||||
self.ensure_one()
|
||||
return (self.instructions or '').strip()
|
||||
712
dn_ai/models/ai_tool.py
Normal file
712
dn_ai/models/ai_tool.py
Normal file
@@ -0,0 +1,712 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import json
|
||||
import logging
|
||||
|
||||
from odoo import api, fields, models
|
||||
from odoo.exceptions import AccessError, UserError
|
||||
from odoo.tools import OrderedSet
|
||||
|
||||
from ..utils.ai_utils import coerce_domain, compute_date, get_text_from_parts
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
# Models the agent must never inspect directly.
|
||||
AI_MODELS_BLOCKLIST = {
|
||||
'base.automation',
|
||||
'res.device',
|
||||
'res.groups',
|
||||
'res.groups.privilege',
|
||||
'res.users.settings',
|
||||
'ir.model',
|
||||
'ir.model.fields',
|
||||
'ir.rule',
|
||||
}
|
||||
|
||||
|
||||
class AITool(models.AbstractModel):
|
||||
"""Implementation of every tool callable by the model.
|
||||
|
||||
Each ``_ai_tool_xxx`` method receives the raw arguments and a mutable
|
||||
``tools_context`` dict. Returning a dict lets the caller collect a summary
|
||||
and, for interactive tools, a ``user_input_request``.
|
||||
"""
|
||||
_name = 'ai.tool'
|
||||
_description = 'AI Tool'
|
||||
|
||||
# ==================================================================
|
||||
# access helpers
|
||||
# ==================================================================
|
||||
def _check_agent_model_access(self, model_name, operation='read'):
|
||||
if model_name in AI_MODELS_BLOCKLIST or model_name.startswith('ir.'):
|
||||
raise ValueError(f"Model '{model_name}' cannot be used by AI agents.")
|
||||
model = self.env.get(model_name)
|
||||
if model is None:
|
||||
raise ValueError(f"Model '{model_name}' does not exist.")
|
||||
model.check_access(operation)
|
||||
return model
|
||||
|
||||
def _parse_domain(self, model_name, domain, operation='read'):
|
||||
"""Validate a domain coming from the model, with user-level rights."""
|
||||
model = self._check_agent_model_access(model_name, operation)
|
||||
if domain in (None, '', False):
|
||||
return []
|
||||
if isinstance(domain, str):
|
||||
try:
|
||||
domain = json.loads(domain)
|
||||
except ValueError:
|
||||
try:
|
||||
domain = coerce_domain(domain)
|
||||
except (ValueError, SyntaxError):
|
||||
raise ValueError(f"Invalid domain: {domain}") from None
|
||||
if not isinstance(domain, list):
|
||||
raise ValueError("A domain must be a list.")
|
||||
return domain
|
||||
|
||||
def _get_model_fields(self, model_name):
|
||||
model = self._check_agent_model_access(model_name)
|
||||
return model.fields_get()
|
||||
|
||||
@api.model
|
||||
def _ai_tool_get_models(self):
|
||||
"""List the models the current user may query."""
|
||||
rows = []
|
||||
for index, model_name in enumerate(self.env):
|
||||
model = self.env[model_name]
|
||||
if model_name in AI_MODELS_BLOCKLIST or model_name.startswith('ir.'):
|
||||
continue
|
||||
if model._abstract or model._transient:
|
||||
continue
|
||||
if not model.has_access('read'):
|
||||
continue
|
||||
rows.append({'model': model_name, 'description': model._description})
|
||||
if index > 2000: # guard against a runaway registry
|
||||
break
|
||||
rows.sort(key=lambda row: row['model'])
|
||||
return {
|
||||
'summary': {'icon': 'view_list', 'text': self.env._("Models")},
|
||||
'models': rows,
|
||||
}
|
||||
|
||||
@api.model
|
||||
def _ai_tool_get_fields(self, model_name, include_description=True):
|
||||
"""Return the technical fields of a model."""
|
||||
self._check_agent_model_access(model_name)
|
||||
model = self.env[model_name]
|
||||
fields_info = model.fields_get()
|
||||
result = []
|
||||
for name, info in sorted(fields_info.items()):
|
||||
row = {
|
||||
'name': name,
|
||||
'type': info.get('type'),
|
||||
'string': info.get('string'),
|
||||
}
|
||||
if info.get('relation'):
|
||||
row['relation'] = info['relation']
|
||||
if info.get('selection'):
|
||||
row['selection'] = [v for v, _label in info['selection']][:30]
|
||||
if info.get('required'):
|
||||
row['required'] = True
|
||||
if info.get('readonly'):
|
||||
row['readonly'] = True
|
||||
if include_description and info.get('help'):
|
||||
row['help'] = info['help'][:200]
|
||||
result.append(row)
|
||||
return {
|
||||
'summary': {'icon': 'view_list', 'text': self.env._("Fields of %s", model._description)},
|
||||
'model': model_name,
|
||||
'fields': result,
|
||||
}
|
||||
|
||||
# ==================================================================
|
||||
# menus
|
||||
# ==================================================================
|
||||
@api.model
|
||||
def _get_available_menus(self):
|
||||
all_menus = self.env['ir.ui.menu'].sudo().load_web_menus(False)
|
||||
root_ids = set(all_menus['root']['children'])
|
||||
rows = []
|
||||
for menu_id, web_menu in all_menus.items():
|
||||
if menu_id == 'root':
|
||||
continue
|
||||
if web_menu.get('actionModel') not in (
|
||||
'ir.actions.act_window', 'ir.actions.client', 'ir.actions.report',
|
||||
):
|
||||
continue
|
||||
menu = self.env['ir.ui.menu'].sudo().browse(web_menu['id'])
|
||||
if not menu.exists():
|
||||
continue
|
||||
action = self.sudo().env[web_menu['actionModel']].browse(web_menu['actionID'])
|
||||
if not action.exists():
|
||||
continue
|
||||
model = action.res_model if action.type != 'ir.actions.report' else action.model
|
||||
view_types = ([v[1] for v in action.views] if action.type == 'ir.actions.act_window' and action.views else [])
|
||||
default_view = view_types[0] if view_types else None
|
||||
if action.type == 'ir.actions.act_window' and action.view_id:
|
||||
default_view = action.view_id.type
|
||||
rows.append({
|
||||
'menu_id': menu.id,
|
||||
'action_id': action.id,
|
||||
'action_type': action.type,
|
||||
'name': menu.complete_name,
|
||||
'model': model or '',
|
||||
'views': view_types,
|
||||
'default_view': default_view,
|
||||
})
|
||||
rows.sort(key=lambda row: row['name'])
|
||||
return rows
|
||||
|
||||
@api.model
|
||||
def _ai_tool_get_menus(self):
|
||||
return {
|
||||
'summary': {'icon': 'apps', 'text': self.env._("Menus")},
|
||||
'menus': self._get_available_menus(),
|
||||
}
|
||||
|
||||
@api.model
|
||||
def _ai_tool_get_menu_details(self, menu_ids, include_model_fields=True):
|
||||
if isinstance(menu_ids, int):
|
||||
menu_ids = [menu_ids]
|
||||
menus = self.env['ir.ui.menu'].sudo().browse(menu_ids).exists()
|
||||
details = []
|
||||
for menu in menus:
|
||||
action = menu.action
|
||||
entry = {
|
||||
'menu_id': menu.id,
|
||||
'name': menu.complete_name,
|
||||
'action_id': action.id if action else None,
|
||||
'action_type': action.type if action else None,
|
||||
'model': (action.res_model if action and action.type != 'ir.actions.report'
|
||||
else getattr(action, 'model', None)),
|
||||
}
|
||||
if include_model_fields and entry['model']:
|
||||
try:
|
||||
entry['fields'] = list(self._get_model_fields(entry['model']))
|
||||
except (ValueError, AccessError):
|
||||
entry['fields'] = []
|
||||
details.append(entry)
|
||||
return {
|
||||
'summary': {'icon': 'apps', 'text': self.env._("Menu details")},
|
||||
'menus': details,
|
||||
}
|
||||
|
||||
# ==================================================================
|
||||
# data retrieval
|
||||
# ==================================================================
|
||||
def _ai_tool_search(self, model_name, domain="", fields=None, offset=0, limit=None, order=None):
|
||||
model = self._check_agent_model_access(model_name)
|
||||
parsed = self._parse_domain(model_name, domain)
|
||||
limit = min(int(limit or 40), 200)
|
||||
read_fields = fields or ['display_name']
|
||||
if isinstance(read_fields, str):
|
||||
read_fields = [read_fields]
|
||||
records = model.search(parsed, offset=int(offset or 0), limit=limit, order=order)
|
||||
vals = records.read(read_fields, load=False)
|
||||
# Normalise relational values so the model sees ids, not (id, name) tuples.
|
||||
for row in vals:
|
||||
for key, value in list(row.items()):
|
||||
if isinstance(value, tuple):
|
||||
row[key] = list(value)
|
||||
return {
|
||||
'summary': {'icon': 'search', 'text': self.env._("Search %s", model._description)},
|
||||
'model': model_name,
|
||||
'count': len(records),
|
||||
'records': vals,
|
||||
}
|
||||
|
||||
def _ai_tool_read_group(self, model_name, domain, groupby=None, aggregates=None):
|
||||
model = self._check_agent_model_access(model_name)
|
||||
parsed = self._parse_domain(model_name, domain)
|
||||
groupby = groupby or []
|
||||
aggregates = aggregates or ['__count']
|
||||
rows = model._read_group(parsed, groupby=groupby, aggregates=aggregates)
|
||||
result = []
|
||||
for row in rows:
|
||||
payload = {}
|
||||
for index, value in enumerate(groupby):
|
||||
key = value.split(':')[0]
|
||||
payload[key] = row[index].display_name if hasattr(row[index], 'display_name') else row[index]
|
||||
for index, measure in enumerate(aggregates):
|
||||
payload[measure] = row[len(groupby) + index]
|
||||
result.append(payload)
|
||||
return {
|
||||
'summary': {'icon': 'bar_chart', 'text': self.env._("Group %s", model._description)},
|
||||
'groups': result,
|
||||
}
|
||||
|
||||
def _ai_tool_read_binary_content(self, model_name, record_ids, field_name=None):
|
||||
model = self._check_agent_model_access(model_name)
|
||||
records = model.browse(record_ids if isinstance(record_ids, (list, tuple)) else [record_ids])
|
||||
payload = []
|
||||
for record in records.exists():
|
||||
if field_name:
|
||||
payload.append({'id': record.id, 'field': field_name,
|
||||
'content': record._ai_read([field_name])[1]})
|
||||
else:
|
||||
payload.append({'id': record.id, 'name': record.display_name})
|
||||
return {
|
||||
'summary': {'icon': 'attachment', 'text': self.env._("Attachments")},
|
||||
'records': payload,
|
||||
}
|
||||
|
||||
# ==================================================================
|
||||
# dates
|
||||
# ==================================================================
|
||||
def _ai_tool_compute_date(self, model_name, field_name, operations=None, pin=None):
|
||||
model = self._check_agent_model_access(model_name)
|
||||
field = model._fields.get(field_name)
|
||||
if not field or field.type not in ('date', 'datetime'):
|
||||
raise ValueError(f"Field '{field_name}' is not a date/datetime field of {model_name}.")
|
||||
today = fields.Date.context_today(model)
|
||||
value = compute_date(field.type, self.env.user.tz or 'UTC', today, operations, pin)
|
||||
return {
|
||||
'summary': {'icon': 'calendar', 'text': self.env._("Computed date")},
|
||||
'field': field_name,
|
||||
'type': field.type,
|
||||
'value': value,
|
||||
}
|
||||
|
||||
# ==================================================================
|
||||
# UI navigation
|
||||
# ==================================================================
|
||||
def _resolve_window_action(self, menu_id, model_name=None):
|
||||
"""Return ``(action, action_dict)`` for a menu, ready to hand to the client.
|
||||
|
||||
The browser side runs ``services.action.doAction(action_dict)``, so the
|
||||
payload must be a **full action dictionary**, not ``{actionId: 12}``.
|
||||
Passing just an id leaves the client with nothing to load, which is how
|
||||
the UI ends up "opened" in the transcript but unchanged on screen.
|
||||
"""
|
||||
menu = self.env['ir.ui.menu'].sudo().browse(menu_id).exists()
|
||||
if not menu:
|
||||
raise ValueError(f"Menu with ID {menu_id} not found.")
|
||||
action = menu.action
|
||||
if not action or action.type != 'ir.actions.act_window':
|
||||
raise ValueError(
|
||||
f"Menu ID {menu_id} is not bound to a window action "
|
||||
f"(got {action.type if action else 'no action'}).")
|
||||
action_dict = action._get_action_dict()
|
||||
if model_name and action_dict.get('res_model') != model_name:
|
||||
raise ValueError(
|
||||
f"The model '{model_name}' does not match the action of menu "
|
||||
f"ID {menu_id} ('{action_dict.get('res_model')}').")
|
||||
return action, action_dict
|
||||
|
||||
def _model_label(self, model_name):
|
||||
"""Return the translated, human-readable name of a model.
|
||||
|
||||
``model._description`` is a plain Python class attribute — it is never
|
||||
routed through the translation layer, so a Chinese user would see
|
||||
"Sales Order" inside an otherwise Chinese sentence. ``ir.model.name``
|
||||
is the translated variant, which is what the UI itself shows.
|
||||
"""
|
||||
ir_model = self.env['ir.model'].sudo().search(
|
||||
[('model', '=', model_name)], limit=1)
|
||||
return ir_model.name or self.env[model_name]._description
|
||||
|
||||
def _normalize_search_terms(self, model_name, search):
|
||||
"""Coerce the tool's ``search`` argument into the client's expected shape.
|
||||
|
||||
The schema asks for a free-text string, but the browser wants a list of
|
||||
``{search_field, value}`` objects (that is what "typing in the search
|
||||
bar" produces). A bare string has no field attached, so anchor it on the
|
||||
model's ``_rec_name`` — searching "SO001" should look at the display
|
||||
name, not at every char field.
|
||||
"""
|
||||
if not search:
|
||||
return []
|
||||
if isinstance(search, (list, tuple)):
|
||||
return [term for term in search if isinstance(term, dict)]
|
||||
model = self.env[model_name]
|
||||
rec_name = model._rec_name
|
||||
if not rec_name or rec_name not in model._fields:
|
||||
return []
|
||||
return [{'search_field': rec_name, 'value': str(search)}]
|
||||
|
||||
def _build_view_action(self, menu_id, model_name, domain=None, filters=None,
|
||||
groupbys=None, search=None, view_type='list', extra=None):
|
||||
"""Build the ``show_view`` payload for the browser.
|
||||
|
||||
``oneway`` matters: opening a view is fire-and-forget. Without it the
|
||||
server pauses in ``waiting_client_result`` and the conversation hangs
|
||||
because nothing ever posts a result back.
|
||||
"""
|
||||
action, action_dict = self._resolve_window_action(menu_id, model_name)
|
||||
available = [view[1] for view in action_dict.get('views') or []]
|
||||
if view_type not in available:
|
||||
raise ValueError(
|
||||
f"'{view_type}' view is not available on menu ID {menu_id}; "
|
||||
f"available: {available}.")
|
||||
|
||||
ai_props = {
|
||||
'selectedFilters': filters or [],
|
||||
'selectedGroupBys': groupbys or [],
|
||||
'search': self._normalize_search_terms(model_name, search),
|
||||
}
|
||||
if domain:
|
||||
# The model sends domains as a JSON string; parse (and validate)
|
||||
# before handing it to the browser.
|
||||
ai_props['customDomain'] = self._parse_domain(model_name, domain)
|
||||
if extra:
|
||||
# Pivot/graph specific keys (``measures``, ``colGroupBys``, ``mode``…)
|
||||
# belong **inside** ``props.ai``: the view patch only reads
|
||||
# ``this.componentProps.ai``. Putting them at the top level of
|
||||
# ``options`` leaves them unread, so the view opens with its default
|
||||
# measures and grouping.
|
||||
ai_props.update({key: value for key, value in extra.items()
|
||||
if value is not None})
|
||||
|
||||
options = {'viewType': view_type, 'props': {'ai': ai_props}}
|
||||
return {
|
||||
'action': action_dict,
|
||||
'options': options,
|
||||
'menuId': menu_id,
|
||||
}
|
||||
|
||||
def _ai_tool_open_menu_list(self, menu_id, model_name, selected_filters=None,
|
||||
selected_groupbys=None, search=None, custom_domain=None):
|
||||
params = self._build_view_action(
|
||||
menu_id, model_name, domain=custom_domain, filters=selected_filters,
|
||||
groupbys=selected_groupbys, search=search, view_type='list')
|
||||
return {
|
||||
'summary': {'icon': 'open_in_browser',
|
||||
'text': self.env._("Opened the list view for %s",
|
||||
self._model_label(model_name))},
|
||||
'client_tool': {'name': 'show_view', 'oneway': True, 'params': params},
|
||||
}
|
||||
|
||||
def _ai_tool_open_menu_kanban(self, menu_id, model_name, selected_filters=None,
|
||||
selected_groupbys=None, search=None, custom_domain=None):
|
||||
params = self._build_view_action(
|
||||
menu_id, model_name, domain=custom_domain, filters=selected_filters,
|
||||
groupbys=selected_groupbys, search=search, view_type='kanban')
|
||||
return {
|
||||
'summary': {'icon': 'open_in_browser',
|
||||
'text': self.env._("Opened the kanban view for %s",
|
||||
self._model_label(model_name))},
|
||||
'client_tool': {'name': 'show_view', 'oneway': True, 'params': params},
|
||||
}
|
||||
|
||||
def _ai_tool_open_menu_pivot(self, menu_id, model_name, selected_filters=None,
|
||||
selected_groupbys=None, row_groupbys=None, col_groupbys=None,
|
||||
measures=None, search=None, custom_domain=None):
|
||||
params = self._build_view_action(
|
||||
menu_id, model_name, domain=custom_domain, filters=selected_filters,
|
||||
groupbys=row_groupbys or selected_groupbys, search=search, view_type='pivot',
|
||||
extra={'colGroupBys': col_groupbys, 'measures': measures})
|
||||
return {
|
||||
'summary': {'icon': 'open_in_browser',
|
||||
'text': self.env._("Opened the pivot view for %s",
|
||||
self._model_label(model_name))},
|
||||
'client_tool': {'name': 'show_view', 'oneway': True, 'params': params},
|
||||
}
|
||||
|
||||
def _ai_tool_open_menu_graph(self, menu_id, model_name, selected_filters=None,
|
||||
selected_groupbys=None, row_groupbys=None, measures=None,
|
||||
chart_type=None, search=None, custom_domain=None):
|
||||
grouped_by = row_groupbys or selected_groupbys
|
||||
params = self._build_view_action(
|
||||
menu_id, model_name, domain=custom_domain, filters=selected_filters,
|
||||
groupbys=grouped_by, search=search, view_type='graph',
|
||||
# Graph reads `measure` (a single field name), `mode` and `groupBys`
|
||||
# — not `graphMeasures`/`graphType`, which nothing consumes.
|
||||
extra={'measure': (measures or [None])[0], 'mode': chart_type,
|
||||
'groupBys': grouped_by})
|
||||
return {
|
||||
'summary': {'icon': 'open_in_browser',
|
||||
'text': self.env._("Opened the graph view for %s",
|
||||
self._model_label(model_name))},
|
||||
'client_tool': {'name': 'show_view', 'oneway': True, 'params': params},
|
||||
}
|
||||
|
||||
def _ai_tool_adjust_search(self, model_name, remove_facets=None, toggle_filters=None,
|
||||
toggle_groupbys=None, apply_searches=None, measures=None,
|
||||
mode=None, order=None, stacked=None, cumulated=None,
|
||||
custom_domain=None, switch_view_type=None):
|
||||
self._check_agent_model_access(model_name)
|
||||
params = {
|
||||
'removeFacets': remove_facets or [],
|
||||
'toggleFilters': toggle_filters or [],
|
||||
'toggleGroupBys': toggle_groupbys or [],
|
||||
'applySearches': self._normalize_search_terms(model_name, apply_searches),
|
||||
'measures': measures or [],
|
||||
'mode': mode or None,
|
||||
'order': order or 'ASC',
|
||||
'stacked': stacked if stacked is not None else None,
|
||||
'cumulated': cumulated if cumulated is not None else None,
|
||||
'switchViewType': switch_view_type or False,
|
||||
}
|
||||
if custom_domain:
|
||||
# `customDomain` is consumed by `SearchModel.splitAndAddDomain`,
|
||||
# which expects a real domain, not the JSON string the tool gets.
|
||||
params['customDomain'] = self._parse_domain(model_name, custom_domain)
|
||||
return {
|
||||
'summary': {'icon': 'filter_alt',
|
||||
'text': self.env._("Refined the search on %s",
|
||||
self._model_label(model_name))},
|
||||
'client_tool': {'name': 'adjust_view', 'oneway': True, 'params': params},
|
||||
}
|
||||
|
||||
def _ai_tool_run_view_action(self, menu_id, action_type):
|
||||
params = self._build_view_action(menu_id, None, view_type=action_type)
|
||||
return {
|
||||
'summary': {'icon': 'open_in_browser', 'text': self.env._("Opened view")},
|
||||
'client_tool': {'name': 'show_view', 'oneway': True, 'params': params},
|
||||
}
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# opening one specific record
|
||||
# ------------------------------------------------------------------
|
||||
def _find_window_action_for_model(self, model_name):
|
||||
"""Return ``(menu, action_dict)`` for a form-capable action on a model.
|
||||
|
||||
After a write the freshly created record must be shown in the surface
|
||||
the user knows, with the right menu highlighted, so the menu bound to
|
||||
the action is preferred. ``menu`` is ``None`` when the model is only
|
||||
reachable from a child action that no menu points at directly.
|
||||
"""
|
||||
actions = self.env['ir.actions.act_window'].sudo().search(
|
||||
[('res_model', '=', model_name)])
|
||||
fallback = None
|
||||
for action in actions:
|
||||
view_types = [view[1] for view in action.views or []]
|
||||
if 'form' not in view_types:
|
||||
continue
|
||||
action_dict = action._get_action_dict()
|
||||
menu = self.env['ir.ui.menu'].sudo().search(
|
||||
[('action', '=', f'ir.actions.act_window,{action.id}')], limit=1)
|
||||
if menu:
|
||||
return menu, action_dict
|
||||
# Keep looking: another action of the same model may be the one a
|
||||
# menu actually points at. Remember this one in case none is.
|
||||
if fallback is None:
|
||||
fallback = action_dict
|
||||
return None, fallback
|
||||
|
||||
def _build_record_action(self, model_name, res_ids, menu_id=None, label=None):
|
||||
"""Build a ``show_view`` payload that opens the given records.
|
||||
|
||||
A single record is opened as a **form view driven by ``res_id``**, not
|
||||
by putting the id in a domain — a domain lands on a one-row list, which
|
||||
is the "it says it created the order but nothing opened" symptom. A
|
||||
batch opens the list filtered on those ids, because a form view cannot
|
||||
present a set.
|
||||
"""
|
||||
res_ids = [int(res_id) for res_id in (res_ids or []) if res_id]
|
||||
if not res_ids:
|
||||
raise ValueError("No record to open.")
|
||||
|
||||
if menu_id:
|
||||
menu, action_dict = self._resolve_window_action(menu_id, model_name)
|
||||
else:
|
||||
menu, action_dict = self._find_window_action_for_model(model_name)
|
||||
|
||||
if action_dict:
|
||||
action_dict = dict(action_dict)
|
||||
else:
|
||||
# No stored action carries the form view (rare, but a model can be
|
||||
# written to without any menu). A minimal action still opens it.
|
||||
view_types = ['form'] if len(res_ids) == 1 else ['list', 'form']
|
||||
action_dict = {
|
||||
'type': 'ir.actions.act_window',
|
||||
'res_model': model_name,
|
||||
'view_mode': ','.join(view_types),
|
||||
'views': [[False, view] for view in view_types],
|
||||
'target': 'current',
|
||||
}
|
||||
|
||||
action_dict['name'] = label or action_dict.get('name') or self._model_label(model_name)
|
||||
options = {}
|
||||
if len(res_ids) == 1:
|
||||
# `res_id` on the action is what makes the form controller load the
|
||||
# record; `viewType: form` forces it even when the action defaults
|
||||
# to the list (e.g. the "Sales" menu).
|
||||
action_dict['res_id'] = res_ids[0]
|
||||
options['viewType'] = 'form'
|
||||
options['props'] = {'resId': res_ids[0]}
|
||||
else:
|
||||
action_dict.pop('res_id', None)
|
||||
options['viewType'] = 'list'
|
||||
options['props'] = {
|
||||
'ai': {'customDomain': [['id', 'in', res_ids]]},
|
||||
}
|
||||
if menu:
|
||||
# Drop the breadcrumb so the back button does not grow a trail of
|
||||
# AI-opened windows; the menu highlight still points at the app.
|
||||
options['clearBreadcrumbs'] = True
|
||||
return {
|
||||
'action': action_dict,
|
||||
'options': options,
|
||||
'menuId': menu.id if menu else None,
|
||||
}
|
||||
|
||||
|
||||
def _ai_tool_compute_report_measures(self, action_id, model):
|
||||
model_obj = self._check_agent_model_access(model)
|
||||
fields_info = model_obj.fields_get()
|
||||
measures = []
|
||||
for name, info in fields_info.items():
|
||||
if info.get('type') in ('integer', 'float', 'monetary') and info.get('aggregator'):
|
||||
measures.append({
|
||||
'name': name,
|
||||
'string': info.get('string'),
|
||||
'type': info.get('type'),
|
||||
'aggregator': info.get('aggregator'),
|
||||
})
|
||||
return {
|
||||
'summary': {'icon': 'sum', 'text': self.env._("Measures")},
|
||||
'measures': measures,
|
||||
}
|
||||
|
||||
# ==================================================================
|
||||
# write operations (always preview first)
|
||||
# ==================================================================
|
||||
def _ai_tool_prepare_record_previews(self, model_name, record_ids, preview_label=None):
|
||||
model = self._check_agent_model_access(model_name)
|
||||
records = model.browse(record_ids if isinstance(record_ids, (list, tuple)) else [record_ids])
|
||||
records.check_access('read')
|
||||
existing = records.exists()
|
||||
return {
|
||||
'summary': {'icon': 'visibility', 'text': preview_label or self.env._("Preview")},
|
||||
'records': [
|
||||
{'id': record.id, 'name': record.display_name} for record in existing
|
||||
],
|
||||
'preview_links': [
|
||||
{'label': record.display_name, 'model': model_name, 'id': record.id}
|
||||
for record in existing
|
||||
],
|
||||
}
|
||||
|
||||
def _ai_tool_create_records(self, tool_context, explanation, preview_menu_id,
|
||||
model_name, values):
|
||||
if not tool_context.get('tool_request_confirmed'):
|
||||
raise UserError(self.env._("Creating records requires user confirmation."))
|
||||
if not model_name or not isinstance(model_name, str):
|
||||
raise ValueError("'model_name' is required (the technical model name, "
|
||||
"e.g. 'res.partner').")
|
||||
if not values:
|
||||
raise ValueError("'values' is required: a dict of field values.")
|
||||
model = self._check_agent_model_access(model_name, 'create')
|
||||
created = model.create(values if isinstance(values, list) else [values])
|
||||
outcome = {
|
||||
'summary': {'icon': 'add', 'text': self.env._("Created %s", model._description)},
|
||||
'created': [{'id': record.id, 'name': record.display_name} for record in created],
|
||||
'response': '\n'.join(
|
||||
f'Created {model._description}: {record.display_name}' for record in created
|
||||
),
|
||||
}
|
||||
outcome.update(self._open_after_write(
|
||||
tool_context, model_name, created, preview_menu_id, explanation))
|
||||
return outcome
|
||||
|
||||
def _open_after_write(self, tool_context, model_name, records, menu_id=None,
|
||||
label=None):
|
||||
"""Queue the browser action that shows what was just written.
|
||||
|
||||
Without this the transcript says "Created Sales Order" and the user is
|
||||
left to hunt for the record in the menus.
|
||||
|
||||
The action is marked ``exclusive``: a turn that creates a contact, two
|
||||
products and then a sales order queues four navigations, and replaying
|
||||
them in order would flicker through every form and land on the last one
|
||||
anyway. An exclusive entry replaces the previous exclusive ones, so the
|
||||
user lands on the record the answer is about.
|
||||
"""
|
||||
if not records:
|
||||
return {}
|
||||
try:
|
||||
params = self._build_record_action(
|
||||
model_name, records.ids, menu_id=menu_id, label=label)
|
||||
except (ValueError, AccessError) as exc:
|
||||
# Opening a view is a convenience: never fail a successful write
|
||||
# because the model has no action or the user cannot see it.
|
||||
_logger.info("dn_ai: cannot open %s after write: %s", model_name, exc)
|
||||
return {}
|
||||
return {
|
||||
'client_tool': {
|
||||
'name': 'show_view', 'oneway': True, 'exclusive': True,
|
||||
'params': params,
|
||||
},
|
||||
}
|
||||
|
||||
def _ai_tool_update_records(self, tool_context, explanation, preview_menus, updates):
|
||||
if not tool_context.get('tool_request_confirmed'):
|
||||
raise UserError(self.env._("Updating records requires user confirmation."))
|
||||
if len(updates) > 50:
|
||||
raise ValueError("At most 50 updates are allowed at once.")
|
||||
done = []
|
||||
touched = None
|
||||
touched_model = None
|
||||
for update in updates:
|
||||
model_name = update['model_name']
|
||||
model = self._check_agent_model_access(model_name, 'write')
|
||||
domain = self._parse_domain(model_name, update.get('domain'), operation='write')
|
||||
if not domain:
|
||||
raise ValueError("You cannot update all records; pass a real domain.")
|
||||
changes = {}
|
||||
for item in update.get('changes') or []:
|
||||
changes[item['field']] = item.get('value')
|
||||
records = model.search(domain)
|
||||
records.check_access('write')
|
||||
records.write(changes)
|
||||
done.append({'model': model_name, 'count': len(records)})
|
||||
if records and touched_model is None:
|
||||
# Remember the first batch: it is the one the explanation is
|
||||
# about, so it is the one worth showing.
|
||||
touched, touched_model = records, model_name
|
||||
outcome = {
|
||||
'summary': {'icon': 'edit', 'text': self.env._("Updated records")},
|
||||
'updated': done,
|
||||
'response': 'Updated: ' + json.dumps(done, ensure_ascii=False),
|
||||
}
|
||||
if touched is not None and len(touched) == 1:
|
||||
# Only a single record has an obvious form to open; a bulk update
|
||||
# would open an arbitrary member of the set.
|
||||
outcome.update(self._open_after_write(
|
||||
tool_context, touched_model, touched,
|
||||
preview_menus[0] if preview_menus else None))
|
||||
return outcome
|
||||
|
||||
|
||||
# ==================================================================
|
||||
# interaction
|
||||
# ==================================================================
|
||||
def _ai_tool_ask_user_question(self, tool_context, question, choices=None,
|
||||
multi_select=False, allow_free_text=True):
|
||||
normalised = []
|
||||
for choice in choices or []:
|
||||
if isinstance(choice, dict):
|
||||
label = choice.get('label') or choice.get('value') or ''
|
||||
value = choice.get('value') or label
|
||||
else:
|
||||
label = value = str(choice)
|
||||
normalised.append({'label': label, 'value': value})
|
||||
tool_context['user_input_request'] = {
|
||||
'type': 'question',
|
||||
'question': question,
|
||||
'choices': normalised,
|
||||
'multi_select': bool(multi_select),
|
||||
'allow_free_text': bool(allow_free_text),
|
||||
}
|
||||
return {
|
||||
'summary': {'icon': 'help', 'text': self.env._("Waiting for your answer")},
|
||||
'response': 'Waiting for the user to answer.',
|
||||
}
|
||||
|
||||
def _ai_tool_load_skills(self, tool_context, skill_ids):
|
||||
from ..utils.ai_utils import get_text_from_parts # local import avoids cycle
|
||||
skills = self.env['ai.skill'].browse(skill_ids).exists()
|
||||
if not skills:
|
||||
raise ValueError("No valid skill id provided.")
|
||||
state = tool_context['state']
|
||||
state['loaded_skills'] = list(dict.fromkeys(
|
||||
(state.get('loaded_skills') or []) + skills.ids))
|
||||
new_tools = skills.mapped('tool_ids').filtered('use_in_ai')
|
||||
state['available_tools'] = list(dict.fromkeys(
|
||||
(state.get('available_tools') or []) + new_tools.ids))
|
||||
blocks = []
|
||||
for skill in skills:
|
||||
blocks.append(f"## {skill.name}\n{skill.instructions or ''}")
|
||||
return {
|
||||
'summary': {'icon': 'lightbulb', 'text': self.env._("Loaded skills")},
|
||||
'response': "\n\n".join(blocks),
|
||||
}
|
||||
174
dn_ai/models/discuss_channel.py
Normal file
174
dn_ai/models/discuss_channel.py
Normal file
@@ -0,0 +1,174 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from datetime import timedelta
|
||||
|
||||
from odoo import api, fields, models
|
||||
from odoo.exceptions import UserError
|
||||
from odoo.addons.mail.tools.discuss import Store
|
||||
|
||||
|
||||
class DiscussChannel(models.Model):
|
||||
"""Make Discuss aware of AI conversations."""
|
||||
_inherit = "discuss.channel"
|
||||
|
||||
channel_type = fields.Selection(
|
||||
selection_add=[("ai_chat", "AI chat")],
|
||||
ondelete={"ai_chat": "cascade"},
|
||||
)
|
||||
ai_agent_id = fields.Many2one(
|
||||
"ai.agent", index="btree_not_null", groups=fields.NO_ACCESS,
|
||||
help="Agent driving this conversation. Only written by controlled flows.",
|
||||
)
|
||||
ai_session_ids = fields.One2many('ai.session', inverse_name='channel_id')
|
||||
|
||||
_ai_channel_type_check = models.Constraint(
|
||||
"CHECK(ai_agent_id IS NULL OR channel_type = 'ai_chat')",
|
||||
'An AI agent can only be attached to an AI chat.',
|
||||
)
|
||||
|
||||
def _compute_display_name(self):
|
||||
super()._compute_display_name()
|
||||
for channel in self:
|
||||
# The conversation is named after its agent, so renaming the agent
|
||||
# renames the chat; the stored `name` is only there because the
|
||||
# column is NOT NULL.
|
||||
if channel.channel_type == 'ai_chat':
|
||||
agent = channel.sudo().ai_agent_id
|
||||
if agent:
|
||||
channel.display_name = agent.name
|
||||
|
||||
@api.depends("channel_type", "image_128", "ai_agent_id.partner_id.avatar_128")
|
||||
def _compute_avatar_128(self):
|
||||
base_channels = self.env['discuss.channel']
|
||||
for channel in self:
|
||||
if (channel.channel_type == 'ai_chat' and not channel.image_128
|
||||
and (agent := channel.sudo().ai_agent_id)):
|
||||
channel.avatar_128 = agent.partner_id.avatar_128
|
||||
else:
|
||||
base_channels |= channel
|
||||
super(DiscussChannel, base_channels)._compute_avatar_128()
|
||||
|
||||
@api.autovacuum
|
||||
def _remove_ai_chat_channels(self):
|
||||
self.sudo().search([
|
||||
('channel_type', '=', 'ai_chat'),
|
||||
('has_message', '=', False),
|
||||
('create_date', '<', fields.Datetime.now() - timedelta(days=2)),
|
||||
]).unlink()
|
||||
|
||||
def _store_channel_fields(self, res: Store.FieldList):
|
||||
super()._store_channel_fields(res)
|
||||
res.one("ai_agent_id", "_store_agent_fields", sudo=True,
|
||||
predicate=lambda c: c.channel_type == 'ai_chat')
|
||||
res.attr("create_date", predicate=lambda c: c.channel_type == 'ai_chat')
|
||||
# The confirmation / question card has to be rendered by the chat
|
||||
# window itself: the choices are interactive, and a stored message body
|
||||
# cannot carry working buttons (it is sanitised on the way in).
|
||||
res.attr("dn_ai_pending", predicate=lambda c: c.channel_type == 'ai_chat')
|
||||
|
||||
dn_ai_pending = fields.Json(
|
||||
"Pending AI interaction",
|
||||
compute="_compute_dn_ai_pending",
|
||||
help="Confirmation or question the agent is waiting for, surfaced to "
|
||||
"the chat window so it can render clickable choices.",
|
||||
)
|
||||
|
||||
@api.depends("channel_type", "ai_session_ids.loop_state",
|
||||
"ai_session_ids.pending_tool_call", "ai_session_ids.parent_session_id")
|
||||
def _compute_dn_ai_pending(self):
|
||||
sessions = self.env['ai.session'].sudo().search([
|
||||
('channel_id', 'in', self.ids),
|
||||
('parent_session_id', '=', False),
|
||||
])
|
||||
by_channel = {session.channel_id.id: session for session in sessions}
|
||||
for channel in self:
|
||||
session = by_channel.get(channel.id)
|
||||
if channel.channel_type != 'ai_chat' or not session:
|
||||
channel.dn_ai_pending = False
|
||||
continue
|
||||
request = (session.pending_tool_call or {}).get('request') or {}
|
||||
if not request or session.loop_state not in (
|
||||
'waiting_confirmation', 'waiting_answer',
|
||||
):
|
||||
channel.dn_ai_pending = False
|
||||
continue
|
||||
channel.dn_ai_pending = {
|
||||
'session_id': session.id,
|
||||
'type': 'question' if request.get('type') == 'question' else 'confirmation',
|
||||
'body': request.get('body') or request.get('question') or '',
|
||||
'choices': request.get('choices') or [],
|
||||
'multi_select': bool(request.get('multi_select')),
|
||||
'allow_free_text': request.get('allow_free_text', True),
|
||||
}
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# RPC used by the standalone chat panel (static/src/chat.js)
|
||||
# ------------------------------------------------------------------
|
||||
def dn_ai_fetch_messages(self, limit=60):
|
||||
"""Return the transcript plus the pending interaction, if any.
|
||||
|
||||
Kept as a plain server call so the chat panel does not need to know
|
||||
anything about the mail store / websocket protocol.
|
||||
"""
|
||||
self.ensure_one()
|
||||
self.check_access('read')
|
||||
if self.channel_type != 'ai_chat':
|
||||
raise UserError(self.env._("This conversation is not an AI chat."))
|
||||
session = self.env['ai.session'].sudo()._get_channel_session(self)
|
||||
agent = session.agent_id if session else self.sudo().ai_agent_id
|
||||
agent_partner = agent.partner_id
|
||||
|
||||
messages = []
|
||||
for message in self.sudo().message_ids.sorted('id')[-limit:]:
|
||||
author = message.author_id
|
||||
body = message.body or ''
|
||||
messages.append({
|
||||
'id': message.id,
|
||||
'body': body,
|
||||
# A tool summary is one line of progress ("搜索 Contact"),
|
||||
# posted as its own message by the loop. Flagging it lets the
|
||||
# panel fold consecutive steps into a single collapsible
|
||||
# timeline instead of a wall of speech bubbles that buries the
|
||||
# actual answer.
|
||||
'is_step': 'o_ai_tool_summary' in body,
|
||||
'author_name': author.name or self.env._('System'),
|
||||
'is_agent': bool(agent_partner and author == agent_partner),
|
||||
'date': fields.Datetime.to_string(message.date),
|
||||
# The panel renders its own bubble instead of the mail chatter,
|
||||
# so the attachment cards have to travel with the message.
|
||||
'attachments': [
|
||||
{
|
||||
'id': attachment.id,
|
||||
'name': attachment.name,
|
||||
'mimetype': attachment.mimetype or '',
|
||||
'size': attachment.file_size or 0,
|
||||
# Internal users read their own uploads through the
|
||||
# regular ACL, no access token needed.
|
||||
'url': f"/web/content/{attachment.id}?download=true",
|
||||
'is_image': (attachment.mimetype or '').startswith('image/'),
|
||||
}
|
||||
for attachment in message.attachment_ids.sudo()
|
||||
],
|
||||
})
|
||||
|
||||
pending = False
|
||||
if session:
|
||||
request = (session.pending_tool_call or {}).get('request') or {}
|
||||
if request and session.loop_state in (
|
||||
'waiting_confirmation', 'waiting_answer',
|
||||
):
|
||||
pending = {
|
||||
'type': 'question' if request.get('type') == 'question' else 'confirmation',
|
||||
'body': request.get('body') or request.get('question') or '',
|
||||
'choices': request.get('choices') or [],
|
||||
'multi_select': bool(request.get('multi_select')),
|
||||
'allow_free_text': request.get('allow_free_text', True),
|
||||
}
|
||||
|
||||
return {
|
||||
'messages': messages,
|
||||
'agent_name': (agent.name if agent else '') or '',
|
||||
'session_id': session.id if session else False,
|
||||
'pending': pending,
|
||||
'loop_state': session.loop_state if session else False,
|
||||
}
|
||||
|
||||
306
dn_ai/models/ir_actions_server.py
Normal file
306
dn_ai/models/ir_actions_server.py
Normal file
@@ -0,0 +1,306 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
|
||||
from odoo import api, fields, models
|
||||
from odoo.exceptions import UserError, ValidationError
|
||||
|
||||
from ..utils.agent_instructions_prompts import AI_ACTIONS_PROMPT
|
||||
from ..utils.ai_utils import format_tool_result, get_text_from_parts
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
# Server action types that can safely be exposed to the model.
|
||||
ALLOWED_STATES_FOR_AI = {
|
||||
'code', 'next_activity', 'object_create', 'object_copy',
|
||||
'followers', 'remove_followers', 'webhook', 'mail_post',
|
||||
}
|
||||
|
||||
TOOL_NAME_RE = re.compile(r'[a-zA-Z0-9_]{1,64}')
|
||||
|
||||
|
||||
class IrActionsServer(models.Model):
|
||||
_inherit = "ir.actions.server"
|
||||
|
||||
# ---- AI action ---------------------------------------------------
|
||||
state = fields.Selection(
|
||||
selection_add=[("ai", "AI")],
|
||||
ondelete={"ai": "cascade"},
|
||||
)
|
||||
ai_action_prompt = fields.Html(
|
||||
string="AI Action Prompt",
|
||||
help='Prompt used by the "AI" action type.',
|
||||
sanitize=True,
|
||||
sanitize_output_method="xml",
|
||||
)
|
||||
ai_tool_ids = fields.Many2many(
|
||||
"ir.actions.server", "dn_ai_action_tool_rel", "parent_id", "tool_id",
|
||||
string="Tools",
|
||||
)
|
||||
|
||||
# ---- AI tool -----------------------------------------------------
|
||||
ai_tool_name = fields.Char("AI Tool Name")
|
||||
ai_tool_description = fields.Text("AI Tool Description", translate=True)
|
||||
ai_tool_schema = fields.Text(
|
||||
"AI Schema",
|
||||
help="JSON Schema describing the arguments the model must provide.",
|
||||
store=True,
|
||||
readonly=False,
|
||||
compute="_compute_use_in_ai",
|
||||
)
|
||||
use_in_ai = fields.Boolean(
|
||||
"Use in AI", store=True, readonly=False, compute="_compute_use_in_ai",
|
||||
)
|
||||
ai_tool_is_candidate = fields.Boolean(compute="_compute_ai_tool_is_candidate")
|
||||
ai_tool_has_schema = fields.Boolean(compute="_compute_ai_tool_has_schema")
|
||||
ai_tool_thinking_text = fields.Char(
|
||||
"AI Tool Thinking Text", translate=True,
|
||||
help="Progress message shown while the tool runs.",
|
||||
)
|
||||
ai_tool_requires_confirmation = fields.Boolean(
|
||||
"Requires confirmation",
|
||||
help="Show a confirmation card before executing this tool.",
|
||||
)
|
||||
|
||||
_ai_tool_name_unique = models.UniqueIndex(
|
||||
"(ai_tool_name) WHERE use_in_ai IS TRUE",
|
||||
"Two AI tools cannot share the same name.",
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# computes / constraints
|
||||
# ------------------------------------------------------------------
|
||||
@api.depends("state")
|
||||
def _compute_use_in_ai(self):
|
||||
for action in self:
|
||||
if not action.ai_tool_is_candidate:
|
||||
action.use_in_ai = False
|
||||
action.ai_tool_schema = False
|
||||
|
||||
@api.depends("state", "child_ids", "evaluation_type")
|
||||
def _compute_ai_tool_is_candidate(self):
|
||||
for action in self:
|
||||
action.ai_tool_is_candidate = (
|
||||
action.state in ALLOWED_STATES_FOR_AI
|
||||
or (action.state == 'object_write' and action.evaluation_type in ('value', 'sequence'))
|
||||
or (action.state == 'multi' and all(c.ai_tool_is_candidate for c in action.child_ids))
|
||||
)
|
||||
|
||||
@api.depends("state", "child_ids")
|
||||
def _compute_ai_tool_has_schema(self):
|
||||
for action in self:
|
||||
action.ai_tool_has_schema = (
|
||||
action.state == 'code'
|
||||
or (action.state == 'multi' and any(c.ai_tool_has_schema for c in action.child_ids))
|
||||
)
|
||||
|
||||
@api.constrains("state", "use_in_ai")
|
||||
def _check_use_in_ai(self):
|
||||
for action in self:
|
||||
if action.use_in_ai and not action.ai_tool_is_candidate:
|
||||
raise ValidationError(
|
||||
self.env._("The action '%s' cannot be used as an AI tool.", action.name))
|
||||
|
||||
@api.constrains("use_in_ai", "ai_tool_name")
|
||||
def _check_ai_tool_name(self):
|
||||
for action in self.filtered('use_in_ai'):
|
||||
if not action.ai_tool_name:
|
||||
raise ValidationError(self.env._(
|
||||
"The action '%s' must have an AI Tool Name.", action.name))
|
||||
if not TOOL_NAME_RE.fullmatch(action.ai_tool_name):
|
||||
raise ValidationError(self.env._(
|
||||
"The tool name may only contain letters, digits and underscores "
|
||||
"(max 64 characters)."))
|
||||
|
||||
@api.constrains("ai_tool_schema")
|
||||
def _check_ai_tool_schema(self):
|
||||
for action in self:
|
||||
if not action.ai_tool_schema:
|
||||
continue
|
||||
try:
|
||||
data = json.loads(action.ai_tool_schema)
|
||||
except ValueError:
|
||||
raise ValidationError(self.env._("Invalid JSON schema (malformed JSON).")) from None
|
||||
if not isinstance(data, dict):
|
||||
raise ValidationError(self.env._("Invalid JSON schema (must be an object)."))
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# execution
|
||||
# ------------------------------------------------------------------
|
||||
def _ai_tool_run(self, record, arguments, tools_context):
|
||||
"""Execute this action as a tool call."""
|
||||
self.ensure_one()
|
||||
arguments = dict(arguments or {})
|
||||
if self.ai_tool_schema:
|
||||
try:
|
||||
schema = json.loads(self.ai_tool_schema)
|
||||
except ValueError:
|
||||
schema = {}
|
||||
arguments = self._ai_coerce_arguments(arguments, schema)
|
||||
|
||||
if self.ai_tool_requires_confirmation and self._ai_needs_confirmation(tools_context):
|
||||
tools_context['user_input_request'] = {
|
||||
'type': 'confirmation',
|
||||
'body': self.ai_tool_thinking_text or self.env._(
|
||||
'Should I run "%s"?', self.name),
|
||||
'choices': [
|
||||
{'label': self.env._("Yes, do it"), 'value': 'confirm_once'},
|
||||
{'label': self.env._("Yes, always approve in this chat"), 'value': 'auto_confirm'},
|
||||
{'label': self.env._("No, I want something else"), 'value': 'decline'},
|
||||
],
|
||||
'allow_free_text': False,
|
||||
}
|
||||
return {'summary': {'icon': 'help', 'text': self.env._("Waiting for your confirmation")},
|
||||
'response': 'Waiting for the user to confirm.'}
|
||||
|
||||
model_name = self.model_id.model
|
||||
record = record if record and record._name == model_name else self.env[model_name]
|
||||
eval_context = arguments.copy()
|
||||
eval_context |= self._get_eval_context(self)
|
||||
eval_context['ai'] = tools_context or {}
|
||||
eval_context['record'] = record.sudo(False)
|
||||
eval_context['records'] = record.sudo(False)
|
||||
eval_context['model'] = eval_context['model'].sudo(False)
|
||||
eval_context['env'] = self.env(su=False)
|
||||
|
||||
if self.state == 'code':
|
||||
eval_context = self._ai_fill_missing_names(eval_context)
|
||||
self._run_action_code_multi(eval_context=eval_context)
|
||||
if eval_context.get('action'):
|
||||
raise UserError(self.env._(
|
||||
'This action is interactive and cannot be executed by the agent.'))
|
||||
return eval_context['ai'].get('result')
|
||||
|
||||
if self.state == 'multi':
|
||||
result = None
|
||||
for action in self.child_ids:
|
||||
result = action._ai_tool_run(record, arguments, tools_context) or result
|
||||
return result
|
||||
|
||||
if self.ai_tool_is_candidate:
|
||||
self._run(record, eval_context)
|
||||
return self._ai_get_action_description(record)
|
||||
|
||||
raise UserError(self.env._("This action cannot be executed by the AI."))
|
||||
|
||||
def _ai_needs_confirmation(self, tools_context):
|
||||
return not tools_context.get('tool_request_confirmed')
|
||||
|
||||
def _ai_is_confirmed(self, tools_context):
|
||||
return bool(tools_context.get('tool_request_confirmed'))
|
||||
|
||||
def _ai_get_action_description(self, record):
|
||||
self.ensure_one()
|
||||
if self.state == 'next_activity':
|
||||
return self.env._('Activity created.')
|
||||
return self.env._('Action "%(action)s" done.', action=self.name)
|
||||
|
||||
@api.model
|
||||
def _ai_fill_missing_names(self, eval_context):
|
||||
"""Define any bare name the action code reads but the schema omits.
|
||||
|
||||
Server-action code runs ``record._ai_tool_xxx(menu_id, ..., search)``
|
||||
with the arguments injected as locals. A name the schema never declared
|
||||
is therefore simply *undefined*, and the whole tool call dies with::
|
||||
|
||||
NameError: name 'search' is not defined
|
||||
|
||||
which the model then reports to the user as an opaque internal error.
|
||||
Binding those names to ``None`` turns a hard failure into an argument the
|
||||
tool can default, so a stale schema degrades instead of breaking.
|
||||
"""
|
||||
import ast
|
||||
import builtins
|
||||
|
||||
code = self.code or ''
|
||||
try:
|
||||
tree = ast.parse(code.lstrip('\n'), mode='exec')
|
||||
except SyntaxError:
|
||||
return eval_context # let the regular runner report the real error
|
||||
|
||||
defined = set(eval_context) | set(dir(builtins))
|
||||
loaded = {
|
||||
node.id for node in ast.walk(tree)
|
||||
if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Load)
|
||||
}
|
||||
for name in loaded - defined:
|
||||
eval_context[name] = None
|
||||
return eval_context
|
||||
|
||||
def _ai_coerce_arguments(self, arguments, schema):
|
||||
"""Coerce LLM strings to the declared types and fill optional args.
|
||||
|
||||
Server-action code interpolates arguments as local variables, so every
|
||||
declared property must exist — otherwise a missing optional argument
|
||||
would raise ``NameError`` inside the tool body.
|
||||
"""
|
||||
properties = schema.get('properties') or {}
|
||||
for key, spec in properties.items():
|
||||
if key not in arguments and spec.get('default') is not None:
|
||||
arguments[key] = spec['default']
|
||||
if key not in arguments:
|
||||
arguments[key] = None
|
||||
for key, value in list(arguments.items()):
|
||||
spec = properties.get(key) or {}
|
||||
expected = spec.get('type')
|
||||
if isinstance(expected, list):
|
||||
expected = expected[0] if expected else None
|
||||
if expected == 'integer' and isinstance(value, str):
|
||||
try:
|
||||
arguments[key] = int(value)
|
||||
except ValueError:
|
||||
pass
|
||||
elif expected == 'number' and isinstance(value, str):
|
||||
try:
|
||||
arguments[key] = float(value)
|
||||
except ValueError:
|
||||
pass
|
||||
elif expected == 'boolean' and isinstance(value, str):
|
||||
arguments[key] = value.strip().lower() in ('true', '1', 'yes')
|
||||
elif expected == 'array' and isinstance(value, str):
|
||||
try:
|
||||
arguments[key] = json.loads(value)
|
||||
except ValueError:
|
||||
pass
|
||||
return arguments
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# "AI" action type: run the agent on a record
|
||||
# ------------------------------------------------------------------
|
||||
def _run_action_ai_multi(self, eval_context=None):
|
||||
for record in self._ai_get_records(eval_context):
|
||||
self._ai_action_run(record)
|
||||
|
||||
def _ai_get_records(self, eval_context):
|
||||
if self.env.context.get('onchange_self'):
|
||||
return self.env.context['onchange_self']
|
||||
records = eval_context.get('record') or eval_context['model']
|
||||
return records | (eval_context.get('records') or eval_context['model'])
|
||||
|
||||
def _ai_action_run(self, record):
|
||||
self.ensure_one()
|
||||
action_prompt = ''
|
||||
if self.ai_action_prompt:
|
||||
action_prompt = get_text_from_parts(
|
||||
self.env['ir.qweb']._render('dn_ai.ai_action_prompt_text', {
|
||||
'action': self, 'record': record}))
|
||||
|
||||
from datetime import UTC, datetime
|
||||
now = datetime.now(UTC).astimezone().replace(second=0, microsecond=0).isoformat()
|
||||
context_text = f"# Context\n## Current date\n{now}"
|
||||
context_text += f'\n## Current record\n{{"model": "{record._name}", "id": {record.id}}}'
|
||||
|
||||
parts = [{'type': 'text', 'text': f"# Action request\n{action_prompt}\n{context_text}"}]
|
||||
responses, history = self.env['ai.session']._get_direct_response(
|
||||
instructions=AI_ACTIONS_PROMPT,
|
||||
message=parts,
|
||||
tools=self.ai_tool_ids.filtered('use_in_ai'),
|
||||
record=record,
|
||||
)
|
||||
return responses, history
|
||||
|
||||
def action_open_ai_action(self):
|
||||
"""Smart button helper: open the record form (placeholder)."""
|
||||
self.ensure_one()
|
||||
return True
|
||||
84
dn_ai/models/ir_attachment.py
Normal file
84
dn_ai/models/ir_attachment.py
Normal file
@@ -0,0 +1,84 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import base64
|
||||
|
||||
from odoo import api, models
|
||||
|
||||
from ..utils.ai_attachment_tools import build_parts, format_size
|
||||
|
||||
DEFAULT_MAX_TEXT_CHARS = 40000
|
||||
|
||||
|
||||
class IrAttachment(models.Model):
|
||||
"""Teach ``ir.attachment`` how to feed a file to the language model.
|
||||
|
||||
Mirrors the Enterprise assistant: an attachment is turned into message
|
||||
parts (``text`` or ``inline_data``) which are then sent as the user turn.
|
||||
The chat panel and the composer share this code path, so any surface that
|
||||
collects attachments behaves the same.
|
||||
"""
|
||||
_inherit = 'ir.attachment'
|
||||
|
||||
@api.model
|
||||
def _dn_ai_max_text_chars(self):
|
||||
char = self.env['ir.config_parameter'].sudo().get_int(
|
||||
'dn_ai.attachment_max_chars', 0)
|
||||
return char or DEFAULT_MAX_TEXT_CHARS
|
||||
|
||||
def _dn_ai_read(self):
|
||||
"""Return a flat list of message parts for ``self``.
|
||||
|
||||
The files are read with ``sudo``: the assistant already runs on behalf
|
||||
of the user and the attachment was access-checked when it was uploaded.
|
||||
Refusing here would only break the very turn the user just started.
|
||||
"""
|
||||
parts = []
|
||||
max_chars = self._dn_ai_max_text_chars()
|
||||
for attachment in self.sudo():
|
||||
name = attachment.name or 'file'
|
||||
try:
|
||||
data = attachment._dn_ai_raw_bytes()
|
||||
except (ValueError, OSError, FileNotFoundError) as exc:
|
||||
parts.append({
|
||||
'type': 'text',
|
||||
'text': f"File '{name}' could not be read: {exc}",
|
||||
})
|
||||
continue
|
||||
parts.extend(build_parts(
|
||||
name, attachment.mimetype or '', data, max_text_chars=max_chars))
|
||||
return parts
|
||||
|
||||
def _dn_ai_raw_bytes(self):
|
||||
"""Return the file content as ``bytes``, whichever Odoo version runs.
|
||||
|
||||
``ir.attachment.raw`` changed shape between versions:
|
||||
|
||||
* 17.0 — a plain ``fields.Binary``, so reading it yields ``bytes``;
|
||||
* 18.0+ — a lazy ``BinaryValue`` wrapper, where the payload is reached
|
||||
through ``.content``.
|
||||
|
||||
Reading ``.content`` unconditionally is what made every PDF upload fail
|
||||
on 17 with ``'bytes' object has no attribute 'content'``; reading
|
||||
``.raw`` unconditionally would return the wrapper object on 18+. The
|
||||
value is coerced here instead of at each call site so both work.
|
||||
"""
|
||||
self.ensure_one()
|
||||
raw = self.raw
|
||||
if not raw:
|
||||
return b''
|
||||
# 18.0+ wrapper: the bytes live behind `.content`.
|
||||
content = getattr(raw, 'content', None)
|
||||
if isinstance(content, (bytes, bytearray)):
|
||||
return bytes(content)
|
||||
if isinstance(raw, (bytes, bytearray)):
|
||||
return bytes(raw)
|
||||
if isinstance(raw, str):
|
||||
# A Binary field can hand back base64 text in some flows.
|
||||
return base64.b64decode(raw)
|
||||
raise ValueError(f"Unexpected attachment payload type: {type(raw).__name__}")
|
||||
|
||||
def _dn_ai_summary(self):
|
||||
"""Short human description used in the chat transcript."""
|
||||
return ', '.join(
|
||||
f"{attachment.name} ({format_size(attachment.file_size or 0)})"
|
||||
for attachment in self
|
||||
)
|
||||
95
dn_ai/models/res_config_settings.py
Normal file
95
dn_ai/models/res_config_settings.py
Normal file
@@ -0,0 +1,95 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from odoo import api, fields, models
|
||||
|
||||
from ..utils.openai_client import PROVIDER_PRESETS
|
||||
|
||||
PROVIDER_SELECTION = [(key, preset['label']) for key, preset in PROVIDER_PRESETS.items()]
|
||||
|
||||
|
||||
class ResConfigSettings(models.TransientModel):
|
||||
_inherit = 'res.config.settings'
|
||||
|
||||
dn_ai_provider = fields.Selection(
|
||||
PROVIDER_SELECTION, string="AI Provider", default='deepseek',
|
||||
config_parameter='dn_ai.provider',
|
||||
)
|
||||
dn_ai_base_url = fields.Char(
|
||||
string="API Base URL", config_parameter='dn_ai.base_url',
|
||||
help="Leave empty to use the default endpoint of the selected provider.",
|
||||
)
|
||||
dn_ai_api_key = fields.Char(
|
||||
string="API Key", config_parameter='dn_ai.api_key',
|
||||
help="Stored in a system parameter; never shown to non-admin users.",
|
||||
)
|
||||
dn_ai_model = fields.Char(
|
||||
string="Model", config_parameter='dn_ai.model',
|
||||
help="e.g. deepseek-chat, qwen-plus, gpt-4o-mini.",
|
||||
)
|
||||
dn_ai_temperature = fields.Float(
|
||||
string="Temperature", config_parameter='dn_ai.temperature',
|
||||
help="Leave empty for the provider default.",
|
||||
)
|
||||
dn_ai_max_tokens = fields.Integer(
|
||||
string="Max Tokens", config_parameter='dn_ai.max_tokens',
|
||||
)
|
||||
dn_ai_embedding_model = fields.Char(
|
||||
string="Embedding Model", config_parameter='dn_ai.embedding_model',
|
||||
help="Required for knowledge sources (RAG).",
|
||||
)
|
||||
dn_ai_max_rounds = fields.Integer(
|
||||
string="Max Tool Rounds", config_parameter='dn_ai.max_rounds', default=20,
|
||||
)
|
||||
dn_ai_max_tools_per_call = fields.Integer(
|
||||
string="Max Tools per Round", config_parameter='dn_ai.max_tools_per_call', default=20,
|
||||
)
|
||||
dn_ai_timeout = fields.Integer(
|
||||
string="Request Timeout (s)", config_parameter='dn_ai.timeout', default=120,
|
||||
)
|
||||
dn_ai_vision = fields.Selection(
|
||||
[('true', "Yes"), ('false', "No")],
|
||||
string="Send Images to the Model",
|
||||
config_parameter='dn_ai.vision',
|
||||
help="When enabled, uploaded images and PDFs are sent to the provider "
|
||||
"as multimodal content (or uploaded through its Files API). Turn "
|
||||
"it off for text-only endpoints: PDFs are then read locally and "
|
||||
"sent as text instead. Leave empty to follow the provider default.",
|
||||
)
|
||||
dn_ai_attachment_max_chars = fields.Integer(
|
||||
string="Attachment Text Limit", config_parameter='dn_ai.attachment_max_chars',
|
||||
default=40000,
|
||||
help="Maximum number of characters extracted from one uploaded file. "
|
||||
"Longer documents are truncated.",
|
||||
)
|
||||
|
||||
@api.model
|
||||
def default_get(self, fields_list):
|
||||
values = super().default_get(fields_list)
|
||||
# ``ir.config_parameter`` may hold a value that is not one of the keys
|
||||
# below -- an empty string written by an older build or by hand is the
|
||||
# common case. ``Selection.convert_to_cache`` raises on such a value and
|
||||
# the whole settings page dies with "Wrong value for
|
||||
# res.config.settings.dn_ai_vision". Fall back to "unset" instead, which
|
||||
# makes ``ai.provider.get_vision`` follow the provider preset.
|
||||
#
|
||||
# Note the membership test: ``False`` is the legitimate "unset" value and
|
||||
# an empty string is *not* falsy-insignificant here -- it is exactly the
|
||||
# value that used to crash the form.
|
||||
if 'dn_ai_vision' in values:
|
||||
allowed = self._fields['dn_ai_vision'].get_values(self.env)
|
||||
if values['dn_ai_vision'] not in allowed:
|
||||
values['dn_ai_vision'] = False
|
||||
return values
|
||||
|
||||
@api.onchange('dn_ai_provider')
|
||||
def _onchange_dn_ai_provider(self):
|
||||
preset = PROVIDER_PRESETS.get(self.dn_ai_provider)
|
||||
if preset:
|
||||
self.dn_ai_base_url = preset['base_url']
|
||||
self.dn_ai_model = preset['model']
|
||||
self.dn_ai_embedding_model = preset['embedding_model']
|
||||
# Keep the multimodal switch in sync with the chosen provider:
|
||||
# sending image blocks to a text-only endpoint fails every request.
|
||||
self.dn_ai_vision = 'true' if preset.get('vision') else 'false'
|
||||
|
||||
def action_dn_ai_test_connection(self):
|
||||
return self.env['dn.ai.provider'].action_test_connection()
|
||||
12
dn_ai/security/ai_security.xml
Normal file
12
dn_ai/security/ai_security.xml
Normal file
@@ -0,0 +1,12 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<odoo>
|
||||
<!-- Odoo 20 merged ir.model.access and ir.rule into 'ir.access', so access
|
||||
is fully declared in ir.access.csv. Like the Enterprise assistant, the
|
||||
module reuses the standard groups: any internal user may chat with an
|
||||
agent, only administrators may configure one. -->
|
||||
<record id="privilege_dn_ai" model="res.groups.privilege">
|
||||
<field name="name">AI Assistant</field>
|
||||
<field name="category_id" ref="base.module_category_productivity"/>
|
||||
<field name="sequence">50</field>
|
||||
</record>
|
||||
</odoo>
|
||||
13
dn_ai/security/ir.access.csv
Normal file
13
dn_ai/security/ir.access.csv
Normal file
@@ -0,0 +1,13 @@
|
||||
id,name,model_id,group_id/id,operation,domain
|
||||
access_ai_agent_user,ai.agent user,ai.agent,base.group_user,r,
|
||||
access_ai_agent_system,ai.agent system,ai.agent,base.group_system,crud,
|
||||
access_ai_skill_user,ai.skill user,ai.skill,base.group_user,r,
|
||||
access_ai_skill_system,ai.skill system,ai.skill,base.group_system,crud,
|
||||
access_ai_composer_user,ai.composer user,ai.composer,base.group_user,r,
|
||||
access_ai_composer_system,ai.composer system,ai.composer,base.group_system,crud,
|
||||
access_ai_prompt_button_user,ai.prompt.button user,ai.prompt.button,base.group_user,r,
|
||||
access_ai_prompt_button_system,ai.prompt.button system,ai.prompt.button,base.group_system,crud,
|
||||
access_ai_session_user,ai.session user,ai.session,base.group_user,crud,"[('create_uid', '=', user.id)]"
|
||||
access_ai_session_system,ai.session system,ai.session,base.group_system,crud,
|
||||
access_ai_session_event_user,ai.session.event user,ai.session.event,base.group_user,crud,"[('ai_session_id.create_uid', '=', user.id)]"
|
||||
access_ai_session_event_system,ai.session.event system,ai.session.event,base.group_system,crud,
|
||||
|
BIN
dn_ai/static/description/icon.png
Normal file
BIN
dn_ai/static/description/icon.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 1.2 KiB |
63
dn_ai/static/description/make_icon.py
Normal file
63
dn_ai/static/description/make_icon.py
Normal file
@@ -0,0 +1,63 @@
|
||||
import struct
|
||||
import zlib
|
||||
import os
|
||||
|
||||
# Minimal 256x256 RGBA PNG: a violet rounded square with a white "spark".
|
||||
W = H = 256
|
||||
BG = (124, 58, 237, 255) # violet-600
|
||||
FG = (255, 255, 255, 255)
|
||||
TRANSPARENT = (0, 0, 0, 0)
|
||||
|
||||
|
||||
def inside_rounded(x, y, r=44):
|
||||
if r <= x < W - r or r <= y < H - r:
|
||||
return 0 <= x < W and 0 <= y < H
|
||||
cx = r if x < r else W - 1 - r
|
||||
cy = r if y < r else H - 1 - r
|
||||
return (x - cx) ** 2 + (y - cy) ** 2 <= r * r
|
||||
|
||||
|
||||
def spark(x, y):
|
||||
"""A four-point star centred in the tile."""
|
||||
cx, cy = W / 2, H / 2
|
||||
dx, dy = abs(x - cx), abs(y - cy)
|
||||
# diamond body
|
||||
if dx + dy < 62:
|
||||
return True
|
||||
# thin cross arms
|
||||
if dx < 9 and dy < 104:
|
||||
return True
|
||||
if dy < 9 and dx < 104:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
rows = []
|
||||
for y in range(H):
|
||||
row = bytearray([0]) # PNG filter type 0
|
||||
for x in range(W):
|
||||
if not inside_rounded(x, y):
|
||||
row.extend(TRANSPARENT)
|
||||
elif spark(x, y):
|
||||
row.extend(FG)
|
||||
else:
|
||||
row.extend(BG)
|
||||
rows.append(bytes(row))
|
||||
|
||||
raw = b"".join(rows)
|
||||
|
||||
|
||||
def chunk(tag, data):
|
||||
return (struct.pack(">I", len(data)) + tag + data
|
||||
+ struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF))
|
||||
|
||||
|
||||
png = (b"\x89PNG\r\n\x1a\n"
|
||||
+ chunk(b"IHDR", struct.pack(">IIBBBBB", W, H, 8, 6, 0, 0, 0))
|
||||
+ chunk(b"IDAT", zlib.compress(raw, 9))
|
||||
+ chunk(b"IEND", b""))
|
||||
|
||||
out = os.path.join(os.path.dirname(os.path.abspath(__file__)), "icon.png")
|
||||
with open(out, "wb") as fh:
|
||||
fh.write(png)
|
||||
print("written", out, len(png), "bytes")
|
||||
71
dn_ai/static/src/_deprecated/attachment_utils.js
Normal file
71
dn_ai/static/src/_deprecated/attachment_utils.js
Normal file
@@ -0,0 +1,71 @@
|
||||
/** @odoo-module **/
|
||||
import { _t } from "@web/core/l10n/translation";
|
||||
|
||||
/**
|
||||
* Upload one file to an AI conversation.
|
||||
*
|
||||
* Uses a plain `fetch` with `FormData` because the payload is binary: the
|
||||
* regular RPC helper serialises JSON and cannot carry a file. The route is an
|
||||
* `http` one (not `jsonrpc`) and validates the CSRF token, hence the explicit
|
||||
* field below.
|
||||
*
|
||||
* @param {number} channelId
|
||||
* @param {File} file
|
||||
* @returns {Promise<object>} `{id, name, mimetype, size, kind, readable}`
|
||||
* @throws {Error} with a user-readable message on any failure
|
||||
*/
|
||||
export async function uploadDnAiAttachment(channelId, file) {
|
||||
const formData = new FormData();
|
||||
formData.append("csrf_token", odoo.csrf_token);
|
||||
formData.append("channel_id", channelId);
|
||||
formData.append("ufile", file, file.name);
|
||||
|
||||
const response = await fetch("/dn_ai/upload_attachment", {
|
||||
method: "POST",
|
||||
body: formData,
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(_t("The upload failed (HTTP %s).", response.status));
|
||||
}
|
||||
let data;
|
||||
try {
|
||||
data = await response.json();
|
||||
} catch {
|
||||
// A redirect to the login page yields HTML; surface that as an error
|
||||
// instead of a confusing "Unexpected token <" in the console.
|
||||
throw new Error(_t("The upload failed. Please reload the page and try again."));
|
||||
}
|
||||
if (data.error) {
|
||||
throw new Error(data.error);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Human readable file size, mirroring the server side helper.
|
||||
*/
|
||||
export function dnAiFormatSize(size) {
|
||||
const value = size || 0;
|
||||
if (value < 1024) {
|
||||
return `${value} B`;
|
||||
}
|
||||
if (value < 1024 * 1024) {
|
||||
return `${(value / 1024).toFixed(1)} kB`;
|
||||
}
|
||||
return `${(value / (1024 * 1024)).toFixed(1)} MB`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Icon name for a file, from a small set that exists in the Odoo 20 icon
|
||||
* wishlist (`fa-*` renders nothing here).
|
||||
*/
|
||||
export function dnAiFileIcon(attachment) {
|
||||
const mimetype = attachment.mimetype || "";
|
||||
if (mimetype.startsWith("image/")) {
|
||||
return "image";
|
||||
}
|
||||
if (mimetype === "application/pdf") {
|
||||
return "description";
|
||||
}
|
||||
return "attach_file";
|
||||
}
|
||||
453
dn_ai/static/src/_deprecated/chat.js
Normal file
453
dn_ai/static/src/_deprecated/chat.js
Normal file
@@ -0,0 +1,453 @@
|
||||
/** @odoo-module **/
|
||||
import {
|
||||
Component,
|
||||
markup,
|
||||
onMounted,
|
||||
onPatched,
|
||||
onWillStart,
|
||||
proxy,
|
||||
signal,
|
||||
t,
|
||||
useProps,
|
||||
} from "@odoo/owl";
|
||||
import { registry } from "@web/core/registry";
|
||||
import { useService } from "@web/core/utils/hooks";
|
||||
import { _t } from "@web/core/l10n/translation";
|
||||
|
||||
import { runDnAiClientTools } from "./client_tools";
|
||||
import {
|
||||
dnAiFileIcon,
|
||||
dnAiFormatSize,
|
||||
uploadDnAiAttachment,
|
||||
} from "./attachment_utils";
|
||||
|
||||
/**
|
||||
* Standalone AI chat panel.
|
||||
*
|
||||
* Kept outside of the Discuss internals on purpose: the agent loop posts plain
|
||||
* chatter messages, so any surface able to read a channel can render the
|
||||
* conversation. This gives us a stable place to show tool progress,
|
||||
* confirmation cards and question cards.
|
||||
*/
|
||||
export class DnAiChat extends Component {
|
||||
static template = "dn_ai.Chat";
|
||||
|
||||
props = useProps({
|
||||
action: t.object().optional(),
|
||||
actionId: t.any().optional(),
|
||||
className: t.string().optional(),
|
||||
state: t.object().optional(),
|
||||
// Chatter button can open the dialog on a specific conversation.
|
||||
channelId: t.number().optional(),
|
||||
// The floating panel renders its own title bar, so the panel inside it
|
||||
// hides this one to avoid two stacked headers.
|
||||
hideHeader: t.boolean().optional(),
|
||||
});
|
||||
|
||||
// Literal text in an Owl template is invisible to the PO extractor, so
|
||||
// every user-facing string goes through a getter backed by _t().
|
||||
get labels() {
|
||||
return {
|
||||
agentFallback: _t("AI"),
|
||||
emptyTitle: _t("Ask about your records, or tell me what to change."),
|
||||
emptyHint: _t("The assistant reads and writes data with your own access rights."),
|
||||
thinking: _t("Thinking…"),
|
||||
send: _t("Send"),
|
||||
attachFile: _t("Attach files"),
|
||||
removeFile: _t("Remove"),
|
||||
dropHint: _t("Drop the files here"),
|
||||
steps: _t("Working steps"),
|
||||
};
|
||||
}
|
||||
|
||||
// Owl 3 dropped `useRef`: refs are signals created up-front and bound from
|
||||
// the template with t-ref="this.scrollRef".
|
||||
scrollRef = signal.ref();
|
||||
fileInputRef = signal.ref();
|
||||
|
||||
setup() {
|
||||
this.orm = useService("orm");
|
||||
this.notification = useService("notification");
|
||||
|
||||
const params = this.props.action?.params || {};
|
||||
// The dialog passes the channel through sub-env because Owl 3 slots
|
||||
// have their own scope and cannot read the parent component's props.
|
||||
const envChannel = this.env.dnAiChannelId || false;
|
||||
this.state = proxy({
|
||||
channelId: envChannel || this.props.channelId || params.channel_id || false,
|
||||
agentName: "",
|
||||
messages: [],
|
||||
rows: [],
|
||||
input: "",
|
||||
busy: false,
|
||||
sessionId: false,
|
||||
pending: false,
|
||||
attachments: [],
|
||||
dragActive: false,
|
||||
stepsOpen: false,
|
||||
});
|
||||
|
||||
// A depth counter, not a boolean: `dragleave` fires every time the
|
||||
// pointer crosses a child element, which would flicker the overlay.
|
||||
this._dragDepth = 0;
|
||||
|
||||
// Scroll after Owl has actually written the transcript to the DOM.
|
||||
//
|
||||
// `onMounted` covers the first paint (the panel is re-created every
|
||||
// time it is opened, so this is the common case); `onPatched` covers
|
||||
// later refreshes. A bare `requestAnimationFrame` inside `refresh()`
|
||||
// is not enough: it races the initial render and measures the empty
|
||||
// list, which is exactly why the panel used to open at the very top.
|
||||
onMounted(() => this._scrollToBottomNow());
|
||||
onPatched(() => {
|
||||
if (this._scrollPending) {
|
||||
this._scrollPending = false;
|
||||
this._scrollToBottomNow();
|
||||
}
|
||||
});
|
||||
|
||||
onWillStart(async () => {
|
||||
await this.loadChannel();
|
||||
});
|
||||
}
|
||||
|
||||
async loadChannel() {
|
||||
if (!this.state.channelId) {
|
||||
const data = await this.orm.call("ai.agent", "dn_ai_get_default_channel", []);
|
||||
if (!data) {
|
||||
return;
|
||||
}
|
||||
this.state.channelId = data.channel_id;
|
||||
this.state.agentName = data.agent_name;
|
||||
this.state.sessionId = data.session_id;
|
||||
}
|
||||
await this.refresh();
|
||||
}
|
||||
|
||||
async refresh() {
|
||||
if (!this.state.channelId) {
|
||||
return;
|
||||
}
|
||||
const data = await this.orm.call("discuss.channel", "dn_ai_fetch_messages", [
|
||||
this.state.channelId,
|
||||
]);
|
||||
// Chatter bodies are sanitised server-side; `markup` keeps the HTML
|
||||
// instead of escaping the tags into visible text.
|
||||
// Only label the first message of a consecutive run by the same author,
|
||||
// like every other chat UI does.
|
||||
let previousAuthor = null;
|
||||
this.state.messages = data.messages.map((message) => {
|
||||
const showAuthor = message.author_name !== previousAuthor;
|
||||
previousAuthor = message.author_name;
|
||||
return {
|
||||
...message,
|
||||
body: markup(message.body || ""),
|
||||
attachments: message.attachments || [],
|
||||
is_step: Boolean(message.is_step),
|
||||
showAuthor,
|
||||
};
|
||||
});
|
||||
this.state.rows = this._buildRows(this.state.messages);
|
||||
this.state.agentName = data.agent_name || this.state.agentName;
|
||||
this.state.sessionId = data.session_id;
|
||||
this.state.pending = data.pending;
|
||||
this.scrollToBottom();
|
||||
}
|
||||
|
||||
/**
|
||||
* Fold runs of tool steps into groups.
|
||||
*
|
||||
* An agent answering a request like "create this sales order" posts ten
|
||||
* one-line progress messages ("搜索 Contact", "已创建 Product", …) and one
|
||||
* answer. Rendered as bubbles they bury the answer. A run of steps becomes
|
||||
* a single collapsible line: collapsed by default when it is in the past,
|
||||
* so the transcript reads as question → answer with the machinery tucked
|
||||
* away, but still one click from the full trail.
|
||||
*/
|
||||
_buildRows(messages) {
|
||||
const rows = [];
|
||||
let group = null;
|
||||
for (const message of messages) {
|
||||
if (message.is_step) {
|
||||
if (!group) {
|
||||
group = { isGroup: true, id: `steps-${message.id}`, steps: [] };
|
||||
rows.push(group);
|
||||
}
|
||||
group.steps.push(message);
|
||||
continue;
|
||||
}
|
||||
group = null;
|
||||
rows.push(message);
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
get stepRows() {
|
||||
return this.state.rows.filter((row) => row.isGroup);
|
||||
}
|
||||
|
||||
/**
|
||||
* A group is expanded when the agent is still working (its steps are the
|
||||
* only feedback) or when the user opened it by hand.
|
||||
*/
|
||||
isGroupOpen(group) {
|
||||
if (this.state.stepsOpen) {
|
||||
return true;
|
||||
}
|
||||
// The last row being a group means the turn is still in progress.
|
||||
return this.state.busy && this.state.rows[this.state.rows.length - 1] === group;
|
||||
}
|
||||
|
||||
toggleSteps() {
|
||||
this.state.stepsOpen = !this.state.stepsOpen;
|
||||
}
|
||||
|
||||
/**
|
||||
* Request a scroll to the latest message.
|
||||
*
|
||||
* The actual scroll happens in `onPatched`, once Owl has written the new
|
||||
* messages into the DOM — measuring any earlier gives the *previous*
|
||||
* transcript height. The rAF below is only a safety net for refreshes that
|
||||
* change nothing (no patch is scheduled then).
|
||||
*/
|
||||
scrollToBottom() {
|
||||
this._scrollPending = true;
|
||||
requestAnimationFrame(() => {
|
||||
if (this._scrollPending) {
|
||||
this._scrollPending = false;
|
||||
this._scrollToBottomNow();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
_scrollToBottomNow() {
|
||||
const el = this.scrollRef();
|
||||
if (!el) {
|
||||
return;
|
||||
}
|
||||
el.scrollTop = el.scrollHeight;
|
||||
// Messages arrive as HTML: images and web fonts can still change the
|
||||
// height right after the patch, which would leave us a few lines short
|
||||
// of the bottom. Re-apply on the next two frames; the operation is
|
||||
// idempotent and cheap.
|
||||
requestAnimationFrame(() => {
|
||||
el.scrollTop = el.scrollHeight;
|
||||
requestAnimationFrame(() => {
|
||||
el.scrollTop = el.scrollHeight;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
get placeholder() {
|
||||
return _t("Ask anything about your data…");
|
||||
}
|
||||
|
||||
get sendDisabled() {
|
||||
const hasContent = (this.state.input || "").trim() ||
|
||||
this.state.attachments.some((file) => !file.uploading);
|
||||
return Boolean(this.state.busy) || !hasContent;
|
||||
}
|
||||
|
||||
fileIcon(file) {
|
||||
return dnAiFileIcon(file);
|
||||
}
|
||||
|
||||
fileSize(file) {
|
||||
return dnAiFormatSize(file.size);
|
||||
}
|
||||
|
||||
async onKeydown(ev) {
|
||||
if (ev.key === "Enter" && !ev.shiftKey) {
|
||||
ev.preventDefault();
|
||||
await this.send();
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// attachments
|
||||
// ------------------------------------------------------------------
|
||||
openFilePicker() {
|
||||
const input = this.fileInputRef();
|
||||
if (input) {
|
||||
input.click();
|
||||
}
|
||||
}
|
||||
|
||||
async onFilePicked(ev) {
|
||||
const files = Array.from(ev.target.files || []);
|
||||
// Reset immediately: picking the same file twice must fire `change`
|
||||
// again, which it does not while the value is kept.
|
||||
ev.target.value = "";
|
||||
await this.uploadFiles(files);
|
||||
}
|
||||
|
||||
onPaste(ev) {
|
||||
// Screenshots are pasted, not selected. Handling `paste` here is the
|
||||
// only way to attach one without a detour through the file system.
|
||||
const items = Array.from(ev.clipboardData?.items || []);
|
||||
const files = items
|
||||
.filter((item) => item.kind === "file")
|
||||
.map((item) => item.getAsFile())
|
||||
.filter(Boolean);
|
||||
if (files.length) {
|
||||
ev.preventDefault();
|
||||
this.uploadFiles(files);
|
||||
}
|
||||
}
|
||||
|
||||
onDragOver(ev) {
|
||||
if (!ev.dataTransfer?.types?.includes("Files")) {
|
||||
return;
|
||||
}
|
||||
this._dragDepth += 1;
|
||||
this.state.dragActive = true;
|
||||
}
|
||||
|
||||
onDragLeave() {
|
||||
this._dragDepth = Math.max(0, this._dragDepth - 1);
|
||||
if (!this._dragDepth) {
|
||||
this.state.dragActive = false;
|
||||
}
|
||||
}
|
||||
|
||||
async onDrop(ev) {
|
||||
this._dragDepth = 0;
|
||||
this.state.dragActive = false;
|
||||
if (this.state.busy) {
|
||||
return;
|
||||
}
|
||||
const files = Array.from(ev.dataTransfer?.files || []);
|
||||
if (files.length) {
|
||||
await this.uploadFiles(files);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload every file, showing a chip per file straight away.
|
||||
*
|
||||
* The chip appears *before* the request completes so a slow upload still
|
||||
* gives feedback; it is marked `uploading` until the server answers, and is
|
||||
* dropped again if that answer is an error.
|
||||
*/
|
||||
async uploadFiles(files) {
|
||||
if (!files.length || !this.state.channelId) {
|
||||
return;
|
||||
}
|
||||
const pending = files.map((file) => ({
|
||||
id: `tmp-${Date.now()}-${file.name}-${Math.random().toString(36).slice(2, 8)}`,
|
||||
name: file.name,
|
||||
size: file.size,
|
||||
mimetype: file.type || "",
|
||||
uploading: true,
|
||||
}));
|
||||
this.state.attachments.push(...pending);
|
||||
|
||||
await Promise.all(pending.map(async (placeholder, index) => {
|
||||
try {
|
||||
const attachment = await uploadDnAiAttachment(this.state.channelId, files[index]);
|
||||
const target = this.state.attachments.find((item) => item.id === placeholder.id);
|
||||
if (!target) {
|
||||
return; // removed by the user while uploading
|
||||
}
|
||||
Object.assign(target, {
|
||||
id: attachment.id,
|
||||
name: attachment.name,
|
||||
size: attachment.size,
|
||||
mimetype: attachment.mimetype,
|
||||
uploading: false,
|
||||
});
|
||||
} catch (error) {
|
||||
this.removeAttachment(placeholder.id);
|
||||
this.notification.add(error.message || _t("The upload failed."), {
|
||||
type: "danger",
|
||||
});
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
removeAttachment(id) {
|
||||
this.state.attachments = this.state.attachments.filter((file) => file.id !== id);
|
||||
}
|
||||
|
||||
async send() {
|
||||
const body = (this.state.input || "").trim();
|
||||
const uploaded = this.state.attachments.filter((file) => !file.uploading);
|
||||
if ((!body && !uploaded.length) || this.state.busy) {
|
||||
return;
|
||||
}
|
||||
if (this.state.attachments.some((file) => file.uploading)) {
|
||||
this.notification.add(_t("Please wait for the uploads to finish."), {
|
||||
type: "warning",
|
||||
});
|
||||
return;
|
||||
}
|
||||
this.state.busy = true;
|
||||
this.state.input = "";
|
||||
// Clear the chips optimistically: the message is about to be posted and
|
||||
// the files become part of the transcript, so keeping them in the input
|
||||
// would let the user send them twice.
|
||||
this.state.attachments = [];
|
||||
try {
|
||||
const result = await this.orm.call("ai.session", "dn_ai_send_message", [
|
||||
this.state.channelId,
|
||||
body,
|
||||
], {
|
||||
// keyword argument of the model method: the files the model has
|
||||
// to read for this turn.
|
||||
attachment_ids: uploaded.map((file) => file.id),
|
||||
});
|
||||
this.state.sessionId = result.session_id;
|
||||
this.state.pending = result.pending;
|
||||
await this.refresh();
|
||||
await this._runClientTools(result.client_tools);
|
||||
} catch (error) {
|
||||
// Put the draft back so a failed turn does not silently eat the
|
||||
// message (or the attached files) the user just composed.
|
||||
this.state.input = body;
|
||||
this.state.attachments = uploaded;
|
||||
this.notification.add(error.message || _t("The AI request failed."), {
|
||||
type: "danger",
|
||||
});
|
||||
} finally {
|
||||
this.state.busy = false;
|
||||
}
|
||||
}
|
||||
|
||||
async onChoice(value) {
|
||||
if (this.state.busy || !this.state.sessionId) {
|
||||
return;
|
||||
}
|
||||
this.state.busy = true;
|
||||
try {
|
||||
const kind = this.state.pending?.type === "question" ? "question" : "confirmation";
|
||||
const result = await this.orm.call("ai.session", "dn_ai_resume", [
|
||||
this.state.sessionId,
|
||||
{ kind, value },
|
||||
]);
|
||||
this.state.pending = result.pending;
|
||||
await this.refresh();
|
||||
await this._runClientTools(result.client_tools);
|
||||
} catch (error) {
|
||||
this.notification.add(error.message || _t("The AI request failed."), {
|
||||
type: "danger",
|
||||
});
|
||||
} finally {
|
||||
this.state.busy = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the browser actions the server queued for this turn.
|
||||
*
|
||||
* The transcript is refreshed *before* this runs on purpose: opening a
|
||||
* view unmounts the panel, and any state update after that point is lost.
|
||||
*/
|
||||
async _runClientTools(clientTools) {
|
||||
if (!clientTools || !clientTools.length) {
|
||||
return;
|
||||
}
|
||||
await runDnAiClientTools(this.env, clientTools);
|
||||
}
|
||||
}
|
||||
|
||||
registry.category("actions").add("dn_ai.chat", DnAiChat);
|
||||
352
dn_ai/static/src/_deprecated/chat.scss
Normal file
352
dn_ai/static/src/_deprecated/chat.scss
Normal file
@@ -0,0 +1,352 @@
|
||||
.o_dn_ai_chat {
|
||||
min-height: 0;
|
||||
// Positioning context for the drop overlay.
|
||||
position: relative;
|
||||
|
||||
.o_dn_ai_chat_messages {
|
||||
background-color: var(--body-bg, #fff);
|
||||
// A flex child does not shrink below its content by default, so without
|
||||
// `min-height: 0` the message list grows and the scroll container is
|
||||
// the panel — `scrollTop` on this element then does nothing.
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.o_dn_ai_bubble {
|
||||
max-width: 80%;
|
||||
white-space: normal;
|
||||
overflow-wrap: anywhere;
|
||||
|
||||
.o_dn_ai_body {
|
||||
:last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
}
|
||||
|
||||
// A table or a code block needs more room than a sentence, and the
|
||||
// bubble above is capped at 80% to keep chat bubbles readable. Widening
|
||||
// only the bubbles that hold one keeps prose narrow without squeezing
|
||||
// the content that actually needs the width.
|
||||
&:has(.o_dn_ai_table_wrap),
|
||||
&:has(.o_dn_ai_code) {
|
||||
max-width: 100%;
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------
|
||||
// rendered markdown
|
||||
// ---------------------------------------------------------------
|
||||
.o_dn_ai_body {
|
||||
line-height: 1.55;
|
||||
|
||||
// -- tables -------------------------------------------------
|
||||
.o_dn_ai_table_wrap {
|
||||
// Wide tables scroll sideways instead of forcing the panel to
|
||||
// grow: the chat column is narrow by design.
|
||||
overflow-x: auto;
|
||||
margin: 0.5rem 0;
|
||||
border: 1px solid var(--border-color, #dee2e6);
|
||||
border-radius: 0.375rem;
|
||||
}
|
||||
|
||||
.o_dn_ai_table {
|
||||
width: 100%;
|
||||
margin: 0;
|
||||
border-collapse: collapse;
|
||||
font-size: 0.875rem;
|
||||
// Numbers line up under each other, which is the whole point of
|
||||
// showing an order line table.
|
||||
font-variant-numeric: tabular-nums;
|
||||
|
||||
th,
|
||||
td {
|
||||
padding: 0.375rem 0.625rem;
|
||||
border-bottom: 1px solid var(--border-color, #dee2e6);
|
||||
text-align: left;
|
||||
vertical-align: top;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
thead th {
|
||||
background-color: var(--o-gray-200, #eef1f3);
|
||||
font-weight: 600;
|
||||
// The header stays put while a long table scrolls under it.
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
tbody tr:last-child td {
|
||||
border-bottom: 0;
|
||||
}
|
||||
|
||||
tbody tr:hover {
|
||||
background-color: rgba(0, 0, 0, 0.03);
|
||||
}
|
||||
}
|
||||
|
||||
// -- headings ------------------------------------------------
|
||||
.o_dn_ai_h {
|
||||
font-size: 0.9375rem;
|
||||
font-weight: 600;
|
||||
margin: 0.75rem 0 0.375rem;
|
||||
|
||||
&:first-child {
|
||||
margin-top: 0;
|
||||
}
|
||||
}
|
||||
|
||||
// -- lists ---------------------------------------------------
|
||||
ul,
|
||||
ol {
|
||||
margin: 0.375rem 0;
|
||||
padding-left: 1.25rem;
|
||||
}
|
||||
|
||||
li {
|
||||
margin-bottom: 0.125rem;
|
||||
}
|
||||
|
||||
// -- quotes, rules -------------------------------------------
|
||||
blockquote {
|
||||
margin: 0.5rem 0;
|
||||
padding: 0.25rem 0.75rem;
|
||||
border-left: 3px solid var(--o-brand-primary, #714b67);
|
||||
background-color: rgba(0, 0, 0, 0.03);
|
||||
color: var(--body-color, #212529);
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
hr {
|
||||
margin: 0.75rem 0;
|
||||
border-color: var(--border-color, #dee2e6);
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
// -- code ----------------------------------------------------
|
||||
code.ai-code-response {
|
||||
padding: 0.1em 0.35em;
|
||||
font-size: 0.85em;
|
||||
background-color: rgba(0, 0, 0, 0.07);
|
||||
border-radius: 0.25rem;
|
||||
}
|
||||
|
||||
.o_dn_ai_code pre,
|
||||
pre.ai-pre-response {
|
||||
margin: 0.5rem 0;
|
||||
padding: 0.625rem 0.75rem;
|
||||
background-color: rgba(0, 0, 0, 0.05);
|
||||
border-radius: 0.375rem;
|
||||
font-size: 0.8125rem;
|
||||
overflow-x: auto;
|
||||
white-space: pre;
|
||||
}
|
||||
|
||||
a {
|
||||
text-decoration: underline;
|
||||
}
|
||||
}
|
||||
|
||||
// The user's own bubble is dark, so the same rendered markdown has to
|
||||
// invert its surfaces instead of stacking grey on grey.
|
||||
.o_dn_ai_bubble.bg-primary {
|
||||
.o_dn_ai_table {
|
||||
th,
|
||||
td {
|
||||
border-color: rgba(255, 255, 255, 0.25);
|
||||
}
|
||||
|
||||
thead th {
|
||||
background-color: rgba(255, 255, 255, 0.15);
|
||||
}
|
||||
|
||||
tbody tr:hover {
|
||||
background-color: rgba(255, 255, 255, 0.08);
|
||||
}
|
||||
}
|
||||
|
||||
.o_dn_ai_table_wrap {
|
||||
border-color: rgba(255, 255, 255, 0.25);
|
||||
}
|
||||
|
||||
blockquote {
|
||||
border-left-color: rgba(255, 255, 255, 0.6);
|
||||
background-color: rgba(255, 255, 255, 0.1);
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
code.ai-code-response,
|
||||
.o_dn_ai_code pre,
|
||||
pre.ai-pre-response {
|
||||
background-color: rgba(255, 255, 255, 0.15);
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
hr {
|
||||
border-color: rgba(255, 255, 255, 0.4);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------
|
||||
// tool steps
|
||||
// ---------------------------------------------------------------
|
||||
.o_dn_ai_steps {
|
||||
margin: 0 0 0.75rem;
|
||||
|
||||
.o_dn_ai_steps_head {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.375rem;
|
||||
padding: 0.125rem 0.5rem;
|
||||
border: 1px solid var(--border-color, #dee2e6);
|
||||
border-radius: 1rem;
|
||||
background-color: transparent;
|
||||
color: var(--text-muted, #6c757d);
|
||||
font-size: 0.8125rem;
|
||||
line-height: 1.4;
|
||||
|
||||
&:hover {
|
||||
background-color: var(--o-gray-200, #eef1f3);
|
||||
color: var(--body-color, #212529);
|
||||
}
|
||||
}
|
||||
|
||||
.o_dn_ai_steps_icon {
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.o_dn_ai_steps_count {
|
||||
padding: 0 0.375rem;
|
||||
border-radius: 0.75rem;
|
||||
background-color: var(--o-gray-300, #dee2e6);
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
// The trail runs down a vertical line, like a build log: each entry is
|
||||
// a completed step, not a message from the assistant.
|
||||
.o_dn_ai_steps_body {
|
||||
margin-top: 0.5rem;
|
||||
padding-left: 0.75rem;
|
||||
border-left: 2px solid var(--border-color, #dee2e6);
|
||||
|
||||
.o_dn_ai_step {
|
||||
margin-bottom: 0.25rem;
|
||||
font-size: 0.8125rem;
|
||||
color: var(--text-muted, #6c757d);
|
||||
|
||||
// The server emits each step as a div with an icon; flatten it
|
||||
// into a single muted line so ten of them stay scannable.
|
||||
.o_ai_tool_summary {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.375rem;
|
||||
}
|
||||
|
||||
&:last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.o_dn_ai_textarea {
|
||||
resize: none;
|
||||
}
|
||||
|
||||
// Material Symbols replaced FontAwesome in Odoo 20; there is no built-in
|
||||
// `fa-spin` equivalent, so the "thinking" icon needs its own animation.
|
||||
.o_dn_ai_spin {
|
||||
display: inline-block;
|
||||
animation: o_dn_ai_spin 1s linear infinite;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------
|
||||
// attachments
|
||||
// ---------------------------------------------------------------
|
||||
.o_dn_ai_attach {
|
||||
// Sits inside the input group; keeping the border thin avoids the
|
||||
// "double button" look next to the textarea.
|
||||
border-color: var(--border-color, #dee2e6);
|
||||
}
|
||||
|
||||
.o_dn_ai_file_input {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.o_dn_ai_message_files {
|
||||
.o_dn_ai_file_card {
|
||||
background-color: rgba(0, 0, 0, 0.06);
|
||||
border: 1px solid rgba(0, 0, 0, 0.08);
|
||||
max-width: 320px;
|
||||
|
||||
&:hover {
|
||||
background-color: rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
}
|
||||
|
||||
.o_dn_ai_file_name {
|
||||
// The name is the only part allowed to shrink; icon and size must
|
||||
// stay readable on long file names.
|
||||
min-width: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.o_dn_ai_pending_files {
|
||||
.o_dn_ai_chip {
|
||||
background-color: var(--o-gray-200, #eef1f3);
|
||||
border: 1px solid var(--border-color, #dee2e6);
|
||||
max-width: 260px;
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
.o_dn_ai_chip_loading {
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
.o_dn_ai_chip_name {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.o_dn_ai_chip_remove {
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
line-height: 1;
|
||||
|
||||
&:hover {
|
||||
color: var(--o-danger, #dc3545);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
&.o_dn_ai_dragging .o_dn_ai_chat_input {
|
||||
// A dashed outline on the input area alone would be too subtle to
|
||||
// notice while dragging; the overlay below makes it unmistakable.
|
||||
border-color: var(--o-brand-primary, #714b67);
|
||||
}
|
||||
|
||||
.o_dn_ai_drop_hint {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background-color: rgba(113, 75, 103, 0.08);
|
||||
border: 2px dashed var(--o-brand-primary, #714b67);
|
||||
border-radius: 0.5rem;
|
||||
color: var(--o-brand-primary, #714b67);
|
||||
font-weight: 600;
|
||||
// The overlay must not swallow the drop event itself, or the browser
|
||||
// opens the file in a new tab instead of uploading it.
|
||||
pointer-events: none;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes o_dn_ai_spin {
|
||||
from {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
145
dn_ai/static/src/_deprecated/chat.xml
Normal file
145
dn_ai/static/src/_deprecated/chat.xml
Normal file
@@ -0,0 +1,145 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<templates xml:space="preserve">
|
||||
|
||||
<t t-name="dn_ai.Chat">
|
||||
<div t-attf-class="o_dn_ai_chat d-flex flex-column h-100 {{ this.state.dragActive ? 'o_dn_ai_dragging' : '' }}"
|
||||
t-on-dragover.prevent="this.onDragOver"
|
||||
t-on-dragleave.prevent="this.onDragLeave"
|
||||
t-on-drop.prevent="this.onDrop">
|
||||
<!-- Odoo 20 dropped FontAwesome: icons are Material Symbols
|
||||
(`class="oi"` + `data-icon`). `fa fa-*` renders nothing. -->
|
||||
<div t-if="!this.props.hideHeader"
|
||||
class="o_dn_ai_chat_header d-flex align-items-center px-3 py-2 border-bottom">
|
||||
<span class="oi oi-filled me-2 text-primary" data-icon="wand_stars"/>
|
||||
<span class="fw-bold" t-out="this.state.agentName || this.labels.agentFallback"/>
|
||||
</div>
|
||||
|
||||
<div class="o_dn_ai_chat_messages flex-grow-1 overflow-auto px-3 py-3" t-ref="this.scrollRef">
|
||||
<div t-if="!this.state.messages.length" class="text-center text-muted py-5">
|
||||
<span class="oi d-block mb-3 opacity-50" style="font-size: 3rem" data-icon="forum"/>
|
||||
<p class="mb-1" t-out="this.labels.emptyTitle"/>
|
||||
<p class="small mb-0" t-out="this.labels.emptyHint"/>
|
||||
</div>
|
||||
<t t-foreach="this.state.rows" t-as="row" t-key="row.id">
|
||||
<!-- A run of tool progress lines, folded into one
|
||||
collapsible strip. Expanded while the agent is still
|
||||
working, collapsed once the answer has landed. -->
|
||||
<div t-if="row.isGroup" class="o_dn_ai_steps">
|
||||
<button type="button"
|
||||
class="o_dn_ai_steps_head"
|
||||
t-on-click="this.toggleSteps">
|
||||
<span class="oi o_dn_ai_steps_icon"
|
||||
t-attf-data-icon="{{ this.isGroupOpen(row) ? 'expand_less' : 'expand_more' }}"/>
|
||||
<span t-out="this.labels.steps"/>
|
||||
<span class="o_dn_ai_steps_count" t-out="row.steps.length"/>
|
||||
</button>
|
||||
<div t-if="this.isGroupOpen(row)" class="o_dn_ai_steps_body">
|
||||
<t t-foreach="row.steps" t-as="step" t-key="step.id">
|
||||
<div class="o_dn_ai_step" t-out="step.body"/>
|
||||
</t>
|
||||
</div>
|
||||
</div>
|
||||
<div t-else=""
|
||||
t-attf-class="o_dn_ai_message mb-3 d-flex {{ row.is_agent ? 'justify-content-start' : 'justify-content-end' }}">
|
||||
<div t-attf-class="o_dn_ai_bubble p-2 px-3 rounded-3 {{ row.is_agent ? 'bg-body-tertiary' : 'bg-primary text-white' }}">
|
||||
<div class="o_dn_ai_author small opacity-75 mb-1" t-if="row.showAuthor" t-out="row.author_name"/>
|
||||
<div class="o_dn_ai_body" t-if="row.body" t-out="row.body"/>
|
||||
<!-- Attachments travel with the transcript, not
|
||||
inside the body: extracted text can be tens of
|
||||
thousands of characters and has no business in
|
||||
a chat bubble. -->
|
||||
<div t-if="row.attachments and row.attachments.length"
|
||||
t-attf-class="o_dn_ai_message_files d-flex flex-column gap-1 {{ row.body ? 'mt-2' : '' }}">
|
||||
<t t-foreach="row.attachments" t-as="file" t-key="file.id">
|
||||
<a class="o_dn_ai_file_card d-flex align-items-center text-decoration-none rounded-2 px-2 py-1"
|
||||
t-attf-class="{{ row.is_agent ? 'text-reset' : 'text-white' }}"
|
||||
t-att-href="file.url"
|
||||
t-att-title="file.name"
|
||||
target="_blank" rel="noopener">
|
||||
<span class="oi oi-fw me-2" t-att-data-icon="this.fileIcon(file)"/>
|
||||
<span class="o_dn_ai_file_name text-truncate" t-out="file.name"/>
|
||||
<span class="small opacity-75 ms-2 flex-shrink-0" t-out="this.fileSize(file)"/>
|
||||
</a>
|
||||
</t>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</t>
|
||||
<div t-if="this.state.busy" class="text-muted small">
|
||||
<span class="oi me-1 o_dn_ai_spin" data-icon="progress_activity"/><t t-out="this.labels.thinking"/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="o_dn_ai_chat_pending border-top px-3 py-2" t-if="this.state.pending">
|
||||
<div class="small text-muted mb-1" t-out="this.state.pending.body"/>
|
||||
<div class="d-flex flex-wrap gap-2">
|
||||
<t t-foreach="this.state.pending.choices" t-as="choice" t-key="choice.value">
|
||||
<button type="button"
|
||||
t-attf-class="btn btn-sm o_dn_ai_choice {{ choice.value === 'decline' ? 'btn-outline-secondary' : 'btn-primary' }}"
|
||||
t-att-disabled="this.state.busy"
|
||||
t-on-click="() => this.onChoice(choice.value)"
|
||||
t-out="choice.label"/>
|
||||
</t>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="o_dn_ai_chat_input border-top p-2">
|
||||
<!-- Files picked but not sent yet. Shown above the textarea so
|
||||
the user sees exactly what will travel with the next
|
||||
message, and can drop one without clearing everything. -->
|
||||
<div t-if="this.state.attachments.length"
|
||||
class="o_dn_ai_pending_files d-flex flex-wrap gap-2 mb-2">
|
||||
<t t-foreach="this.state.attachments" t-as="file" t-key="file.id">
|
||||
<div t-attf-class="o_dn_ai_chip d-flex align-items-center rounded-pill px-2 py-1 {{ file.uploading ? 'o_dn_ai_chip_loading' : '' }}">
|
||||
<span class="oi oi-fw me-1" t-att-data-icon="this.fileIcon(file)"/>
|
||||
<span class="o_dn_ai_chip_name text-truncate" t-out="file.name"/>
|
||||
<span t-if="!file.uploading" class="small opacity-75 ms-2" t-out="this.fileSize(file)"/>
|
||||
<span t-if="file.uploading" class="oi oi-fw o_dn_ai_spin ms-2" data-icon="progress_activity"/>
|
||||
<button type="button"
|
||||
class="btn btn-link btn-sm p-0 ms-2 o_dn_ai_chip_remove"
|
||||
t-att-title="this.labels.removeFile"
|
||||
t-on-click="() => this.removeAttachment(file.id)">
|
||||
<span class="oi" data-icon="close"/>
|
||||
</button>
|
||||
</div>
|
||||
</t>
|
||||
</div>
|
||||
|
||||
<div class="input-group">
|
||||
<button type="button"
|
||||
class="btn btn-outline-secondary o_dn_ai_attach"
|
||||
t-att-disabled="this.state.busy || !this.state.channelId"
|
||||
t-att-title="this.labels.attachFile"
|
||||
t-on-click="this.openFilePicker">
|
||||
<span class="oi" data-icon="attach_file"/>
|
||||
</button>
|
||||
<textarea class="form-control o_dn_ai_textarea"
|
||||
rows="2"
|
||||
t-att-placeholder="this.placeholder"
|
||||
t-model.proxy="this.state.input"
|
||||
t-on-keydown="this.onKeydown"
|
||||
t-on-paste="this.onPaste"/>
|
||||
<button type="button"
|
||||
class="btn btn-primary"
|
||||
t-att-disabled="this.sendDisabled"
|
||||
t-att-title="this.labels.send"
|
||||
t-on-click="this.send">
|
||||
<span class="oi" data-icon="send"/>
|
||||
</button>
|
||||
</div>
|
||||
<!-- The native input lives outside the flex row: it must never
|
||||
take space, and a hidden `display:none` input can still be
|
||||
clicked programmatically in every browser we target. -->
|
||||
<input type="file" multiple="multiple"
|
||||
class="o_dn_ai_file_input"
|
||||
t-ref="this.fileInputRef"
|
||||
t-on-change="this.onFilePicked"/>
|
||||
|
||||
<div t-if="this.state.dragActive" class="o_dn_ai_drop_hint">
|
||||
<span class="oi me-2" data-icon="attach_file"/><t t-out="this.labels.dropHint"/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</t>
|
||||
|
||||
</templates>
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user