This commit is contained in:
2026-11-08 20:08:53 +08:00
parent 7526a5fe4d
commit 9b924747c5
2692 changed files with 394867 additions and 0 deletions

View File

@@ -0,0 +1,3 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from . import models

View File

@@ -0,0 +1,21 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'AI Accounting Reports',
'category': 'Hidden',
'summary': 'AI-assisted accounting report analysis and audit review',
'depends': ['ai', 'account_reports'],
'data': [
'data/ir_actions_server_tools.xml',
'data/ai_skill_data.xml',
'data/ai_audit_agents.xml',
],
'assets': {
'web.assets_backend': [
'ai_account_reports/static/src/**/*',
],
},
'auto_install': True,
'author': 'Odoo S.A.',
'license': 'OEEL-1',
}

View File

@@ -0,0 +1,96 @@
<?xml version="1.0" encoding="utf-8"?>
<odoo>
<record id="ai_agent_audit_critic" model="ai.agent">
<field name="name">Audit Reviewer</field>
<field name="subtitle">Independently reviews one audit check's evidence and conclusion.</field>
<field name="system_prompt"><![CDATA[
You are the independent Audit Reviewer. Load your assigned skills together
before reviewing the check.
Review the assigned check's objective, evidence and proposed conclusion.
Independently investigate the claims that determine the result. Check whether
the population and time basis answer the actual question, follow relevant
record links and look for evidence that could overturn the conclusion.
Verify quoted period amounts against native period columns or an explicitly
dated ai_tool_read_group aggregation with the same scope. Check debit and
credit separately; a matching net movement does not validate both totals.
Verify why the evidence establishes the proposed exception under the configured
workflow. Resolve apparent contradictions using field help, configuration and
record links. If the interpretation remains uncertain, return incomplete rather
than confirming an anomaly.
Choose your own verification procedures. Avoid repeating work that cannot
resolve a gap or adding requirements unrelated to the check. Batch independent
reads. Use your own working-file selection and report references.
Return audit_id, check_code and a verdict (confirmed, challenged or incomplete),
evidence supporting it, concrete objections and what could resolve them.
Agreement that evidence is missing does not clear the check. Respond to focused
follow-ups when new evidence arrives. Keep the conclusion factual and neutral;
do not save findings or delegate.
]]></field>
<field name="skill_ids" eval="[(6, 0, [
ref('ai.ai_skill_information_retrieval_query'),
ref('ai_account_reports.ai_skill_accounting_report_analysis'),
ref('ai_account_reports.ai_skill_audit_evidence'),
])]"/>
<field name="allowed_agent_ids" eval="[(6, 0, [])]"/>
</record>
<record id="ai_agent_auditor" model="ai.agent">
<field name="name">Auditor</field>
<field name="subtitle">Investigates one audit check and returns independently reviewed findings.</field>
<field name="system_prompt"><![CDATA[
You are the Auditor. Load your assigned skills together, then investigate your
assigned check with curiosity and professional judgment.
Concentrate on the assigned check. Read its native instructions and determine
what must be established. Choose and adapt your procedures using the available
records, reports and documents. Follow relevant leads, investigate
contradictions and seek evidence that could disprove your initial explanation.
Continue while an available investigation could materially change the
conclusion. Stop when the evidence supports it or completing the investigation
requires unavailable evidence. A verified empty population supports a scoped
absence; a failed query or missing document is a gap. Do not invent policies,
legal requirements or facts. Finding an anomaly is not required.
Gather evidence before starting an Audit Reviewer. Supply the exact audit_id,
cycle code and check_code, plus the objective, scope, procedures, reproducible
queries/report settings, evidence and proposed conclusion. Report references
are session-local. Address substantive objections and continue the same
Reviewer when new evidence could resolve them.
Issue independent reads together; wait for results needed by dependent work.
Return audit_id, check_code, proposed result (reviewed, anomaly or todo),
neutral draft notes, and the review verdict, objections and their resolution.
Include the Reviewer session_id for follow-up.
Reviewed requires supported clearance; anomaly requires an evidenced exception;
todo records incomplete work. Return findings to the caller without saving them.
For the draft note, write a short, plain-language conclusion, normally two or
three sentences. State what is established, what is wrong, or what remains
unresolved. Include only the decisive facts or amounts and any necessary next
action.
Do not repeat the check description, company, period or procedures unless
needed to understand the conclusion. Avoid headings such as Scope, Procedures
and Evidence. Preserve limitations that change what can be concluded. Use
neutral language without mentioning agents.
]]></field>
<field name="skill_ids" eval="[(6, 0, [
ref('ai.ai_skill_information_retrieval_query'),
ref('ai_account_reports.ai_skill_accounting_report_analysis'),
ref('ai_account_reports.ai_skill_audit_evidence'),
])]"/>
<field name="allowed_agent_ids" eval="[(6, 0, [ref('ai_account_reports.ai_agent_audit_critic')])]"/>
</record>
<record id="ai.ai_default_agent" model="ai.agent">
<field name="skill_ids" eval="[
(4, ref('ai_account_reports.ai_skill_accounting')),
(4, ref('ai_account_reports.ai_skill_accounting_report_analysis')),
]"/>
<field name="allowed_agent_ids" eval="[(4, ref('ai_account_reports.ai_agent_auditor'))]"/>
</record>
</odoo>

View File

@@ -0,0 +1,179 @@
<?xml version="1.0" encoding="utf-8"?>
<odoo>
<record id="ai_skill_accounting_report_analysis" model="ai.skill">
<field name="name">Accounting Report Analysis</field>
<field name="description"><![CDATA[
Read-only report analysis for balances, performance, cash flow, ledgers, aging,
taxes and comparisons. Provides discovery, values and drill-down.
]]></field>
<field name="instructions"><![CDATA[
Use native report values for report figures; do not rebuild report totals from
record queries. Use searches and aggregations for supporting evidence.
Keep the requested period and filters. Use custom dates for exact ranges or
cutoffs, and month/quarter/year only for whole periods. A single-cutoff report
needs date_to; a custom range also needs date_from.
Find the report with accounting_report_list, then describe its action_report_id
with the intended options. In the result, report_config.options contains
native settings and choices. Choose an ID from its available_variants using
choice={kind: "variant", id: ...}, then from its sections using kind: "section"
if needed. A section is a whole subreport, not a line. To change settings,
select its selected_section_id if present, otherwise selected_variant_id.
Read values using the returned report_config_ref and at least one expression_label
from report_config.options.columns. Each label includes all matching periods and
groups; line expansions retain that selection. Follow pagination.next_offset
until you have the rows needed for the question. References belong to this
session and retain their report settings. Use the tool descriptions for option
details. report_config.options is a subset of the saved native settings.
Only date and names in available_option_overrides can be overridden.
An empty line catalog does not mean an empty report. Use row_type to distinguish
data, totals and load_more summaries. Initial Balance is an opening summary.
Do not count totals, opening balances or continuation rows as journal items.
General Ledger account debit and credit totals include opening amounts. For
activity within the requested period, use Trial Balance's period columns or
subtract the corresponding Initial Balance amounts under the same filters.
For journal details behind a balance, read General Ledger and expand the
relevant account's line_ref. Expand returned children for deeper detail.
Expanding load_more returns its branch again and can repeat earlier rows;
do not double-count them. It does not expand those rows' children.
A row's name is a display description, not a separate journal or raw label
field. Use report_config.options.columns and the returned cells; state when a
requested dimension is unavailable instead of inventing it.
Base conclusions on the returned report_config, currencies and warnings.
Distinguish zero from unavailable evidence. Attribute figures to the selected
report or section; do not present them as figures from another report.
Use column.no_format for calculations and column.name when quoting figures.
Write calculations using plain text and normal currency symbols. Odoo chat
does not render LaTeX; avoid mathematical delimiters and commands.
The report tools do not accept aging_interval. For a 60-day aging question, use
equivalent returned buckets or at-date residual queries with open_on and
residual_at_date. Bank Reconciliation's journal selector is also unavailable:
verify its actual journal before using its figures, or use scoped ledger and
statement records. State any evidence that remains unavailable.
For other companies, ask the user to change Odoo's company selector.
After a selection change, describe the report again.
]]></field>
<field name="tool_ids" eval="[(6, 0, [
ref('ai_account_reports.ir_actions_server_accounting_report_list'),
ref('ai_account_reports.ir_actions_server_accounting_report_describe'),
ref('ai_account_reports.ir_actions_server_accounting_report_select'),
ref('ai_account_reports.ir_actions_server_accounting_report_get_values'),
ref('ai_account_reports.ir_actions_server_accounting_report_expand_line'),
ref('ai_account_reports.ir_actions_server_accounting_report_open'),
])]"/>
</record>
<record id="ai_skill_accounting" model="ai.skill">
<field name="name">Accounting</field>
<field name="description"><![CDATA[
Entry point for user-facing accounting questions, reports and audit working
files. Report figures also require Accounting Report Analysis; supporting
record queries require Search Database.
]]></field>
<field name="instructions"><![CDATA[
You own the accounting request and the user-facing answer. Answer methodology
questions without inventing company facts or rules.
Follow the user's requested scope. A focused audit question need not complete
a check or change its status.
Explain results in accounting terms. In user-facing answers, translate tool
metadata into its business meaning; omit internal field names, raw objects and
configuration references. Preserve relevant accounting terminology, report
labels and statutory codes.
For ordinary report answers, open the main supporting report before answering
the user. Internal audit investigations do not require opening reports.
For an audit, read the working-file scope and all requested checks. Create a
file only when requested. For a full cycle, include every non-file check, even
if native logic already marks it reviewed; that status does not establish that
its instructions were investigated. Start one Auditor per check, issuing
independent assignments together. Supply the exact audit_id, cycle code,
check_code, objective and relevant user context. The Auditor retrieves the
instructions and chooses the investigation. Keep file checks as manual evidence
requirements.
After the batch returns, reconcile findings and review objections. Continue the
same Auditor for a concrete unresolved question; do not redispatch work blocked
on unavailable documents. Account for every assigned check before reporting
the investigation complete. Save authorized findings in cycle batches. Keep
unsupported conclusions todo; leave formal completion and supervision to the
user.
Preserve the Auditor's concise conclusions when saving notes.
After saving, briefly summarize the overall outcome, progress and main
unresolved actions, and link the working file. Leave individual check details
there unless requested.
Base the summary on the saved findings and save result. Preserve their scope,
uncertainty and limitations. Check that each factual statement is supported,
without strengthening conclusions or adding new claims.
Use check names in user-facing summaries. Keep agent names, delegation and
reviewer history out of saved notes and user-facing answers.
For other companies, ask the user to change Odoo's company selector.
]]></field>
<field name="tool_ids" eval="[(6, 0, [
ref('ai_account_reports.ir_actions_server_accounting_report_open'),
ref('ai_account_reports.ir_actions_server_accounting_audit_create'),
ref('ai_account_reports.ir_actions_server_accounting_audit_get_checks'),
ref('ai_account_reports.ir_actions_server_accounting_audit_update_checks'),
])]"/>
</record>
<record id="ai_skill_audit_evidence" model="ai.skill">
<field name="name">Accounting Audit Evidence</field>
<field name="description"><![CDATA[
Read native audit instructions and action hints, select this session's working
file and interpret Odoo accounting evidence.
]]></field>
<field name="instructions"><![CDATA[
Use the exact assigned audit_id. If it is missing, return that gap to the
caller; do not guess from matching file names or dates. Read
accounting_audit_get_checks for that file and cycle, locating the assigned
check_code and its full instructions. Inspect its action details as
investigation hints. An absent action does not mean absent evidence.
Native check statuses may be assigned automatically. "Reviewed" does not
establish human review or sign-off. Before reporting a control failure,
establish that the control applies and that evidence demonstrates its failure.
Otherwise, describe the evidence gap and leave the check todo.
Select your assigned working file before querying audit-computed fields.
Its companies and main company must match Odoo's company selector. Keep date
and posting scope explicit in ordinary queries; report figures follow their
selected report options.
For income, expense and equity_unaffected accounts, audit_debit/audit_credit are
period activity; for other accounts they accumulate through the cutoff. Use
dated ledger queries for annual movements. Current balances, residuals and stock
quantities are not automatically historical evidence.
Use ai_tool_get_fields with include_description=true to read field help before
interpreting unfamiliar statuses or amounts. Check the account and journal
configuration; a field label alone does not establish its accounting meaning.
Payments posted directly to the journal's default bank/cash account can have
is_matched=true without a bank statement. A journal item's residual or
reconciled=false on an account with reconcile=false does not establish an
unsettled receipt. Trace the payment and counterpart entries; these flags alone
prove neither external settlement nor non-settlement.
]]></field>
<field name="tool_ids" eval="[(6, 0, [
ref('ai_account_reports.ir_actions_server_accounting_audit_get_checks'),
ref('ai_account_reports.ir_actions_server_accounting_audit_get_check_action_detail'),
ref('ai_account_reports.ir_actions_server_accounting_audit_set_working_file'),
])]"/>
</record>
</odoo>

View File

@@ -0,0 +1,589 @@
<?xml version="1.0" encoding="utf-8"?>
<odoo>
<record id="ir_actions_server_accounting_report_list" model="ir.actions.server">
<field name="name">AI Tool: List Accounting Reports</field>
<field name="ai_tool_name">accounting_report_list</field>
<field name="state">code</field>
<field name="use_in_ai" eval="True"/>
<field name="model_id" ref="ai.model_ai_tool"/>
<field name="ai_tool_thinking_text">Finding accessible accounting reports</field>
<field name="ai_tool_description"><![CDATA[
Lists accessible report entry points from account_report client actions.
Use action_report_id to describe an entry; report.report_id identifies its
native default selection. Returns report names, default variant/section IDs,
filter_date_range and pagination. An empty list means no matching entries.
]]></field>
<field name="code">ai['result'] = record._ai_tool_accounting_report_list(offset=offset, limit=limit)</field>
<field name="ai_tool_schema"><![CDATA[
{
"type": "object",
"properties": {
"offset": {"type": "integer", "minimum": 0},
"limit": {"type": "integer", "minimum": 1, "description": "Page size from 1 to 200; defaults to 60."}
},
"required": []
}
]]></field>
</record>
<record id="ir_actions_server_accounting_report_describe" model="ir.actions.server">
<field name="name">AI Tool: Describe Accounting Report</field>
<field name="ai_tool_name">accounting_report_describe</field>
<field name="state">code</field>
<field name="use_in_ai" eval="True"/>
<field name="model_id" ref="ai.model_ai_tool"/>
<field name="ai_tool_thinking_text">Inspecting the accounting report</field>
<field name="ai_tool_description"><![CDATA[
Builds reusable configuration from action_report_id returned by
accounting_report_list, using the companies currently selected in Odoo.
A matching current browser report supplies its native options and source
action; otherwise native defaults apply.
Returns report_config, currencies, available_option_overrides, a paginated
line_catalog and report_config_ref. report_config contains action_report_id
and options. options.companies lists the companies included by native reporting,
which may be fewer than the current selection.
Its options retain native settings and choices, including report_id and
columns. report_config.options.columns contains all native column definitions
in order; expression_label can repeat across groups. Match report_id to
available_variants or sections for the selected report name. Currency details
are listed separately by ID.
Returned options are a subset of the saved settings. aging_based_on is
base_on_invoice_date for invoice dates or base_on_maturity_date for due dates.
Use native names in option_overrides. journals and account_type accept
{id, selected} objects. In resolved native options, no selected entries means
all listed entries apply. Use accounting_report_select to change identity or
options. If the user changes the company selection, describe the report again
to obtain a new reference.
]]></field>
<field name="code">ai['result'] = record._ai_tool_accounting_report_describe(tool_context=ai, action_report_id=action_report_id, option_overrides=option_overrides, offset=offset, limit=limit)</field>
<field name="ai_tool_schema"><![CDATA[
{
"type": "object",
"properties": {
"action_report_id": {
"type": "integer",
"minimum": 1,
"description": "action_report_id returned by accounting_report_list. This identifies the report referenced by the client action; do not substitute report_config.options.report_id or a variant/section ID."
},
"option_overrides": {
"type": "object",
"description": "Optional intentional changes keyed by option name. Apart from date, use only names in available_option_overrides. These are native Odoo option names. Omit defaults; false and empty lists are intentional values.",
"properties": {
"date": {
"type": "object",
"description": "Named periods and single-date reports use date_to only; a custom range also needs date_from.",
"properties": {
"period_type": {"type": "string", "enum": ["today", "month", "quarter", "year", "custom"]},
"date_from": {"type": "string", "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"},
"date_to": {"type": "string", "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"}
},
"required": ["period_type", "date_to"]
},
"comparison": {
"type": "object",
"description": "Use only fields belonging to the selected comparison form.",
"properties": {
"filter": {"type": "string", "enum": ["no_comparison", "previous_period", "same_last_year", "custom"]},
"number_period": {"type": "integer", "minimum": 1},
"date_from": {"type": "string", "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"},
"date_to": {"type": "string", "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"}
},
"required": ["filter"]
},
"journals": {
"type": "array",
"items": {
"type": "object",
"properties": {"id": {"type": "integer"}, "selected": {"type": "boolean"}},
"required": ["id", "selected"]
}
},
"analytic_accounts_groupby": {"type": "array", "items": {"type": "integer"}},
"partner_ids": {"type": "array", "items": {"type": "integer"}},
"partner_categories": {"type": "array", "items": {"type": "integer"}},
"account_type": {
"type": "array",
"items": {
"type": "object",
"properties": {
"id": {"type": "string", "enum": ["trade_receivable", "non_trade_receivable", "trade_payable", "non_trade_payable"]},
"selected": {"type": "boolean"}
},
"required": ["id", "selected"]
}
},
"all_entries": {"type": "boolean"},
"unreconciled": {"type": "boolean"},
"hierarchy": {"type": "boolean"},
"tax_unit": {"type": "integer", "minimum": 1},
"selected_horizontal_group_id": {"type": "integer", "minimum": 1}
},
"required": []
},
"offset": {"type": "integer", "minimum": 0},
"limit": {"type": "integer", "minimum": 1, "description": "Page size from 1 to 200; defaults to 60."}
},
"required": ["action_report_id"]
}
]]></field>
</record>
<record id="ir_actions_server_accounting_report_select" model="ir.actions.server">
<field name="name">AI Tool: Select Accounting Report Identity</field>
<field name="ai_tool_name">accounting_report_select</field>
<field name="state">code</field>
<field name="use_in_ai" eval="True"/>
<field name="model_id" ref="ai.model_ai_tool"/>
<field name="ai_tool_thinking_text">Selecting the accounting report</field>
<field name="ai_tool_description"><![CDATA[
Selects a variant or section from an exact report_config_ref.
Use choice={kind: "variant", id: ...} with an ID from
report_config.options.available_variants, or kind: "section" with an ID from
report_config.options.sections. These lists belong to the supplied
configuration. A report can serve different roles in different lists; use the
matching kind. Returns the same description as describe.
Optional option_overrides uses native option names and selection objects.
Checks reference ownership, selected companies and report access.
]]></field>
<field name="code">ai['result'] = record._ai_tool_accounting_report_select(tool_context=ai, report_config_ref=report_config_ref, choice=choice, option_overrides=option_overrides, offset=offset, limit=limit)</field>
<field name="ai_tool_schema"><![CDATA[
{
"type": "object",
"properties": {
"report_config_ref": {
"type": "string",
"pattern": "^[A-Za-z0-9_-]{24}$",
"description": "Required exact configuration returned by the describe or select result that exposed this choice. It binds the current user, source action, top-level report entry, selected companies, native options, and selected identity. A stale or mismatched configuration fails closed."
},
"choice": {
"type": "object",
"description": "Use kind variant with an ID from report_config.options.available_variants, or kind section with an ID from report_config.options.sections in the supplied configuration.",
"properties": {
"kind": {"type": "string", "enum": ["variant", "section"]},
"id": {"type": "integer", "minimum": 1}
},
"required": ["kind", "id"]
},
"option_overrides": {
"type": "object",
"description": "Optional intentional changes keyed by option name. Apart from date, use only names in available_option_overrides. These are native Odoo option names. Omit defaults; false and empty lists are intentional values.",
"properties": {
"date": {
"type": "object",
"description": "Named periods and single-date reports use date_to only; a custom range also needs date_from.",
"properties": {
"period_type": {"type": "string", "enum": ["today", "month", "quarter", "year", "custom"]},
"date_from": {"type": "string", "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"},
"date_to": {"type": "string", "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"}
},
"required": ["period_type", "date_to"]
},
"comparison": {
"type": "object",
"description": "Use only fields belonging to the selected comparison form.",
"properties": {
"filter": {"type": "string", "enum": ["no_comparison", "previous_period", "same_last_year", "custom"]},
"number_period": {"type": "integer", "minimum": 1},
"date_from": {"type": "string", "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"},
"date_to": {"type": "string", "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"}
},
"required": ["filter"]
},
"journals": {
"type": "array",
"items": {
"type": "object",
"properties": {"id": {"type": "integer"}, "selected": {"type": "boolean"}},
"required": ["id", "selected"]
}
},
"analytic_accounts_groupby": {"type": "array", "items": {"type": "integer"}},
"partner_ids": {"type": "array", "items": {"type": "integer"}},
"partner_categories": {"type": "array", "items": {"type": "integer"}},
"account_type": {
"type": "array",
"items": {
"type": "object",
"properties": {
"id": {"type": "string", "enum": ["trade_receivable", "non_trade_receivable", "trade_payable", "non_trade_payable"]},
"selected": {"type": "boolean"}
},
"required": ["id", "selected"]
}
},
"all_entries": {"type": "boolean"},
"unreconciled": {"type": "boolean"},
"hierarchy": {"type": "boolean"},
"tax_unit": {"type": "integer", "minimum": 1},
"selected_horizontal_group_id": {"type": "integer", "minimum": 1}
},
"required": []
},
"offset": {"type": "integer", "minimum": 0},
"limit": {"type": "integer", "minimum": 1, "description": "Page size from 1 to 200; defaults to 60."}
},
"required": ["report_config_ref", "choice"]
}
]]></field>
</record>
<record id="ir_actions_server_accounting_report_get_values" model="ir.actions.server">
<field name="name">AI Tool: Get Accounting Report Values</field>
<field name="ai_tool_name">accounting_report_get_values</field>
<field name="state">code</field>
<field name="use_in_ai" eval="True"/>
<field name="model_id" ref="ai.model_ai_tool"/>
<field name="ai_tool_thinking_text">Computing selected accounting figures</field>
<field name="ai_tool_description"><![CDATA[
Computes native report values from report_config_ref returned by describe or
select. Returns report_config, currencies, column_groups, paginated lines,
native warnings and the same report_config_ref.
An empty warnings object means the report returned no warnings. It does not
establish that the accounts are correct, reconciled or compliant. Consider any
line-level warning_text as well.
report_config.options.columns keeps all native column definitions. Provide at
least one expression_label in columns. These labels select row cells across all
periods and groups without changing the config. Pagination limits rows,
regardless of the number of columns.
Each line contains native columns: expression_label, column_group_index,
no_format (raw value) and name (formatted value). column_group_index indexes
column_groups; forced_options.date identifies that group's period when present,
otherwise use report_config.options.date. A configured date range does not mean
every value is activity within that range: General Ledger account debit and
credit totals include opening amounts. line_ref permits expansion.
row_type distinguishes data, totals and load_more summaries. Lines retain
native warning_text when present.
]]></field>
<field name="code">ai['result'] = record._ai_tool_accounting_report_get_values(tool_context=ai, report_config_ref=report_config_ref, columns=columns, line_codes=line_codes, offset=offset, limit=limit)</field>
<field name="ai_tool_schema"><![CDATA[
{
"type": "object",
"properties": {
"report_config_ref": {
"type": "string",
"pattern": "^[A-Za-z0-9_-]{24}$",
"description": "Required exact configuration returned by accounting_report_describe or accounting_report_select. It already binds the catalog report entry, selected identity, configuration, current user, and selected companies. Do not substitute null or a configuration built for different companies."
},
"columns": {
"type": "array",
"items": {"type": "string"},
"description": "Required nonempty list of expression labels from report_config.options.columns returned by accounting_report_describe or accounting_report_select. Each label selects all matching columns across all periods and groups. To read every column, provide every expression label."
},
"line_codes": {
"type": "array",
"items": {"type": "string"},
"description": "Stable static line codes returned by describing that exact identity. If nonempty, reuse that describe result's report_config_ref; identity selectors are not accepted by this tool. Omit for normal rendered-row order."
},
"offset": {"type": "integer", "minimum": 0},
"limit": {"type": "integer", "minimum": 1, "description": "Page size from 1 to 200; defaults to 60."}
},
"required": ["report_config_ref", "columns"]
}
]]></field>
</record>
<record id="ir_actions_server_accounting_report_expand_line" model="ir.actions.server">
<field name="name">AI Tool: Expand Accounting Report Line</field>
<field name="ai_tool_name">accounting_report_expand_line</field>
<field name="state">code</field>
<field name="use_in_ai" eval="True"/>
<field name="model_id" ref="ai.model_ai_tool"/>
<field name="ai_tool_thinking_text">Drilling into the accounting report</field>
<field name="ai_tool_description"><![CDATA[
Expands a line_ref issued by get_values or expand_line using its exact saved
configuration and column selection. Returns the same report_config, currencies,
lines, column_groups and pagination as get_values. Follow returned line_ref
values for deeper detail. A load_more reference reloads its parent branch and
may repeat earlier lines; do not double-count them.
Rows represent report lines, not necessarily accounting records. Initial Balance
is an opening summary. Row names are display descriptions; do not infer
dimensions absent from the returned data. Lines retain native warning_text
when present.
]]></field>
<field name="code">ai['result'] = record._ai_tool_accounting_report_expand_line(tool_context=ai, line_ref=line_ref, offset=offset, limit=limit)</field>
<field name="ai_tool_schema"><![CDATA[
{
"type": "object",
"properties": {
"line_ref": {
"type": "string",
"pattern": "^[A-Za-z0-9_-]{24}$",
"description": "Required exact opaque reference returned by a dynamic or load-more row. It binds the saved report configuration, selected column labels, and current user."
},
"offset": {"type": "integer", "minimum": 0},
"limit": {"type": "integer", "minimum": 1, "description": "Page size from 1 to 200; defaults to 60."}
},
"required": ["line_ref"]
}
]]></field>
</record>
<record id="ir_actions_server_accounting_report_open" model="ir.actions.server">
<field name="name">AI Tool: Open Accounting Report</field>
<field name="ai_tool_name">accounting_report_open</field>
<field name="state">code</field>
<field name="use_in_ai" eval="True"/>
<field name="model_id" ref="ai.model_ai_tool"/>
<field name="ai_tool_thinking_text">Opening the supporting accounting report</field>
<field name="ai_tool_description"><![CDATA[
Opens the exact saved report_config_ref using its source action and full
native options. Returns opened, report_config, currencies and the reference.
If that exact configuration is already displayed, opened is false and reason
explains why. Otherwise a client action opens it. Call this tool alone and wait
for its result before answering.
]]></field>
<field name="code">ai['result'] = record._ai_tool_accounting_report_open(tool_context=ai, report_config_ref=report_config_ref)</field>
<field name="ai_tool_schema"><![CDATA[
{
"type": "object",
"properties": {
"report_config_ref": {
"type": "string",
"pattern": "^[A-Za-z0-9_-]{24}$",
"description": "Required exact configuration returned by the get-values call supporting the answer. It already binds the catalog report entry, selected identity, configuration, current user, and selected companies; do not substitute null or add overrides."
}
},
"required": ["report_config_ref"]
}
]]></field>
</record>
<record id="ir_actions_server_accounting_audit_set_working_file" model="ir.actions.server">
<field name="name">AI Tool: Set Working Audit File</field>
<field name="ai_tool_name">accounting_audit_set_working_file</field>
<field name="state">code</field>
<field name="use_in_ai" eval="True"/>
<field name="model_id" ref="ai.model_ai_tool"/>
<field name="ai_tool_thinking_text">Setting Working Audit File</field>
<field name="ai_tool_description"><![CDATA[
Set the working audit file for this session's context-dependent accounting
fields, or pass null to clear it. Select the assigned file before querying audit
fields with search/read-group. Wait for the setter result before issuing those
queries. Clear it before unrelated work or select the new file when the
assignment changes. Parent and child sessions keep separate working-file
selections. The file's companies and main company must match Odoo's company
selector.
Returns the active file, company and period, or audit_context=null when cleared.
This does not add company/date domains to ordinary searches, select report
options or modify the working file's findings.
]]></field>
<field name="code">ai['result'] = record._ai_tool_accounting_audit_set_working_file(tool_context=ai, audit_id=audit_id)</field>
<field name="ai_tool_schema"><![CDATA[
{
"type": "object",
"properties": {
"audit_id": {
"anyOf": [
{"type": "integer", "minimum": 1},
{"type": "null"}
],
"description": "Working audit-file ID, or null to clear this session's selection."
}
},
"required": ["audit_id"]
}
]]></field>
</record>
<record id="ir_actions_server_accounting_audit_create" model="ir.actions.server">
<field name="name">AI Tool: Create Audit Working File</field>
<field name="ai_tool_name">accounting_audit_create</field>
<field name="state">code</field>
<field name="use_in_ai" eval="True"/>
<field name="model_id" ref="ai.model_ai_tool"/>
<field name="ai_tool_thinking_text">Create Audit Working File</field>
<field name="ai_tool_description"><![CDATA[
Create a native audit working file for the currently selected company and
exact dates, using the native local audit type and configured cycles. Select
one company in Odoo before calling this tool. Requires confirmation. For branch
structures, ask the user to create the file manually in the Accounting
application and provide its ID. Returns the file scope, URL and native check
progress.
]]></field>
<field name="code">ai['result'] = record._ai_tool_accounting_audit_create(tool_context=ai, date_from=date_from, date_to=date_to)</field>
<field name="ai_tool_schema"><![CDATA[
{
"type": "object",
"properties": {
"date_from": {
"type": "string",
"pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
},
"date_to": {
"type": "string",
"pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
}
},
"required": [
"date_from",
"date_to"
]
}
]]></field>
</record>
<record id="ir_actions_server_accounting_audit_get_checks" model="ir.actions.server">
<field name="name">AI Tool: Read Audit Checks</field>
<field name="ai_tool_name">accounting_audit_get_checks</field>
<field name="state">code</field>
<field name="use_in_ai" eval="True"/>
<field name="model_id" ref="ai.model_ai_tool"/>
<field name="ai_tool_thinking_text">Read Audit Checks</field>
<field name="ai_tool_description"><![CDATA[
Read the native working file, complete check instructions and notes, company and
dates, live cycle progress, and paginated checks. Pass cycle to read the
assigned cycle, or omit it to discover all cycles. File checks require manual
evidence. Native record count is only a capped hint; it is not a complete
evidence count. Progress summarizes native statuses and refresh flags, not a
record of agent investigations.
]]></field>
<field name="code">ai['result'] = record._ai_tool_accounting_audit_get_checks(audit_id=audit_id, cycle=cycle, offset=offset, limit=limit)</field>
<field name="ai_tool_schema"><![CDATA[
{
"type": "object",
"properties": {
"audit_id": {
"type": "integer",
"minimum": 1,
"description": "Native audit working-file ID."
},
"cycle": {
"type": "string",
"description": "Copy the native cycle code from accounting_audit_get_checks."
},
"offset": {
"type": "integer",
"minimum": 0
},
"limit": {
"type": "integer",
"minimum": 1,
"description": "Page size from 1 to 200; defaults to 60."
}
},
"required": [
"audit_id"
]
}
]]></field>
</record>
<record id="ir_actions_server_accounting_audit_get_check_action_detail" model="ir.actions.server">
<field name="name">AI Tool: Get Audit Check Action Detail</field>
<field name="ai_tool_name">accounting_audit_get_check_action_detail</field>
<field name="state">code</field>
<field name="use_in_ai" eval="True"/>
<field name="model_id" ref="ai.model_ai_tool"/>
<field name="ai_tool_thinking_text">Inspecting the audit check action</field>
<field name="ai_tool_description"><![CDATA[
Return a check's native action in action_detail as an investigation hint, with
search and main view XML for record actions. Interpret its domain, active search
defaults and search-panel selections using the XML, including filter grouping.
Group-by defaults suggest grouping rather than record restrictions. Choose
fields and explicit domains for search/read-group, or use accounting-report
tools for report actions. Native report IDs and options remain in the action.
No records or report_config_ref are returned. Action context is metadata for
interpreting the action; it does not configure subsequent tools.
If no action is available, investigate from the check instructions and attached
documents. Other executable actions are returned without being run.
]]></field>
<field name="code">ai['result'] = record._ai_tool_accounting_audit_get_check_action_detail(audit_id=audit_id, check_code=check_code)</field>
<field name="ai_tool_schema"><![CDATA[
{
"type": "object",
"properties": {
"audit_id": {
"type": "integer",
"minimum": 1,
"description": "Native audit working-file ID."
},
"check_code": {
"type": "string"
}
},
"required": [
"audit_id",
"check_code"
]
}
]]></field>
</record>
<record id="ir_actions_server_accounting_audit_update_checks" model="ir.actions.server">
<field name="name">AI Tool: Save Audit Cycle Findings</field>
<field name="ai_tool_name">accounting_audit_update_checks</field>
<field name="state">code</field>
<field name="use_in_ai" eval="True"/>
<field name="model_id" ref="ai.model_ai_tool"/>
<field name="ai_tool_thinking_text">Save Audit Cycle Findings</field>
<field name="ai_tool_description"><![CDATA[
Preview and save a validated batch of findings for one assigned cycle, under
native access and review rules. Only non-file checks may be updated. Use
reviewed for supported clearance, anomaly for evidenced exceptions, and todo for
incomplete or blocked checks. Never formally completes or supervises the
working file. Requires confirmation. After saving, returns the updated check
codes, native check progress and working-file URL.
For each saved audit note, write a short, plain-language conclusion, normally
two or three sentences. State what is established, what is wrong, or what
remains unresolved. Include only the decisive facts or amounts and any
necessary next action.
Do not repeat the check description, company, period or procedures unless
needed to understand the conclusion. Avoid headings such as Scope, Procedures
and Evidence. Preserve limitations that change what can be concluded. Use
neutral language without mentioning agents.
]]></field>
<field name="code">ai['result'] = record._ai_tool_accounting_audit_update_checks(tool_context=ai, audit_id=audit_id, cycle=cycle, updates=updates)</field>
<field name="ai_tool_schema"><![CDATA[
{
"type": "object",
"properties": {
"audit_id": {
"type": "integer",
"minimum": 1,
"description": "Native audit working-file ID."
},
"cycle": {
"type": "string",
"description": "Copy the native cycle code from accounting_audit_get_checks."
},
"updates": {
"type": "array",
"description": "Between 1 and 100 findings for distinct non-file checks in this cycle.",
"items": {
"type": "object",
"properties": {
"check_code": {
"type": "string"
},
"notes": {
"type": "string",
"description": "Plain text, without Markdown or HTML."
},
"result": {
"type": "string",
"enum": [
"todo",
"reviewed",
"anomaly"
]
}
},
"required": [
"check_code",
"notes",
"result"
]
}
}
},
"required": [
"audit_id",
"cycle",
"updates"
]
}
]]></field>
</record>
</odoo>

View File

@@ -0,0 +1,5 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from . import ai_session
from . import ai_tool
from . import ai_tool_audit

View File

@@ -0,0 +1,35 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import json
from odoo import models
class AiSession(models.Model):
_inherit = 'ai.session'
def _get_request_context_snapshot(self, context=None):
snapshot = super()._get_request_context_snapshot(context)
if self and (audit_id := (self.request_context or {}).get('working_file_id')):
snapshot['working_file_id'] = audit_id
return snapshot
def _get_tool_execution_context(self):
context = super()._get_tool_execution_context()
if self:
# Read this session's selection, not the environment of a returning child.
context['working_file_id'] = (self.request_context or {}).get('working_file_id')
return context
def _get_context_input(self, text):
current_view_info = self.env.context.get('current_view_info')
if not isinstance(current_view_info, dict) or 'current_account_report' not in current_view_info:
return super()._get_context_input(text)
clean_view = {key: value for key, value in current_view_info.items() if key != 'current_account_report'}
context_input = super(AiSession, self.with_context(current_view_info=clean_view or None))._get_context_input(text)
current_report = self.env(su=False)['ai.tool']._get_current_account_report_context()
if not current_report:
return context_input
payload = json.dumps({'current_account_report': current_report}, ensure_ascii=False)
return context_input.replace('</odoo_current_context>',
f'\n## Current account report\n{payload}</odoo_current_context>')

View File

@@ -0,0 +1,511 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import ast
import json
import secrets
from copy import deepcopy
from odoo import api, fields, models
from odoo.exceptions import AccessError, UserError, ValidationError
from odoo.tools.json import json_default
class AITool(models.AbstractModel):
"""Read native accounting reports using saved configurations.
A report_config dict holds uid, action_id, action_report_id,
allowed_company_ids and the native options dict. action_report_id
identifies the source action's report; options['report_id'] identifies
the selected report. allowed_company_ids records the saved selection;
options['companies'] lists the companies included in the report.
tool_context['state'] stores this session's configurations and line refs.
"""
_inherit = 'ai.tool'
DEFAULT_LIMIT = 60
MAX_LIMIT = 200
MAX_REPORT_CONFIGS = 32
REPORT_CONFIG_KEY = 'accounting_report_configs'
LINE_REF_KEY = 'accounting_report_line_refs'
UNAVAILABLE_CATALOG_REPORT_MESSAGE = (
'The action report {action_report_id} is unavailable or inaccessible. '
'Use action_report_id from accounting_report_list, not a selected variant or section ID.'
)
@api.model
def _ai_tool_accounting_report_list(self, offset=None, limit=None):
"""Return a dict with a page of accessible reports and pagination.
Each entry includes report IDs and names, the selected variant/section
IDs, and whether the report uses a date range.
"""
offset, limit = self._normalize_page(offset, limit)
entries = [(report_id, actions[0], options)
for report_id, (actions, options) in self._get_report_catalog().items()]
page, pagination = self._paginate(entries, offset, limit, 'total_reports')
reports = []
for report_id, action, options in page:
report = self.env['account.report'].browse(report_id)
actual = self.env['account.report'].browse(options['report_id'])
reports.append({
'action_report_id': report_id, 'name': report.name,
**({'alias': action.name} if action.name != report.name else {}),
'report': {'report_id': options['report_id'], 'name': actual.name},
**{key: options[key] for key in ('selected_variant_id', 'selected_section_id') if key in options},
'filter_date_range': actual.filter_date_range})
return {'reports': reports, 'pagination': pagination}
@api.model
def _ai_tool_accounting_report_describe(
self, tool_context, action_report_id, option_overrides=None,
offset=None, limit=None,
):
"""Describe report choices and lines, then save the configuration.
Start from a matching browser report or native defaults, then apply
option_overrides (dict | None). Return a dict with settings, currencies,
editable option names, a line catalog and report_config_ref (str).
"""
offset, limit = self._normalize_page(offset, limit)
entry = self._get_report_catalog(action_report_id).get(action_report_id)
self._guard(entry, self.UNAVAILABLE_CATALOG_REPORT_MESSAGE.format(action_report_id=action_report_id), AccessError)
actions, defaults = entry
current = self._get_current_account_report()
if current and current['action_report_id'] == action_report_id:
action_id, options = current['action_id'], current['options']
else:
action_id, options = actions[0].id, defaults
report_config = {
'uid': self.env.uid, 'action_id': action_id, 'action_report_id': action_report_id,
'allowed_company_ids': self.env.companies.ids, 'options': options,
}
return self._describe_and_save_report_config(
tool_context, report_config, option_overrides, offset, limit,
)
@api.model
def _ai_tool_accounting_report_select(
self, tool_context, report_config_ref, choice, option_overrides=None,
offset=None, limit=None,
):
"""Select a variant or section and return the same details as describe.
choice is {kind: 'variant' | 'section', id: int}, using the saved choices.
Return a reference for the resulting configuration; the input reference
keeps its original options.
"""
offset, limit = self._normalize_page(offset, limit)
report_config = self._load_report_config(tool_context, report_config_ref)
kind, choice_id = choice['kind'], choice['id']
report = self.env['account.report'].browse(report_config['action_report_id'])
choices_key = 'available_variants' if kind == 'variant' else 'sections'
available_ids = [item['id'] for item in report_config['options'][choices_key]]
self._guard(choice_id in available_ids,
f'Unavailable {kind} choice {choice_id}. Choose from {choices_key}: {available_ids}.')
selectors = (
{'selected_variant_id': choice_id} if kind == 'variant'
else {'selected_variant_id': report_config['options']['selected_variant_id'], 'selected_section_id': choice_id}
)
options = report.get_options({**deepcopy(report_config['options']), **selectors})
report_config = dict(report_config, options=options)
return self._describe_and_save_report_config(
tool_context, report_config, option_overrides, offset, limit, selectors=selectors,
)
@api.model
def _ai_tool_accounting_report_get_values(
self, tool_context, report_config_ref, columns, line_codes=None,
offset=None, limit=None,
):
"""Return native figures, report settings, warnings and pagination in a dict.
columns is a nonempty list[str] of expression labels, each including all
matching periods and groups. line_codes (list[str]) can select static lines.
Expandable rows include a line_ref (str) for fetching their details.
Copy options because native rendering can mutate them even in readonly mode.
"""
self._guard(columns, 'Select at least one column expression label.')
offset, limit = self._normalize_page(offset, limit)
report_config = self._load_report_config(tool_context, report_config_ref)
available_labels = {column['expression_label'] for column in report_config['options']['columns']}
missing = [label for label in columns if label not in available_labels]
self._guard(not missing, f'Unavailable columns: {missing}')
report = self.env['account.report'].browse(report_config['options']['report_id'])
information = report.get_report_information_readonly(deepcopy(report_config['options']))
lines = information['lines']
if line_codes:
stable = {line.code for line in report.line_ids if line.code}
by_code = {}
for line in lines:
if line.code in line_codes and report._get_markup(line.id) != 'load_more':
# Keep the original row when a trailing total repeats its code.
by_code.setdefault(line.code, line)
unavailable = [code for code in line_codes if code not in stable or code not in by_code]
self._guard(not unavailable, f'Unavailable or uncomputed line_codes: {unavailable}')
lines = [by_code[code] for code in line_codes]
result = self._build_report_values_payload(
report_config, report_config_ref, lines, tool_context,
columns=columns, offset=offset, limit=limit,
)
result['warnings'] = information['warnings']
return result
@api.model
def _ai_tool_accounting_report_expand_line(
self, tool_context, line_ref, offset=None, limit=None,
):
"""Return expanded rows, settings and pagination for line_ref (str) in a dict.
Reuse the saved options and columns. A load_more reference reloads its
parent branch, so earlier rows can reappear. Only row warnings are included.
"""
offset, limit = self._normalize_page(offset, limit)
ref = (tool_context['state'].get(self.LINE_REF_KEY) or {}).get(line_ref)
self._guard(ref, 'Stale or mismatched line_ref.')
report_config = self._load_report_config(tool_context, ref['report_config_ref'])
report = self.env['account.report'].browse(report_config['options']['report_id'])
parsed_line_id = report._parse_line_id(ref['line_id'], markup_as_string=True)
load_more = parsed_line_id[-1][0] == 'load_more'
line_id = report._build_parent_line_id(parsed_line_id) if load_more else ref['line_id']
lines = report.get_expanded_lines_readonly(
deepcopy(report_config['options']), line_id, ref['groupby'], ref['expand_function'],
ref['horizontal_split_side'], None, ignore_load_more=load_more,
)
return self._build_report_values_payload(
report_config, ref['report_config_ref'], lines, tool_context,
columns=ref['columns'], offset=offset, limit=limit,
)
@api.model
def _ai_tool_accounting_report_open(self, tool_context, report_config_ref):
"""Open the saved report, or explain why it is already displayed.
Return a result dict with opened, settings, currencies and the reference.
When opening is needed, wrap it in {result: dict, client_tool: dict};
client_tool tells the browser to run the action.
"""
report_config = self._load_report_config(tool_context, report_config_ref)
options = report_config['options']
current = self._get_current_account_report()
already_displayed = bool(
current and current['action_report_id'] == report_config['action_report_id'] and current['action_id'] == report_config['action_id']
and current['report_id'] == options['report_id']
and current['options'] == json.loads(json.dumps(options, default=json_default, ensure_ascii=False))
)
currencies = self.env['res.company'].browse(self.env['account.report'].get_report_company_ids(options)).currency_id
result = {
'opened': not already_displayed,
'report_config': self._get_report_config_for_llm(report_config),
'currencies': [{'id': c.id, 'name': c.name, 'symbol': c.symbol} for c in currencies],
'report_config_ref': report_config_ref,
}
if already_displayed:
result['reason'] = 'The exact report and options are already displayed.'
return result
action = self.env['ir.actions.client'].browse(report_config['action_id'])._get_action_dict()
context = ast.literal_eval(action['context'] or '{}')
action['context'] = dict(context, allowed_company_ids=self.env.companies.ids)
action['params'] = {
'options': dict(options, not_reset_journals_filter=True), 'ignore_session': True,
}
return {'result': result, 'client_tool': {'name': 'do_action', 'oneway': True, 'params': {'action': action}}}
def _load_report_config(self, tool_context, report_config_ref):
"""Return the saved configuration dict without rebuilding its options.
Check the user, company selection (including order) and report access.
"""
report_config = (tool_context['state'].get(self.REPORT_CONFIG_KEY) or {}).get(report_config_ref)
self._guard(report_config and report_config['uid'] == self.env.uid, 'Stale or mismatched report_config_ref.')
self._guard(report_config['allowed_company_ids'] == self.env.companies.ids,
'The company selection changed. Describe the report again.')
if not self.env.user.has_groups('account.group_account_readonly,account.group_account_basic'):
raise AccessError(self.env._('You must be an accountant to access accounting reports.'))
self._validate_report_options(report_config['options'])
return report_config
def _save_report_config(self, tool_context, report_config):
"""Save a JSON copy in the session and return its string reference.
Reuse identical copies and move them to the newest position.
Remove the oldest entry when MAX_REPORT_CONFIGS is exceeded.
"""
payload = json.loads(json.dumps(report_config, default=json_default, ensure_ascii=False))
registry = tool_context['state'].setdefault(self.REPORT_CONFIG_KEY, {})
config_ref = next((ref for ref, saved in registry.items() if saved == payload), None) or secrets.token_urlsafe(18)
registry.pop(config_ref, None)
registry[config_ref] = payload
if len(registry) > self.MAX_REPORT_CONFIGS:
registry.pop(next(iter(registry)))
return config_ref
def _issue_line_ref(self, report_config_ref, line, tool_context, columns):
"""Save a row's expansion details and return a string reference.
line is an AccountReportLineData object. Keep its report_config_ref and
column labels for later expansion.
"""
registry = tool_context['state'].setdefault(self.LINE_REF_KEY, {})
handle = secrets.token_urlsafe(18)
registry[handle] = {
'report_config_ref': report_config_ref, 'columns': columns,
'line_id': line.id, 'groupby': line.groupby, 'expand_function': line.expand_function,
'horizontal_split_side': line.horizontal_split_side,
}
if len(registry) > 256:
registry.pop(next(iter(registry)))
return handle
def _get_report_catalog(self, requested_report_id=None):
"""Map report IDs to (client action recordset, native options dict).
Omit requested_report_id to list all reports, or pass an integer ID.
Unavailable entries are omitted; missing accounting access raises an error.
Actions are ordered by ID.
"""
if not self.env.user.has_groups('account.group_account_readonly,account.group_account_basic'):
raise AccessError(self.env._('You must be an accountant to access accounting reports.'))
catalog = {}
for action in self.env['ir.actions.client'].sudo().search([('tag', '=', 'account_report')], order='id'):
try:
context = ast.literal_eval(action.context or '{}')
report_id = context.get('report_id') if isinstance(context, dict) else None
if not report_id or requested_report_id is not None and report_id != requested_report_id:
continue
report = self.env['account.report'].browse(report_id).exists()
if (report and report.active and report.has_access('read')
and report in report._is_available_for(self.env.companies)):
catalog[report_id] = catalog.get(report_id, action.browse()) | action
except (AccessError, SyntaxError, UserError, ValidationError, ValueError):
continue
result = {}
# A catalog entry remains usable only while its native default can initialize.
for report_id, actions in catalog.items():
try:
defaults = self.env['account.report'].browse(report_id).get_options({})
except (AccessError, SyntaxError, UserError, ValidationError, ValueError):
continue
result[report_id] = (actions, defaults)
return result
def _get_current_account_report(self):
"""Return the browser's {action_id, action_report_id, report_id, options}, or None."""
view = self.env.context.get('current_view_info') or {}
return view.get('current_account_report')
@api.model
def _get_current_account_report_context(self):
"""Return the browser report's IDs, name and options in a dict.
Return False if no report is open. Include only the options exposed by
_get_report_options.
"""
current = self._get_current_account_report()
if not current:
return False
options = current['options']
return {
'action_report_id': current['action_report_id'], 'report_id': options['report_id'],
'report_name': self.env['account.report'].browse(options['report_id']).name,
'options': self._get_report_options(options),
}
def _get_available_report_option_overrides(self, report, options):
"""List the supported option names this report allows the user to change.
report is an account.report record; options is its native options dict.
Date is handled separately; variants and sections use the select tool.
"""
analytic = bool(
report.filter_analytic_groupby
and self.env.user.has_group('analytic.group_analytic_accounting')
)
return [
name
for name, enabled in (
('comparison', report.filter_period_comparison),
('journals', report.filter_journals or options.get('journals')),
('analytic_accounts_groupby', analytic),
('partner_ids', report.filter_partner),
('partner_categories', report.filter_partner),
('account_type', report.filter_account_type not in ('disabled', False)),
('all_entries', report.filter_show_draft),
('unreconciled', report.filter_unreconciled),
('hierarchy', options.get('display_hierarchy_filter')),
('tax_unit', report.filter_multi_company == 'tax_units'),
('selected_horizontal_group_id', options.get('available_horizontal_groups')),
)
if enabled
]
def _validate_report_options(self, options):
# Validate the native company scope before accessing the effective report.
companies = self.env['res.company'].browse(
self.env['account.report'].get_report_company_ids(options)
)
if companies[:1] != self.env.company or companies - self.env.companies:
raise ValidationError(self.env._('The report engine returned an invalid company scope.'))
report = self.env['account.report'].browse(options.get('report_id')).exists()
if not (report and report.active and report.has_access('read')
and report in report._is_available_for(companies)):
raise AccessError(self.env._('Unavailable report.'))
def _apply_report_option_overrides(self, report_config, option_overrides, selectors=None):
"""Apply overrides with native get_options and return a report_config dict."""
# The schema inserts None for omitted options; preserve explicit False and [].
changes = {name: value for name, value in (option_overrides or {}).items() if value is not None}
if not changes:
return report_config
options = report_config['options']
report = self.env['account.report'].browse(options['report_id'])
unsupported = changes.keys() - {'date', *self._get_available_report_option_overrides(report, options)}
self._guard(not unsupported, f'Unsupported report option overrides: {sorted(unsupported)}.')
for name in ('date', 'comparison'):
if name in changes:
value = changes[name] = {key: item for key, item in changes[name].items() if item is not None}
dates = {'date_from', 'date_to'} & value.keys()
for key in dates:
fields.Date.to_date(value[key])
self._guard(dates != {'date_from', 'date_to'} or value['date_from'] <= value['date_to'], 'Invalid dates.')
if 'date' in changes:
date = changes['date']
self._guard(date['period_type'] == 'custom' or 'date_from' not in date, 'Invalid date form.')
self._guard(date['period_type'] != 'custom' or ('date_from' in date) == report.filter_date_range,
'Unavailable date form.')
if 'comparison' in changes:
comparison = changes['comparison']
custom = comparison['filter'] == 'custom'
count = comparison.get('number_period')
self._guard(
custom == ({'date_from', 'date_to'} <= comparison.keys())
and (count is None or count <= 5)
and (not custom or count in (None, 1))
and (comparison['filter'] != 'no_comparison' or count is None),
'Invalid comparison form.',
)
if 'journals' in changes:
available_ids = {journal['id'] for journal in options['journals']}
unavailable_ids = {journal['id'] for journal in changes['journals'] if journal['selected']} - available_ids
self._guard(not unavailable_ids, f'Unavailable selected journal IDs: {sorted(unavailable_ids)}. '
'Choose journals from report_config.options.journals.')
if 'partner_categories' in changes:
ids = changes['partner_categories']
categories = self.env['res.partner.category'].with_context(active_test=False)
if set(categories.search([('id', 'in', ids)]).ids) != set(ids):
raise AccessError(self.env._('Invalid or inaccessible partner_categories.'))
options = self.env['account.report'].browse(report_config['action_report_id']).get_options(
{**deepcopy(options), **(selectors or {}), **changes},
)
return dict(report_config, options=options)
def _describe_and_save_report_config(
self, tool_context, report_config, option_overrides, offset, limit, selectors=None,
):
"""Apply overrides, save the configuration and return its description dict.
selectors (dict | None) holds variant/section IDs that must remain selected
after native get_options runs. The result includes report_config_ref (str).
"""
report_config = self._apply_report_option_overrides(report_config, option_overrides, selectors)
options = report_config['options']
self._validate_report_options(options)
for name, choice_id in (selectors or {}).items():
self._guard(options.get(name) == choice_id,
f'Native reporting did not apply {name}={choice_id}; returned {options.get(name)}.')
report = self.env['account.report'].browse(options['report_id'])
lines = [{'code': line.code, 'name': line.name, 'hierarchy_level': line.hierarchy_level}
for line in report.line_ids if line.code]
lines, pagination = self._paginate(lines, offset, limit, 'total_lines')
currencies = self.env['res.company'].browse(report.get_report_company_ids(options)).currency_id
result = {
'report_config': self._get_report_config_for_llm(report_config),
'currencies': [{'id': c.id, 'name': c.name, 'symbol': c.symbol} for c in currencies],
'available_option_overrides': self._get_available_report_option_overrides(report, options),
'line_catalog': {'items': lines, 'pagination': pagination},
}
result['report_config_ref'] = self._save_report_config(tool_context, report_config)
return result
def _build_report_values_payload(
self, report_config, report_config_ref, lines, tool_context, *, columns, offset, limit,
):
"""Format native report rows into a dict for the LLM.
lines contains AccountReportLineData objects. Keep the requested column
labels across all groups, paginate rows and add expansion references.
Include settings, currencies, column groups and any row warnings.
Figures and column definitions remain unchanged.
"""
options = report_config['options']
report = self.env['account.report'].browse(options['report_id'])
lines_page = []
for line in lines[offset:offset + limit]:
line_columns = [{
'expression_label': column.expression_label, 'column_group_index': column.column_group_index,
'no_format': column.no_format, 'name': column.name,
} for column in line.columns or [] if column.expression_label in columns]
markup = report._get_markup(line.id)
expandable = bool(line.expand_function and (line.unfoldable or markup == 'load_more'))
lines_page.append({
'code': line.code, 'name': line.name, 'level': line.level,
'row_type': markup if markup in ('total', 'load_more') else 'data', 'unfoldable': line.unfoldable,
'line_ref': self._issue_line_ref(report_config_ref, line, tool_context, columns) if expandable else None,
'columns': line_columns})
if warning_text := (line.custom or {}).get('warning_text'):
lines_page[-1]['warning_text'] = warning_text
next_offset = offset + len(lines_page)
currencies = self.env['res.company'].browse(report.get_report_company_ids(options)).currency_id
return {
'report_config': self._get_report_config_for_llm(report_config),
'currencies': [{'id': c.id, 'name': c.name, 'symbol': c.symbol} for c in currencies],
'report_config_ref': report_config_ref,
'column_groups': options['column_groups'], 'lines': lines_page,
'pagination': {'offset': offset, 'limit': limit, 'total_lines': len(lines),
'next_offset': next_offset if next_offset < len(lines) else None},
}
def _get_report_config_for_llm(self, report_config):
"""Return {action_report_id: int, options: dict} for the LLM.
Keep only the options exposed by _get_report_options. Other saved fields
stay internal.
"""
return {
'action_report_id': report_config['action_report_id'],
'options': self._get_report_options(report_config['options']),
}
def _get_report_options(self, options):
"""Return the report settings and metadata exposed to the LLM as a dict.
Keep native keys and values unchanged. This subset cannot replace the
full options used to render or open the report.
"""
option_keys = {
'report_id', 'companies', 'columns', 'date', 'comparison', 'all_entries', 'unreconciled', 'hierarchy',
'journals', 'account_type', 'analytic_accounts_groupby', 'partner_ids', 'partner_categories', 'aging_based_on',
'tax_unit', 'selected_horizontal_group_id', 'selected_variant_id', 'selected_section_id',
'available_variants', 'sections', 'available_tax_units', 'available_horizontal_groups', 'filter_date',
}
return {key: value for key, value in options.items() if key in option_keys}
def _normalize_page(self, offset, limit):
offset = 0 if offset is None else offset
limit = self.DEFAULT_LIMIT if limit is None else limit
self._guard(limit <= self.MAX_LIMIT, f'Page limit cannot exceed {self.MAX_LIMIT}.')
return offset, limit
def _paginate(self, values, offset, limit, total_key):
"""Return (page, pagination dict) from a list or recordset.
total_key names the total count; next_offset is None on the last page.
"""
page = values[offset:offset + limit]
next_offset = offset + len(page)
return page, {'offset': offset, 'limit': limit, total_key: len(values),
'next_offset': next_offset if next_offset < len(values) else None}
def _guard(self, condition, message, error=ValidationError):
if not condition:
raise error(message)

View File

@@ -0,0 +1,300 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from ast import literal_eval
from collections import Counter
from markupsafe import Markup
from odoo import Command, fields, models
from odoo.tools import html2plaintext
from odoo.addons.ai.utils.ai_utils import make_confirmation_request_preview
class AIAuditTool(models.AbstractModel):
_inherit = 'ai.tool'
def _audit_file(self, audit_id):
"""Return the audit working file (account.return) for audit_id (int).
Check access and require its companies and main company to match the
current selection.
"""
audit = self.env['account.return'].browse(audit_id).exists()
self._guard(audit, 'Working file not found.')
audit.check_access('read')
self._guard(audit.type_id.category == 'audit', 'Select an audit working file, not a tax return.')
# Native audit fields use the file's companies, independently of the environment.
self._guard(audit.company_id == self.env.company
and set(audit.company_ids.ids) == set(self.env.companies.ids),
"Select the working file's companies and main company in Odoo's company selector.")
return audit
def _audit_context_result(self):
"""Return {'audit_context': dict} for the working file in context, or {}.
Include its ID, companies, dates and a reminder that ordinary searches
still use their own domains.
"""
if not (audit_id := self.env.context.get('working_file_id')):
return {}
audit = self._audit_file(audit_id)
return {'audit_context': {
'working_file_id': audit.id,
'company_ids': audit.company_ids.ids,
'date_from': fields.Date.to_string(audit.date_from),
'date_to': fields.Date.to_string(audit.date_to),
'notice': 'Audit-computed fields use this working file. Ordinary record searches still follow '
'their supplied domains. Clear the working file before unrelated queries with '
'accounting_audit_set_working_file(audit_id=null).',
}}
def _ai_tool_search(self, model_name, domain="", fields=None, offset=0, limit=None, order=None):
"""Return the search result dict with any active audit context in response."""
audit_context = self._audit_context_result()
result = super()._ai_tool_search(model_name, domain, fields, offset, limit, order)
result['response'].update(audit_context)
return result
def _ai_tool_read_group(self, model_name, domain, groupby=None, aggregates=None, having="", offset=0, limit=None, order=None):
"""Return the grouped result dict with any active audit context in response."""
audit_context = self._audit_context_result()
result = super()._ai_tool_read_group(model_name, domain, groupby, aggregates, having, offset, limit, order)
result['response'].update(audit_context)
return result
def _ai_tool_accounting_audit_set_working_file(self, tool_context, audit_id):
"""Select audit_id (int | None) in this session; None clears the selection.
Save it in request_context and return {audit_context: dict | None}.
The company selection is unchanged.
"""
result = self.with_context(working_file_id=audit_id)._audit_context_result()
session = self.env['ai.session'].sudo().browse(tool_context['session_id'])
context = dict(session.request_context or {})
if audit_id:
context['working_file_id'] = audit_id
else:
context.pop('working_file_id', None)
session.request_context = context
return result or {'audit_context': None}
def _audit_cycle_checks(self, audit, cycle):
"""Return an account.return.check recordset for a cycle code in audit.
Use 'other' for checks without a cycle. Raise if no checks match.
"""
checks = audit.check_ids.filtered(lambda check: (check.cycle_id.code or 'other') == cycle)
self._guard(checks, 'Unknown or empty cycle. Copy a cycle code from accounting_audit_get_checks.')
return checks
def _audit_progress(self, audit):
"""Return working-file details and check counts for each cycle in a dict.
Counts and completion flags reflect saved statuses and refresh flags;
they do not establish that evidence was investigated.
"""
def counts(checks):
results = Counter(checks.mapped('result'))
return {
'total': len(checks), 'pending': results['todo'], 'anomalies': results['anomaly'],
'reviewed': results['reviewed'] + results['supervised'],
'manual_pending': len(checks.filtered(lambda c: c.type == 'file' and c.result == 'todo')),
'checks_pending': len(checks.filtered(
lambda c: c.type != 'file' and (c.refresh_result or c.result == 'todo'))),
}
checks = audit.check_ids
cycles = [{
'code': cycle.code, 'name': cycle.name,
**counts(checks.filtered(lambda c: c.cycle_id == cycle)),
} for cycle in checks.cycle_id.sorted()]
if other := checks.filtered(lambda c: not c.cycle_id):
cycles.append({'code': 'other', 'name': 'Other', **counts(other)})
totals = counts(checks)
return {
'audit_id': audit.id, 'name': audit.name,
'url': f'/odoo/action-account_reports.action_view_account_audit_checks?active_id={audit.id}',
'company_ids': audit.company_ids.ids, 'companies': audit.company_ids.mapped('display_name'),
'date_from': fields.Date.to_string(audit.date_from), 'date_to': fields.Date.to_string(audit.date_to),
'cycles': cycles, 'totals': totals,
'remaining_cycles': [c['code'] for c in cycles if c['checks_pending']],
'all_checks_investigated': not totals['checks_pending'],
'all_requirements_reviewed': not totals['pending'] and not totals['anomalies'] and not totals['checks_pending'],
'formally_completed': audit.is_completed,
}
def _audit_confirmation(self, tool_context, body):
"""Request confirmation and return True, or return False to proceed.
Put the confirmation request in tool_context['user_input_request'].
After approval, reject writes if the company selection changed.
"""
if not tool_context.get('tool_request_confirmed'):
tool_context['user_input_request'] = make_confirmation_request_preview(self.env, body)
return True
session = self.env['ai.session'].sudo().browse(tool_context['session_id'])
self._guard(session.request_context['allowed_company_ids'] == self.env.companies.ids,
'The company selection changed. Request this operation again.')
return False
def _ai_tool_accounting_audit_create(self, tool_context, date_from, date_to):
"""Create a working file for the requested dates after confirmation.
date_from and date_to are YYYY-MM-DD strings. Require one selected
company without parents or branches. Return a progress dict, or None
with user_input_request set when approval is needed.
"""
self._guard(len(self.env.companies) == 1,
'Select one company in Odoo before creating an audit working file.')
start, end = fields.Date.to_date(date_from), fields.Date.to_date(date_to)
self._guard(start and end and start <= end, 'Provide a valid start date on or before the end date.')
self.env['account.return'].check_access('create')
company = self.env.company
# REVIEW: What's this guard for?
# Native creation may traverse branch trees; require a single company here.
self._guard(not company.parent_id and not company.child_ids,
'Create this branched-company working file in Accounting, then provide its audit_id.')
values = {'company_id': company.id, 'category': 'audit', 'date_from': start, 'date_to': end}
wizard_model = self.env['account.return.creation.wizard']
wizard_model.check_access('create')
wizard = wizard_model.new(values)
return_type = wizard.return_type_id._origin
self._guard(return_type, 'No native audit return type is available for this company.')
values['return_type_id'] = return_type.id
# The template is literal; Markup formatting escapes the company name and dates.
if self._audit_confirmation(tool_context, Markup(
'<p>Create an audit working file for <strong>%s</strong>, %s to %s, '
'with the native configured checks?</p>'
) % (company.display_name, start, end)):
return
wizard = wizard_model.create(values)
self._guard(wizard.return_type_id, 'No native audit return type is available for this company.')
action = wizard.action_create_manual_account_returns()
audit_id = action['params']['next_action']['context']['active_id']
audit = self._audit_file(audit_id)
self._guard(audit.date_from == start and audit.date_to == end,
'Native creation changed the requested scope. Create the working file in Accounting.')
return self._audit_progress(audit)
def _ai_tool_accounting_audit_get_checks(self, audit_id, cycle=None, offset=None, limit=None):
"""Return working-file progress and a page of check details in a dict.
Include instructions, notes, status, action availability and attachment IDs.
cycle (str | None) limits the page to one cycle; omit it for all checks.
"""
audit = self._audit_file(audit_id)
checks = self._audit_cycle_checks(audit, cycle) if cycle else audit.check_ids
offset, limit = self._normalize_page(offset, limit)
page, pagination = self._paginate(checks, offset, limit, 'total_checks')
return {
**self._audit_progress(audit), 'selected_cycle': cycle,
'checks': [{
'code': check.code, 'name': check.name, 'message': html2plaintext(check.message or ''),
'type': check.type, 'cycle': check.cycle_id.code or 'other', 'result': check.result,
'notes': check.notes or '', 'native_records_count_hint': check.records_count,
'has_action': bool(check.action), 'attachment_ids': check.attachment_ids.ids,
} for check in page], 'pagination': pagination,
}
def _audit_action(self, check):
"""Return the native action dict for a check, if one is available.
Resolve known server actions through native methods. Return other server
actions without running them. No view is opened.
"""
action = check.with_context(working_file_id=check.return_id.id).action_review()
if not action or action.get('type') != 'ir.actions.server':
return action
context = action.get('context') or {}
check = check.with_context(**{**context, 'working_file_id': check.return_id.id})
if action.get('id') == self.env.ref('account_reports.action_audit_report').id:
return check.action_audit_report(check.return_id.id, context.get('action_xml_id'))
if action.get('id') == self.env.ref('account_reports.action_audit_custom_target').id and context.get('target') in (
'depreciation_schedule', 'inventory_valuation', 'fleet', 'documents', 'invoices_to_be_issued',
):
return check.action_audit_custom_target(check.return_id.id, context.get('target'))
if action.get('id') == self.env.ref(
'account_reports.action_server_open_view_account_return_with_additional_params',
).id:
return check.return_id.action_open_tax_return_view(
context.get('sub_action_domain'), context.get('sub_action_context'),
)
return action # Unknown executable actions are never run.
def _ai_tool_accounting_audit_get_check_action_detail(self, audit_id, check_code):
"""Describe a check's action without opening it or fetching evidence records.
Use audit_id (int) and check_code (str) to find the check. Return a dict
with action_detail and, for window actions, search and main view XML.
If no action exists, include the check instructions and attachment IDs.
"""
audit = self._audit_file(audit_id)
check = audit.check_ids.filtered(lambda c: c.code == check_code)
self._guard(check, 'Unknown check code. Read accounting_audit_get_checks first.')
action = self._audit_action(check)
# The tool dispatcher executes a top-level 'action' as navigation.
result = {
'audit_id': audit.id, 'check_code': check.code,
'company_ids': audit.company_ids.ids, 'action_detail': action,
}
if not action:
return {**result, 'hint': html2plaintext(check.message or ''),
'attachment_ids': check.attachment_ids.ids}
if action['type'] != 'ir.actions.act_window':
return result
self._check_agent_model_access(action['res_model'])
context = action.get('context') or {}
context = literal_eval(context) if isinstance(context, str) else context
model = self.env[action['res_model']].with_context(
**{**context, 'allowed_company_ids': self.env.companies.ids},
)
search_view_id = (action.get('search_view_id') or (False,))[0]
result['views'] = {
view_type: model.get_view(view_id, view_type)['arch']
for view_id, view_type in [(search_view_id, 'search'), action['views'][0]]
}
return result
def _ai_tool_accounting_audit_update_checks(self, tool_context, audit_id, cycle, updates):
"""Save a cycle's findings after confirmation and refresh its active view.
updates is a list of dicts with check_code, notes and result.
Return {result: dict, client_tool: dict}, or None with user_input_request
set while waiting for approval. result includes progress and updated codes.
"""
audit = self._audit_file(audit_id)
checks = self._audit_cycle_checks(audit, cycle)
self._guard(updates and len(updates) <= 100, 'Provide between 1 and 100 findings for one cycle.')
by_code = {check.code: check for check in checks}
self._guard(len({u['check_code'] for u in updates}) == len(updates), 'Duplicate check codes.')
checks.check_access('write')
self._guard(not audit.state, 'This working file has already been reviewed.')
for update in updates:
check = by_code.get(update['check_code'])
self._guard(check and check.type != 'file', 'Every finding must target a non-file check in this cycle.')
self._guard(update['notes'].strip(), 'Each finding needs non-blank notes.')
# Check names, results and notes are escaped by the literal Markup template's formatting.
rows = Markup('').join(Markup('<li><strong>%s — %s</strong><pre>%s</pre></li>') % (
by_code[u['check_code']].name, u['result'], u['notes'],
) for u in updates)
# Names are escaped here; rows were already built with escaping-aware formatting.
if self._audit_confirmation(tool_context, Markup('<p>Save findings for %s, cycle %s?</p><ul>%s</ul>') % (
audit.name, cycle, rows,
)):
return
# Native check tracking shares the parent return and field name.
# Finalize each change so a batch keeps separate, accurate entries.
audit._track_finalize()
for update in updates:
# Saving AI findings is not human approval of those findings.
by_code[update['check_code']].write({
'notes': update['notes'], 'result': update['result'],
'approver_ids': [Command.clear()],
})
audit._track_finalize()
result = {'updated_codes': [u['check_code'] for u in updates], **self._audit_progress(audit)}
action = {
'type': 'ir.actions.client', 'tag': 'action_return_refresh',
'params': {'return_ids': audit.ids},
}
return {'result': result, 'client_tool': {'name': 'do_action', 'oneway': True, 'params': {'action': action}}}

View File

@@ -0,0 +1,20 @@
import { AccountReport } from "@account_reports/components/account_report/account_report";
import { useDataGetter } from "@ai/utils/bus_data_getter";
import { patch } from "@web/core/utils/patch";
patch(AccountReport.prototype, {
setup() {
super.setup(...arguments);
useDataGetter("view", () => {
const options = this.controller.options();
return {
current_account_report: {
action_id: this.controller.action.id,
action_report_id: this.controller.actionReportId,
report_id: options.report_id,
options,
},
};
});
},
});