accountant_cn

This commit is contained in:
2026-11-17 17:57:08 +08:00
parent 9b924747c5
commit 5fc4382687
771 changed files with 18102 additions and 820280 deletions

View 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);