Compare commits
12 Commits
12fa20c4f1
...
fusion_acc
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d36933d7f4 | ||
|
|
1817f63c67 | ||
|
|
1ebff01d35 | ||
|
|
ff6d21a561 | ||
|
|
6896c71b79 | ||
|
|
111792599c | ||
|
|
679dbaa979 | ||
|
|
b15bf2293e | ||
|
|
9d8db0f9b1 | ||
|
|
ef2ccb89cf | ||
|
|
51d8ce494d | ||
|
|
190c296240 |
@@ -140,7 +140,11 @@ class TestFollowupAdapter(TransactionCase):
|
||||
|
||||
@tagged('post_install', '-at_install')
|
||||
class TestAssetsAdapter(TransactionCase):
|
||||
def test_list_assets_returns_list(self):
|
||||
def test_list_assets_returns_dict_with_assets(self):
|
||||
# Phase 3 (fusion_accounting_assets) wired list_assets to return
|
||||
# {count, total, assets} — consistent with bank_rec.list_unreconciled etc.
|
||||
adapter = get_adapter(self.env, 'assets')
|
||||
rows = adapter.list_assets()
|
||||
self.assertIsInstance(rows, list)
|
||||
self.assertIsInstance(rows, dict)
|
||||
self.assertIn('assets', rows)
|
||||
self.assertIsInstance(rows['assets'], list)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
@import "variables";
|
||||
// Variables come from _variables.scss via manifest concatenation order.
|
||||
// (V19 forbids cross-file SCSS imports; rely on bundle order instead.)
|
||||
|
||||
.o_fusion_assets {
|
||||
background: $asset-bg-secondary;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
@import "variables";
|
||||
// Variables come from _variables.scss via manifest concatenation order.
|
||||
|
||||
[data-color-scheme="dark"] .o_fusion_assets {
|
||||
background: #1f2937; color: #f9fafb;
|
||||
|
||||
@@ -2,13 +2,15 @@
|
||||
|
||||
import { registry } from "@web/core/registry";
|
||||
import { reactive } from "@odoo/owl";
|
||||
import { rpc } from "@web/core/network/rpc";
|
||||
|
||||
const ENDPOINT_BASE = "/fusion/assets";
|
||||
|
||||
export class AssetsService {
|
||||
constructor(env, services) {
|
||||
this.env = env;
|
||||
this.rpc = services.rpc;
|
||||
// V19: rpc is a standalone import, not a service.
|
||||
this.rpc = rpc;
|
||||
this.notification = services.notification;
|
||||
|
||||
this.state = reactive({
|
||||
@@ -142,7 +144,7 @@ export class AssetsService {
|
||||
}
|
||||
|
||||
export const assetsService = {
|
||||
dependencies: ["rpc", "notification"],
|
||||
dependencies: ["notification"],
|
||||
start(env, services) { return new AssetsService(env, services); },
|
||||
};
|
||||
|
||||
|
||||
@@ -74,7 +74,9 @@ class FusionMigrationWizard(models.TransientModel):
|
||||
Phase 0) and then runs the bank-rec bootstrap. Returns a
|
||||
notification summarizing both.
|
||||
"""
|
||||
_ = super().action_run_migration()
|
||||
# Don't bind super()'s return value to `_` \u2014 that shadows the
|
||||
# imported translation function and breaks the _("...") calls below.
|
||||
super().action_run_migration()
|
||||
result = self._bank_rec_bootstrap_step()
|
||||
return {
|
||||
'type': 'ir.actions.client',
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
@import "variables";
|
||||
// Variables come from _variables.scss via manifest concatenation order.
|
||||
|
||||
// ============================================================
|
||||
// AI Suggestion strip (inline, on each statement line card)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
@import "variables";
|
||||
// Variables come from _variables.scss via manifest concatenation order.
|
||||
// (V19 forbids cross-file SCSS imports; rely on bundle order instead.)
|
||||
|
||||
// ============================================================
|
||||
// Bank reconciliation kanban container
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
@import "variables";
|
||||
|
||||
// Variables come from _variables.scss via manifest concatenation order.
|
||||
// Activated via [data-color-scheme="dark"] on body or any ancestor.
|
||||
// Mirrors Odoo's standard dark-mode trigger pattern.
|
||||
|
||||
|
||||
@@ -14,13 +14,15 @@ import { registry } from "@web/core/registry";
|
||||
import { reactive, useState, EventBus } from "@odoo/owl";
|
||||
import { useService } from "@web/core/utils/hooks";
|
||||
import { browser } from "@web/core/browser/browser";
|
||||
import { rpc } from "@web/core/network/rpc";
|
||||
|
||||
const ENDPOINT_BASE = "/fusion/bank_rec";
|
||||
|
||||
export class BankReconciliationService {
|
||||
constructor(env, services) {
|
||||
this.env = env;
|
||||
this.rpc = services.rpc;
|
||||
// V19: rpc is no longer a service — imported as a standalone function above.
|
||||
this.rpc = rpc;
|
||||
this.notification = services.notification;
|
||||
this.orm = services.orm;
|
||||
|
||||
@@ -400,7 +402,7 @@ export class BankReconciliationService {
|
||||
}
|
||||
|
||||
export const bankReconciliationService = {
|
||||
dependencies: ["rpc", "notification", "orm"],
|
||||
dependencies: ["notification", "orm"],
|
||||
start(env, services) {
|
||||
return new BankReconciliationService(env, services);
|
||||
},
|
||||
|
||||
@@ -78,10 +78,120 @@ class FusionMigrationWizard(models.TransientModel):
|
||||
result['created'], result['skipped'], len(result['errors']))
|
||||
return result
|
||||
|
||||
def _followup_partner_state_bootstrap_step(self):
|
||||
"""Migration step: copy Enterprise account_followup per-partner state
|
||||
onto Fusion's fields on res.partner.
|
||||
|
||||
Idempotent: only updates partners whose Fusion field is at default
|
||||
(no_action) and whose Enterprise field has a non-default value.
|
||||
"""
|
||||
self.ensure_one()
|
||||
_logger.info("fusion_accounting_followup partner-state migration starting")
|
||||
|
||||
Partner = self.env['res.partner'].sudo()
|
||||
has_status = 'followup_status' in Partner._fields
|
||||
has_next_date = 'payment_next_action_date' in Partner._fields
|
||||
has_line = 'followup_line_id' in Partner._fields
|
||||
if not (has_status or has_next_date or has_line):
|
||||
_logger.info(
|
||||
"Enterprise account_followup partner fields not present \u2014 skipping")
|
||||
return {
|
||||
'step': 'followup_partner_state',
|
||||
'enterprise_module_present': False,
|
||||
'updated': 0, 'skipped': 0, 'errors': [],
|
||||
}
|
||||
|
||||
result = {
|
||||
'step': 'followup_partner_state',
|
||||
'enterprise_module_present': True,
|
||||
'updated': 0, 'skipped': 0, 'errors': [],
|
||||
}
|
||||
|
||||
domain_terms = []
|
||||
if has_status:
|
||||
domain_terms.append(('followup_status', '!=', 'no_action_needed'))
|
||||
if has_next_date:
|
||||
domain_terms.append(('payment_next_action_date', '!=', False))
|
||||
if not domain_terms:
|
||||
_logger.info("No usable Enterprise follow-up fields \u2014 skipping")
|
||||
return result
|
||||
if len(domain_terms) > 1:
|
||||
domain = ['|'] * (len(domain_terms) - 1) + domain_terms
|
||||
else:
|
||||
domain = domain_terms
|
||||
candidates = Partner.search(domain)
|
||||
_logger.info(
|
||||
"Found %d partners with non-default Enterprise follow-up state",
|
||||
len(candidates))
|
||||
|
||||
Level = self.env['fusion.followup.level'].sudo()
|
||||
today = fields.Date.today()
|
||||
|
||||
status_map = {
|
||||
'in_need_of_action': 'action_due',
|
||||
'with_overdue_invoices': 'action_due',
|
||||
'no_action_needed': 'no_action',
|
||||
}
|
||||
|
||||
for partner in candidates:
|
||||
try:
|
||||
if partner.fusion_followup_status not in (False, 'no_action'):
|
||||
result['skipped'] += 1
|
||||
continue
|
||||
|
||||
vals = {}
|
||||
|
||||
ent_status = (
|
||||
getattr(partner, 'followup_status', None)
|
||||
if has_status else None)
|
||||
if ent_status and ent_status in status_map:
|
||||
vals['fusion_followup_status'] = status_map[ent_status]
|
||||
|
||||
next_date = (
|
||||
getattr(partner, 'payment_next_action_date', False)
|
||||
if has_next_date else False)
|
||||
if next_date and next_date > today:
|
||||
vals['fusion_followup_paused_until'] = next_date
|
||||
vals['fusion_followup_status'] = 'paused'
|
||||
|
||||
ent_line = (
|
||||
getattr(partner, 'followup_line_id', None)
|
||||
if has_line else None)
|
||||
if ent_line:
|
||||
fusion_level = Level.search([
|
||||
('name', '=', ent_line.name),
|
||||
], limit=1)
|
||||
if fusion_level:
|
||||
vals['fusion_followup_last_level_id'] = fusion_level.id
|
||||
|
||||
if vals:
|
||||
partner.write(vals)
|
||||
result['updated'] += 1
|
||||
_logger.debug(
|
||||
"Migrated partner %s: %s", partner.name, vals)
|
||||
else:
|
||||
result['skipped'] += 1
|
||||
|
||||
except Exception as e:
|
||||
result['errors'].append(
|
||||
f"Partner {partner.id} ({partner.name}): {e}")
|
||||
_logger.warning(
|
||||
"Migration failed for partner %s: %s", partner.id, e)
|
||||
|
||||
_logger.info(
|
||||
"fusion_accounting_followup partner-state migration: "
|
||||
"updated=%d skipped=%d errors=%d",
|
||||
result['updated'], result['skipped'], len(result['errors']))
|
||||
return result
|
||||
|
||||
def action_run_migration(self):
|
||||
result = super().action_run_migration() if hasattr(super(), 'action_run_migration') else None
|
||||
try:
|
||||
self._followup_bootstrap_step()
|
||||
except Exception as e:
|
||||
_logger.warning("followup_bootstrap_step failed: %s", e)
|
||||
try:
|
||||
self._followup_partner_state_bootstrap_step()
|
||||
except Exception as e:
|
||||
_logger.warning("followup_partner_state_bootstrap_step failed: %s", e)
|
||||
return result
|
||||
|
||||
@@ -2,13 +2,15 @@
|
||||
|
||||
import { registry } from "@web/core/registry";
|
||||
import { reactive } from "@odoo/owl";
|
||||
import { rpc } from "@web/core/network/rpc";
|
||||
|
||||
const ENDPOINT_BASE = "/fusion/followup";
|
||||
|
||||
export class FollowupService {
|
||||
constructor(env, services) {
|
||||
this.env = env;
|
||||
this.rpc = services.rpc;
|
||||
// V19: rpc is a standalone import, not a service.
|
||||
this.rpc = rpc;
|
||||
this.notification = services.notification;
|
||||
|
||||
this.state = reactive({
|
||||
@@ -138,7 +140,7 @@ export class FollowupService {
|
||||
}
|
||||
|
||||
export const followupService = {
|
||||
dependencies: ["rpc", "notification"],
|
||||
dependencies: ["notification"],
|
||||
start(env, services) { return new FollowupService(env, services); },
|
||||
};
|
||||
|
||||
|
||||
@@ -19,3 +19,12 @@ class TestFollowupMigrationRoundTrip(TransactionCase):
|
||||
# Second run skips what first created (or both no-op)
|
||||
if first['enterprise_module_present']:
|
||||
self.assertGreaterEqual(second['skipped'], first['created'])
|
||||
|
||||
def test_partner_state_bootstrap_step(self):
|
||||
"""Verify the partner-state migration step runs without error."""
|
||||
wizard = self.env['fusion.migration.wizard'].create({})
|
||||
result = wizard._followup_partner_state_bootstrap_step()
|
||||
self.assertEqual(result['step'], 'followup_partner_state')
|
||||
self.assertIn(result['enterprise_module_present'], [True, False])
|
||||
self.assertGreaterEqual(result['updated'], 0)
|
||||
self.assertGreaterEqual(result['skipped'], 0)
|
||||
|
||||
@@ -36,6 +36,13 @@ menu hides; the engine and AI tools remain available for the chat.
|
||||
'data/report_balance_sheet.xml',
|
||||
'data/report_trial_balance.xml',
|
||||
'data/report_general_ledger.xml',
|
||||
'data/report_cash_flow.xml',
|
||||
'data/report_executive_summary.xml',
|
||||
'data/report_tax_report.xml',
|
||||
'data/report_annual_statements.xml',
|
||||
'data/report_aged_receivable.xml',
|
||||
'data/report_aged_payable.xml',
|
||||
'data/report_partner_ledger.xml',
|
||||
'data/cron.xml',
|
||||
'reports/report_pdf_template.xml',
|
||||
'wizards/xlsx_export_wizard_views.xml',
|
||||
|
||||
@@ -18,7 +18,16 @@ from ..services.date_periods import Period
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
REPORT_TYPES = {'pnl', 'balance_sheet', 'trial_balance', 'general_ledger'}
|
||||
REPORT_TYPES = {
|
||||
'pnl', 'balance_sheet', 'trial_balance', 'general_ledger',
|
||||
'aged_receivable', 'aged_payable', 'partner_ledger',
|
||||
}
|
||||
|
||||
PARTNER_GROUPED_ACCOUNT_TYPE = {
|
||||
'aged_receivable': 'asset_receivable',
|
||||
'aged_payable': 'liability_payable',
|
||||
'partner_ledger': 'asset_receivable',
|
||||
}
|
||||
|
||||
|
||||
def _parse_date(value):
|
||||
@@ -56,7 +65,7 @@ class FusionReportsController(http.Controller):
|
||||
|
||||
@http.route('/fusion/reports/run', type='jsonrpc', auth='user')
|
||||
def run(self, report_type, date_from=None, date_to=None,
|
||||
comparison='none', company_id=None):
|
||||
comparison='none', company_id=None, report_code=None):
|
||||
if report_type not in REPORT_TYPES:
|
||||
raise ValidationError(_("Unknown report type: %s") % report_type)
|
||||
company_id = int(company_id) if company_id else request.env.company.id
|
||||
@@ -66,19 +75,33 @@ class FusionReportsController(http.Controller):
|
||||
period = _build_period(date_from, date_to)
|
||||
return engine.compute_pnl(
|
||||
period, comparison=comparison, company_id=company_id,
|
||||
report_code=report_code,
|
||||
)
|
||||
if report_type == 'balance_sheet':
|
||||
return engine.compute_balance_sheet(
|
||||
_parse_date(date_to),
|
||||
comparison=comparison,
|
||||
company_id=company_id,
|
||||
report_code=report_code,
|
||||
)
|
||||
if report_type == 'trial_balance':
|
||||
period = _build_period(date_from, date_to)
|
||||
return engine.compute_trial_balance(period, company_id=company_id)
|
||||
return engine.compute_trial_balance(
|
||||
period, company_id=company_id, report_code=report_code,
|
||||
)
|
||||
if report_type in PARTNER_GROUPED_ACCOUNT_TYPE:
|
||||
period = _build_period(date_from, date_to)
|
||||
return engine.compute_partner_grouped(
|
||||
period,
|
||||
account_type=PARTNER_GROUPED_ACCOUNT_TYPE[report_type],
|
||||
comparison=comparison,
|
||||
company_id=company_id,
|
||||
)
|
||||
# general_ledger
|
||||
period = _build_period(date_from, date_to)
|
||||
return engine.compute_gl(period, company_id=company_id)
|
||||
return engine.compute_gl(
|
||||
period, company_id=company_id, report_code=report_code,
|
||||
)
|
||||
|
||||
@http.route('/fusion/reports/drill_down', type='jsonrpc', auth='user')
|
||||
def drill_down(self, account_id, date_from, date_to, company_id=None):
|
||||
|
||||
14
fusion_accounting_reports/data/report_aged_payable.xml
Normal file
14
fusion_accounting_reports/data/report_aged_payable.xml
Normal file
@@ -0,0 +1,14 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<odoo noupdate="1">
|
||||
<record id="report_aged_payable" model="fusion.report">
|
||||
<field name="name">Aged Payable</field>
|
||||
<field name="code">aged_payable</field>
|
||||
<field name="report_type">aged_payable</field>
|
||||
<field name="sequence">36</field>
|
||||
<field name="description">Per-vendor outstanding payables, bucketed by aging.</field>
|
||||
<field name="line_specs" eval="[
|
||||
{'label': 'Aged Payable', 'account_type_for_grouping': 'liability_payable'}
|
||||
]"/>
|
||||
<field name="company_id" eval="False"/>
|
||||
</record>
|
||||
</odoo>
|
||||
14
fusion_accounting_reports/data/report_aged_receivable.xml
Normal file
14
fusion_accounting_reports/data/report_aged_receivable.xml
Normal file
@@ -0,0 +1,14 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<odoo noupdate="1">
|
||||
<record id="report_aged_receivable" model="fusion.report">
|
||||
<field name="name">Aged Receivable</field>
|
||||
<field name="code">aged_receivable</field>
|
||||
<field name="report_type">aged_receivable</field>
|
||||
<field name="sequence">35</field>
|
||||
<field name="description">Per-customer outstanding receivables, bucketed by aging.</field>
|
||||
<field name="line_specs" eval="[
|
||||
{'label': 'Aged Receivable', 'account_type_for_grouping': 'asset_receivable'}
|
||||
]"/>
|
||||
<field name="company_id" eval="False"/>
|
||||
</record>
|
||||
</odoo>
|
||||
19
fusion_accounting_reports/data/report_annual_statements.xml
Normal file
19
fusion_accounting_reports/data/report_annual_statements.xml
Normal file
@@ -0,0 +1,19 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<odoo noupdate="1">
|
||||
<record id="report_annual_statements" model="fusion.report">
|
||||
<field name="name">Annual Statements</field>
|
||||
<field name="code">annual_statements</field>
|
||||
<field name="report_type">pnl</field>
|
||||
<field name="sequence">11</field>
|
||||
<field name="default_comparison_mode">previous_year</field>
|
||||
<field name="description">Year-over-year P&L comparison for annual reporting.</field>
|
||||
<field name="line_specs" eval="[
|
||||
{'label': 'Revenue', 'account_type_prefix': 'income', 'sign': -1, 'level': 0},
|
||||
{'label': 'Cost of Goods Sold', 'account_type_prefix': 'expense_direct_cost', 'sign': -1, 'level': 1},
|
||||
{'label': 'Gross Profit', 'compute': 'subtotal', 'above': 2, 'sign': 1, 'level': 0},
|
||||
{'label': 'Operating Expenses', 'account_type_prefix': 'expense', 'sign': -1, 'level': 1},
|
||||
{'label': 'OPERATING INCOME', 'compute': 'subtotal', 'above': 2, 'sign': 1, 'level': 0}
|
||||
]"/>
|
||||
<field name="company_id" eval="False"/>
|
||||
</record>
|
||||
</odoo>
|
||||
29
fusion_accounting_reports/data/report_cash_flow.xml
Normal file
29
fusion_accounting_reports/data/report_cash_flow.xml
Normal file
@@ -0,0 +1,29 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<odoo noupdate="1">
|
||||
<record id="report_cash_flow" model="fusion.report">
|
||||
<field name="name">Cash Flow Statement</field>
|
||||
<field name="code">cash_flow</field>
|
||||
<field name="report_type">pnl</field>
|
||||
<field name="sequence">15</field>
|
||||
<field name="default_comparison_mode">previous_year</field>
|
||||
<field name="description">Cash flow by activity (operating, investing, financing).</field>
|
||||
<field name="line_specs" eval="[
|
||||
{'label': 'Operating Activities', 'level': 0},
|
||||
{'label': 'Net Income (from operations)', 'account_type_prefix': 'income', 'sign': -1, 'level': 1},
|
||||
{'label': 'Depreciation Add-back', 'account_type_prefix': 'expense_depreciation', 'sign': 1, 'level': 1},
|
||||
{'label': 'Operating Cash Flow', 'compute': 'subtotal', 'above': 2, 'sign': 1, 'level': 0},
|
||||
|
||||
{'label': 'Investing Activities', 'level': 0},
|
||||
{'label': 'Fixed Asset Purchases', 'account_type_prefix': 'asset_fixed', 'sign': -1, 'level': 1},
|
||||
{'label': 'Investing Cash Flow', 'compute': 'subtotal', 'above': 1, 'sign': 1, 'level': 0},
|
||||
|
||||
{'label': 'Financing Activities', 'level': 0},
|
||||
{'label': 'Liabilities (long-term)', 'account_type_prefix': 'liability_non_current', 'sign': 1, 'level': 1},
|
||||
{'label': 'Equity', 'account_type_prefix': 'equity', 'sign': 1, 'level': 1},
|
||||
{'label': 'Financing Cash Flow', 'compute': 'subtotal', 'above': 2, 'sign': 1, 'level': 0},
|
||||
|
||||
{'label': 'NET CHANGE IN CASH', 'compute': 'subtotal', 'above': 3, 'sign': 1, 'level': 0}
|
||||
]"/>
|
||||
<field name="company_id" eval="False"/>
|
||||
</record>
|
||||
</odoo>
|
||||
24
fusion_accounting_reports/data/report_executive_summary.xml
Normal file
24
fusion_accounting_reports/data/report_executive_summary.xml
Normal file
@@ -0,0 +1,24 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<odoo noupdate="1">
|
||||
<record id="report_executive_summary" model="fusion.report">
|
||||
<field name="name">Executive Summary</field>
|
||||
<field name="code">executive_summary</field>
|
||||
<field name="report_type">pnl</field>
|
||||
<field name="sequence">5</field>
|
||||
<field name="default_comparison_mode">previous_year</field>
|
||||
<field name="description">Top-level KPI summary: revenue, expenses, net income, key balance positions.</field>
|
||||
<field name="line_specs" eval="[
|
||||
{'label': 'PROFIT & LOSS', 'level': 0},
|
||||
{'label': 'Revenue', 'account_type_prefix': 'income', 'sign': -1, 'level': 1},
|
||||
{'label': 'Expenses', 'account_type_prefix': 'expense', 'sign': -1, 'level': 1},
|
||||
{'label': 'Net Income', 'compute': 'subtotal', 'above': 2, 'sign': 1, 'level': 0},
|
||||
|
||||
{'label': 'BALANCE POSITIONS', 'level': 0},
|
||||
{'label': 'Cash & Bank', 'account_type_prefix': 'asset_cash', 'sign': 1, 'level': 1},
|
||||
{'label': 'Receivables', 'account_type_prefix': 'asset_receivable', 'sign': 1, 'level': 1},
|
||||
{'label': 'Payables', 'account_type_prefix': 'liability_payable', 'sign': -1, 'level': 1},
|
||||
{'label': 'Net Working Position', 'compute': 'subtotal', 'above': 3, 'sign': 1, 'level': 0}
|
||||
]"/>
|
||||
<field name="company_id" eval="False"/>
|
||||
</record>
|
||||
</odoo>
|
||||
14
fusion_accounting_reports/data/report_partner_ledger.xml
Normal file
14
fusion_accounting_reports/data/report_partner_ledger.xml
Normal file
@@ -0,0 +1,14 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<odoo noupdate="1">
|
||||
<record id="report_partner_ledger" model="fusion.report">
|
||||
<field name="name">Partner Ledger</field>
|
||||
<field name="code">partner_ledger</field>
|
||||
<field name="report_type">partner_ledger</field>
|
||||
<field name="sequence">40</field>
|
||||
<field name="description">Per-partner ledger combining receivable and payable activity.</field>
|
||||
<field name="line_specs" eval="[
|
||||
{'label': 'Partner Ledger', 'account_type_for_grouping': 'asset_receivable'}
|
||||
]"/>
|
||||
<field name="company_id" eval="False"/>
|
||||
</record>
|
||||
</odoo>
|
||||
16
fusion_accounting_reports/data/report_tax_report.xml
Normal file
16
fusion_accounting_reports/data/report_tax_report.xml
Normal file
@@ -0,0 +1,16 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<odoo noupdate="1">
|
||||
<record id="report_tax_summary" model="fusion.report">
|
||||
<field name="name">Tax Summary</field>
|
||||
<field name="code">tax_summary</field>
|
||||
<field name="report_type">trial_balance</field>
|
||||
<field name="sequence">25</field>
|
||||
<field name="description">Tax liability + asset positions. v1: aggregate-level only; per-tax-code breakdown is Phase 2.5.</field>
|
||||
<field name="line_specs" eval="[
|
||||
{'label': 'Tax Asset (recoverable)', 'account_type_prefix': 'asset_current', 'sign': 1, 'level': 0},
|
||||
{'label': 'Tax Liability (collected)', 'account_type_prefix': 'liability_current', 'sign': -1, 'level': 0},
|
||||
{'label': 'NET TAX POSITION', 'compute': 'subtotal', 'above': 2, 'sign': 1, 'level': 0}
|
||||
]"/>
|
||||
<field name="company_id" eval="False"/>
|
||||
</record>
|
||||
</odoo>
|
||||
@@ -13,6 +13,9 @@ REPORT_TYPES = [
|
||||
('balance_sheet', 'Balance Sheet'),
|
||||
('trial_balance', 'Trial Balance'),
|
||||
('general_ledger', 'General Ledger'),
|
||||
('aged_receivable', 'Aged Receivable'),
|
||||
('aged_payable', 'Aged Payable'),
|
||||
('partner_ledger', 'Partner Ledger'),
|
||||
]
|
||||
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ Internal pipeline (per report run):
|
||||
"""
|
||||
|
||||
import logging
|
||||
from datetime import date
|
||||
from datetime import date, timedelta
|
||||
|
||||
from odoo import _, api, models
|
||||
from odoo.exceptions import ValidationError
|
||||
@@ -39,10 +39,17 @@ class FusionReportEngine(models.AbstractModel):
|
||||
@api.model
|
||||
def compute_pnl(
|
||||
self, period: Period, *, comparison: str = 'none',
|
||||
company_id: int | None = None,
|
||||
company_id: int | None = None, report_code: str | None = None,
|
||||
) -> dict:
|
||||
"""Income statement (P&L) for the given period."""
|
||||
report = self._get_report('pnl', company_id=company_id)
|
||||
"""Income statement (P&L) for the given period.
|
||||
|
||||
``report_code`` selects between multiple PnL-typed report definitions
|
||||
(``pnl``, ``cash_flow``, ``executive_summary``, ``annual_statements``).
|
||||
When omitted, falls back to the canonical ``pnl`` definition.
|
||||
"""
|
||||
report = self._get_report(
|
||||
'pnl', company_id=company_id, code=report_code,
|
||||
)
|
||||
return self._compute(
|
||||
report, period, comparison=comparison, company_id=company_id,
|
||||
)
|
||||
@@ -50,11 +57,13 @@ class FusionReportEngine(models.AbstractModel):
|
||||
@api.model
|
||||
def compute_balance_sheet(
|
||||
self, date_to: date, *, comparison: str = 'none',
|
||||
company_id: int | None = None,
|
||||
company_id: int | None = None, report_code: str | None = None,
|
||||
) -> dict:
|
||||
"""Balance sheet AS OF date_to. Period.date_from is set to a
|
||||
far-past date so balances are cumulative-since-inception."""
|
||||
report = self._get_report('balance_sheet', company_id=company_id)
|
||||
report = self._get_report(
|
||||
'balance_sheet', company_id=company_id, code=report_code,
|
||||
)
|
||||
period = Period(
|
||||
date_from=date(1970, 1, 1),
|
||||
date_to=date_to,
|
||||
@@ -67,10 +76,17 @@ class FusionReportEngine(models.AbstractModel):
|
||||
@api.model
|
||||
def compute_trial_balance(
|
||||
self, period: Period, *, company_id: int | None = None,
|
||||
report_code: str | None = None,
|
||||
) -> dict:
|
||||
"""Trial balance for the given period - every account with
|
||||
non-zero balance."""
|
||||
report = self._get_report('trial_balance', company_id=company_id)
|
||||
non-zero balance.
|
||||
|
||||
``report_code`` selects between multiple TB-typed reports (e.g.
|
||||
``trial_balance``, ``tax_summary``).
|
||||
"""
|
||||
report = self._get_report(
|
||||
'trial_balance', company_id=company_id, code=report_code,
|
||||
)
|
||||
return self._compute(
|
||||
report, period, comparison='none', company_id=company_id,
|
||||
)
|
||||
@@ -78,12 +94,14 @@ class FusionReportEngine(models.AbstractModel):
|
||||
@api.model
|
||||
def compute_gl(
|
||||
self, period: Period, *, account_ids: list | None = None,
|
||||
company_id: int | None = None,
|
||||
company_id: int | None = None, report_code: str | None = None,
|
||||
) -> dict:
|
||||
"""General ledger for the given period.
|
||||
|
||||
Returns per-account move-line listings rather than aggregated rows."""
|
||||
report = self._get_report('general_ledger', company_id=company_id)
|
||||
report = self._get_report(
|
||||
'general_ledger', company_id=company_id, code=report_code,
|
||||
)
|
||||
company_id = company_id or self.env.company.id
|
||||
result = self._compute(
|
||||
report, period, comparison='none', company_id=company_id,
|
||||
@@ -118,27 +136,188 @@ class FusionReportEngine(models.AbstractModel):
|
||||
limit=500,
|
||||
)
|
||||
|
||||
@api.model
|
||||
def compute_partner_grouped(
|
||||
self, period: Period, *, account_type: str = 'asset_receivable',
|
||||
comparison: str = 'none', company_id: int | None = None,
|
||||
) -> dict:
|
||||
"""Per-partner aggregation report (Aged Receivable, Aged Payable,
|
||||
Partner Ledger).
|
||||
|
||||
Returns a dict with ``rows`` = list of partner-level aggregates.
|
||||
Each row has the partner_id, partner_name, total residual, and
|
||||
aging buckets: current / 1-30 / 31-60 / 61-90 / 90+ days past
|
||||
``period.date_to``.
|
||||
|
||||
SQL-direct for performance: a single GROUP BY query with conditional
|
||||
sum per bucket. Only un-reconciled, posted lines with non-zero
|
||||
residual at the as-of date are included.
|
||||
"""
|
||||
company_id = company_id or self.env.company.id
|
||||
|
||||
accounts = self.env['account.account'].sudo().search([
|
||||
('account_type', '=', account_type),
|
||||
('company_ids', 'in', company_id),
|
||||
])
|
||||
if not accounts:
|
||||
return {
|
||||
'report_type': 'partner_grouped',
|
||||
'account_type': account_type,
|
||||
'period': {
|
||||
'date_from': str(period.date_from),
|
||||
'date_to': str(period.date_to),
|
||||
'label': period.label,
|
||||
},
|
||||
'rows': [],
|
||||
'total': 0.0,
|
||||
'partner_count': 0,
|
||||
}
|
||||
|
||||
as_of = period.date_to
|
||||
d30 = as_of - timedelta(days=30)
|
||||
d60 = as_of - timedelta(days=60)
|
||||
d90 = as_of - timedelta(days=90)
|
||||
|
||||
self.env.cr.execute(
|
||||
"""
|
||||
SELECT
|
||||
COALESCE(p.id, 0) AS partner_id,
|
||||
COALESCE(p.name, '(no partner)') AS partner_name,
|
||||
SUM(aml.amount_residual) AS total_residual,
|
||||
SUM(CASE
|
||||
WHEN aml.date_maturity >= %s
|
||||
OR aml.date_maturity IS NULL
|
||||
THEN aml.amount_residual ELSE 0
|
||||
END) AS bucket_current,
|
||||
SUM(CASE
|
||||
WHEN aml.date_maturity < %s
|
||||
AND aml.date_maturity >= %s
|
||||
THEN aml.amount_residual ELSE 0
|
||||
END) AS bucket_1_30,
|
||||
SUM(CASE
|
||||
WHEN aml.date_maturity < %s
|
||||
AND aml.date_maturity >= %s
|
||||
THEN aml.amount_residual ELSE 0
|
||||
END) AS bucket_31_60,
|
||||
SUM(CASE
|
||||
WHEN aml.date_maturity < %s
|
||||
AND aml.date_maturity >= %s
|
||||
THEN aml.amount_residual ELSE 0
|
||||
END) AS bucket_61_90,
|
||||
SUM(CASE
|
||||
WHEN aml.date_maturity < %s
|
||||
THEN aml.amount_residual ELSE 0
|
||||
END) AS bucket_90_plus,
|
||||
COUNT(*) AS line_count
|
||||
FROM account_move_line aml
|
||||
LEFT JOIN res_partner p ON p.id = aml.partner_id
|
||||
WHERE aml.account_id = ANY(%s)
|
||||
AND aml.parent_state = 'posted'
|
||||
AND aml.reconciled = false
|
||||
AND aml.amount_residual != 0
|
||||
AND aml.company_id = %s
|
||||
AND aml.date <= %s
|
||||
GROUP BY p.id, p.name
|
||||
HAVING SUM(aml.amount_residual) != 0
|
||||
ORDER BY total_residual DESC
|
||||
""",
|
||||
(
|
||||
as_of,
|
||||
as_of, d30,
|
||||
d30, d60,
|
||||
d60, d90,
|
||||
d90,
|
||||
list(accounts.ids), company_id, as_of,
|
||||
),
|
||||
)
|
||||
|
||||
rows = []
|
||||
for r in self.env.cr.dictfetchall():
|
||||
rows.append({
|
||||
'partner_id': r['partner_id'] or False,
|
||||
'partner_name': r['partner_name'] or '(no partner)',
|
||||
'total': float(r['total_residual'] or 0),
|
||||
'bucket_current': float(r['bucket_current'] or 0),
|
||||
'bucket_1_30': float(r['bucket_1_30'] or 0),
|
||||
'bucket_31_60': float(r['bucket_31_60'] or 0),
|
||||
'bucket_61_90': float(r['bucket_61_90'] or 0),
|
||||
'bucket_90_plus': float(r['bucket_90_plus'] or 0),
|
||||
'line_count': r['line_count'],
|
||||
})
|
||||
|
||||
total = sum(r['total'] for r in rows)
|
||||
return {
|
||||
'report_type': 'partner_grouped',
|
||||
'account_type': account_type,
|
||||
'period': {
|
||||
'date_from': str(period.date_from),
|
||||
'date_to': str(period.date_to),
|
||||
'label': period.label,
|
||||
},
|
||||
'company_id': company_id,
|
||||
'rows': rows,
|
||||
'total': total,
|
||||
'partner_count': len(rows),
|
||||
}
|
||||
|
||||
# ============================================================
|
||||
# PRIVATE HELPERS
|
||||
# ============================================================
|
||||
|
||||
def _get_report(self, report_type: str, *, company_id: int | None = None):
|
||||
"""Look up the active fusion.report definition for a given
|
||||
type+company. If no per-company override, falls back to global
|
||||
(company_id=False)."""
|
||||
def _get_report(
|
||||
self, report_type: str, *, company_id: int | None = None,
|
||||
code: str | None = None,
|
||||
):
|
||||
"""Look up the active fusion.report definition.
|
||||
|
||||
When ``code`` is provided, prefer the report with that exact code
|
||||
(validating its ``report_type`` matches). Otherwise fall back to
|
||||
the canonical-by-type lookup: prefer code == report_type, then any
|
||||
report of that type. Per-company overrides win over global.
|
||||
"""
|
||||
Report = self.env['fusion.report'].sudo()
|
||||
company_id = company_id or self.env.company.id
|
||||
company_domain = [
|
||||
('active', '=', True),
|
||||
'|',
|
||||
('company_id', '=', company_id),
|
||||
('company_id', '=', False),
|
||||
]
|
||||
if code:
|
||||
report = Report.search(
|
||||
[('code', '=', code)] + company_domain,
|
||||
order='company_id desc nulls last',
|
||||
limit=1,
|
||||
)
|
||||
if not report:
|
||||
raise ValidationError(
|
||||
_("No active fusion.report definition with code '%s'") % code
|
||||
)
|
||||
if report.report_type != report_type:
|
||||
raise ValidationError(
|
||||
_("Report '%(code)s' has type '%(actual)s' but '%(expected)s' was expected.")
|
||||
% {
|
||||
'code': code,
|
||||
'actual': report.report_type,
|
||||
'expected': report_type,
|
||||
}
|
||||
)
|
||||
return report
|
||||
|
||||
# No code: prefer the canonical (code == report_type), then any
|
||||
# other report of that type.
|
||||
report = Report.search(
|
||||
[
|
||||
('report_type', '=', report_type),
|
||||
('active', '=', True),
|
||||
'|',
|
||||
('company_id', '=', company_id),
|
||||
('company_id', '=', False),
|
||||
],
|
||||
[('code', '=', report_type), ('report_type', '=', report_type)] + company_domain,
|
||||
order='company_id desc nulls last',
|
||||
limit=1,
|
||||
)
|
||||
if report:
|
||||
return report
|
||||
report = Report.search(
|
||||
[('report_type', '=', report_type)] + company_domain,
|
||||
order='company_id desc nulls last, sequence',
|
||||
limit=1,
|
||||
)
|
||||
if not report:
|
||||
raise ValidationError(
|
||||
_("No active fusion.report definition for type '%s'") % report_type
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
@import "variables";
|
||||
// Variables come from _variables.scss via manifest concatenation order.
|
||||
|
||||
[data-color-scheme="dark"] .o_fusion_reports {
|
||||
background: #1f2937;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
@import "variables";
|
||||
// Variables come from _variables.scss via manifest concatenation order.
|
||||
// (V19 forbids cross-file SCSS imports; rely on bundle order instead.)
|
||||
|
||||
.o_fusion_reports {
|
||||
background: $report-bg-secondary;
|
||||
|
||||
@@ -2,13 +2,15 @@
|
||||
|
||||
import { registry } from "@web/core/registry";
|
||||
import { reactive } from "@odoo/owl";
|
||||
import { rpc } from "@web/core/network/rpc";
|
||||
|
||||
const ENDPOINT_BASE = "/fusion/reports";
|
||||
|
||||
export class ReportsService {
|
||||
constructor(env, services) {
|
||||
this.env = env;
|
||||
this.rpc = services.rpc;
|
||||
// V19: rpc is a standalone import, not a service.
|
||||
this.rpc = rpc;
|
||||
this.notification = services.notification;
|
||||
|
||||
this.state = reactive({
|
||||
@@ -140,7 +142,7 @@ export class ReportsService {
|
||||
}
|
||||
|
||||
export const reportsService = {
|
||||
dependencies: ["rpc", "notification"],
|
||||
dependencies: ["notification"],
|
||||
start(env, services) { return new ReportsService(env, services); },
|
||||
};
|
||||
|
||||
|
||||
@@ -90,6 +90,75 @@ class TestFusionReportEngine(TransactionCase):
|
||||
)
|
||||
self.assertIsInstance(rows, list)
|
||||
|
||||
def test_compute_partner_grouped_receivable(self):
|
||||
period = Period(date(2025, 1, 1), date(2025, 12, 31), 'Test')
|
||||
result = self.env['fusion.report.engine'].compute_partner_grouped(
|
||||
period, account_type='asset_receivable',
|
||||
)
|
||||
self.assertEqual(result['report_type'], 'partner_grouped')
|
||||
self.assertEqual(result['account_type'], 'asset_receivable')
|
||||
self.assertIn('rows', result)
|
||||
self.assertIn('total', result)
|
||||
self.assertIn('partner_count', result)
|
||||
if result['rows']:
|
||||
for key in (
|
||||
'partner_name', 'total', 'bucket_current', 'bucket_1_30',
|
||||
'bucket_31_60', 'bucket_61_90', 'bucket_90_plus',
|
||||
):
|
||||
self.assertIn(key, result['rows'][0])
|
||||
|
||||
def test_report_code_disambiguates_same_report_type(self):
|
||||
"""Multiple reports of report_type='pnl' must each be addressable
|
||||
by code so the engine returns the requested definition's line_specs
|
||||
(not whichever was first by company_id)."""
|
||||
spec_one = [
|
||||
{'label': 'A', 'account_type_prefix': 'income_', 'sign': 1},
|
||||
]
|
||||
spec_two = [
|
||||
{'label': 'X', 'account_type_prefix': 'income_', 'sign': 1},
|
||||
{'label': 'Y', 'account_type_prefix': 'expense_', 'sign': -1},
|
||||
{'label': 'Z', 'account_type_prefix': 'asset_', 'sign': 1},
|
||||
]
|
||||
self.env['fusion.report'].create({
|
||||
'name': 'Variant One', 'code': 'variant_one',
|
||||
'report_type': 'pnl', 'line_specs': spec_one,
|
||||
'company_id': self.env.company.id,
|
||||
})
|
||||
self.env['fusion.report'].create({
|
||||
'name': 'Variant Two', 'code': 'variant_two',
|
||||
'report_type': 'pnl', 'line_specs': spec_two,
|
||||
'company_id': self.env.company.id,
|
||||
})
|
||||
period = Period(date(2026, 1, 1), date(2026, 12, 31), 'Test')
|
||||
engine = self.env['fusion.report.engine']
|
||||
r1 = engine.compute_pnl(
|
||||
period, company_id=self.env.company.id,
|
||||
report_code='variant_one',
|
||||
)
|
||||
r2 = engine.compute_pnl(
|
||||
period, company_id=self.env.company.id,
|
||||
report_code='variant_two',
|
||||
)
|
||||
self.assertEqual(r1['report_name'], 'Variant One')
|
||||
self.assertEqual(r2['report_name'], 'Variant Two')
|
||||
self.assertEqual(len(r1['rows']), 1)
|
||||
self.assertEqual(len(r2['rows']), 3)
|
||||
|
||||
def test_report_code_validates_type_match(self):
|
||||
"""Asking for a 'pnl' computation but giving a balance_sheet code
|
||||
should raise ValidationError, not silently mis-render."""
|
||||
self.env['fusion.report'].create({
|
||||
'name': 'Wrong Type', 'code': 'wrong_type_test',
|
||||
'report_type': 'balance_sheet', 'line_specs': [],
|
||||
'company_id': self.env.company.id,
|
||||
})
|
||||
period = Period(date(2026, 1, 1), date(2026, 12, 31), 'Test')
|
||||
with self.assertRaises(ValidationError):
|
||||
self.env['fusion.report.engine'].compute_pnl(
|
||||
period, company_id=self.env.company.id,
|
||||
report_code='wrong_type_test',
|
||||
)
|
||||
|
||||
def test_no_report_raises_validation_error(self):
|
||||
period = Period(date(2026, 1, 1), date(2026, 12, 31), 'Test 2026')
|
||||
# Inactivate any pre-existing GL definitions so the lookup
|
||||
|
||||
@@ -440,25 +440,36 @@ class MrpProduction(models.Model):
|
||||
for override in production.x_fc_override_ids:
|
||||
override_map[override.node_id.id] = override.included
|
||||
|
||||
# Start-at-node: if set, build the set of node IDs that are
|
||||
# "at or descended from" the start node OR on its ancestor
|
||||
# path (so we keep the containing recipe / sub-processes
|
||||
# visible but skip sibling branches that come before the
|
||||
# start point).
|
||||
# Start-at-node: if set, the allowed set is the union of:
|
||||
# 1. start_node and all its descendants (we run these)
|
||||
# 2. each ancestor of start_node (to preserve the container
|
||||
# hierarchy the recipe walker uses to reach start_node)
|
||||
# 3. at each ancestor level, any LATER-sequence sibling and
|
||||
# all of its descendants (these come after start_node
|
||||
# in the flow and must still run)
|
||||
# Earlier siblings at each level are implicitly skipped.
|
||||
start_node = production.x_fc_start_at_node_id
|
||||
allowed_ids = None # None = include everything
|
||||
if start_node:
|
||||
# Descendants (inclusive)
|
||||
descendants = self.env['fusion.plating.process.node'].search([
|
||||
('id', 'child_of', start_node.id),
|
||||
])
|
||||
# Ancestors (excluding self — already in descendants)
|
||||
ancestors = self.env['fusion.plating.process.node']
|
||||
cur = start_node.parent_id
|
||||
while cur:
|
||||
ancestors |= cur
|
||||
cur = cur.parent_id
|
||||
allowed_ids = set(descendants.ids) | set(ancestors.ids)
|
||||
Node = self.env['fusion.plating.process.node']
|
||||
# 1. Descendants of start_node (inclusive)
|
||||
descendants = Node.search([('id', 'child_of', start_node.id)])
|
||||
allowed_ids = set(descendants.ids)
|
||||
# 2+3. Walk up; at each level add the parent and the
|
||||
# later-sibling subtrees.
|
||||
cur = start_node
|
||||
while cur.parent_id:
|
||||
parent = cur.parent_id
|
||||
allowed_ids.add(parent.id)
|
||||
later_sibs = parent.child_ids.filtered(
|
||||
lambda n: n.sequence > cur.sequence
|
||||
)
|
||||
for sib in later_sibs:
|
||||
sib_descendants = Node.search([
|
||||
('id', 'child_of', sib.id),
|
||||
])
|
||||
allowed_ids |= set(sib_descendants.ids)
|
||||
cur = parent
|
||||
|
||||
# Bind the source SO once per production so walk_node closure
|
||||
# can read coating config / spec without an extra search per WO.
|
||||
|
||||
@@ -110,9 +110,15 @@ class SaleOrder(models.Model):
|
||||
"""
|
||||
self.ensure_one()
|
||||
Production = self.env['mrp.production']
|
||||
existing_tags = set(Production.search([
|
||||
('origin', '=', self.name),
|
||||
]).mapped('x_fc_wo_group_tag'))
|
||||
existing_mos = Production.search([('origin', '=', self.name)])
|
||||
existing_tags = set(existing_mos.mapped('x_fc_wo_group_tag'))
|
||||
# Legacy MOs = untagged MOs created before this PR that never
|
||||
# had x_fc_sale_order_line_ids populated. We adopt them 1-for-1
|
||||
# onto the first N untagged groups so re-confirm doesn't
|
||||
# double-book.
|
||||
legacy_untagged = existing_mos.filtered(
|
||||
lambda m: not m.x_fc_wo_group_tag and not m.x_fc_sale_order_line_ids
|
||||
)
|
||||
|
||||
# Build groups from SO lines that carry plating data
|
||||
plating_lines = self.order_line.filtered(
|
||||
@@ -121,94 +127,141 @@ class SaleOrder(models.Model):
|
||||
if not plating_lines:
|
||||
return self._fp_auto_create_mo_legacy()
|
||||
|
||||
groups = {} # {tag_or_line_key: [lines]}
|
||||
for line in plating_lines:
|
||||
key = line.x_fc_wo_group_tag or ('__line__%d' % line.id)
|
||||
groups.setdefault(key, []).append(line)
|
||||
|
||||
created = []
|
||||
adopted = []
|
||||
|
||||
# If a legacy untagged MO already exists for this SO, it
|
||||
# represents the pre-PR "one MO for the whole order" work.
|
||||
# Adopt it by linking EVERY untagged plating line to it, and
|
||||
# treat those lines as covered — don't create per-line MOs on
|
||||
# top of the legacy MO.
|
||||
untagged_lines = plating_lines.filtered(lambda l: not l.x_fc_wo_group_tag)
|
||||
tagged_lines = plating_lines - untagged_lines
|
||||
covered_untagged_ids = set()
|
||||
if legacy_untagged and untagged_lines:
|
||||
legacy = legacy_untagged[0]
|
||||
legacy.write({
|
||||
'x_fc_sale_order_line_ids': [(4, ln.id) for ln in untagged_lines],
|
||||
})
|
||||
adopted.append(legacy)
|
||||
covered_untagged_ids = set(untagged_lines.ids)
|
||||
|
||||
groups = {} # {tag_or_line_key: [lines]}
|
||||
for line in tagged_lines:
|
||||
groups.setdefault(line.x_fc_wo_group_tag, []).append(line)
|
||||
for line in untagged_lines:
|
||||
if line.id in covered_untagged_ids:
|
||||
continue # already adopted onto legacy MO
|
||||
groups['__line__%d' % line.id] = [line]
|
||||
|
||||
for key, lines in groups.items():
|
||||
tag = lines[0].x_fc_wo_group_tag or False
|
||||
# Skip if we already have an MO for this (origin, tag) pair.
|
||||
# Untagged keys are 1:1 with lines; use the line ID in sudo
|
||||
# check via existing MOs' line links.
|
||||
if tag and tag in existing_tags:
|
||||
continue
|
||||
if not tag:
|
||||
# Untagged idempotency — check if any existing MO points
|
||||
# at this line via x_fc_sale_order_line_ids.
|
||||
# Untagged link-based idempotency (rerun protection)
|
||||
if Production.search_count([
|
||||
('origin', '=', self.name),
|
||||
('x_fc_sale_order_line_ids', 'in', [lines[0].id]),
|
||||
]):
|
||||
continue
|
||||
|
||||
# Resolve product: part catalog's linked product if any, else
|
||||
# FP-WIDGET fallback.
|
||||
product = False
|
||||
for ln in lines:
|
||||
pc = ln.x_fc_part_catalog_id
|
||||
if pc and 'product_id' in pc._fields and pc.product_id:
|
||||
product = pc.product_id
|
||||
break
|
||||
if not product:
|
||||
product = self.env['product.product'].search(
|
||||
[('default_code', '=', 'FP-WIDGET')], limit=1,
|
||||
)
|
||||
if not product:
|
||||
# Per-group savepoint so one broken group can't block later
|
||||
# ones AND can't leave partial state committed.
|
||||
savepoint_name = 'fp_mo_group_%s' % abs(hash(key))
|
||||
self.env.cr.execute('SAVEPOINT %s' % savepoint_name)
|
||||
try:
|
||||
# Resolve product: part catalog's linked product if any,
|
||||
# else FP-WIDGET fallback.
|
||||
product = False
|
||||
for ln in lines:
|
||||
pc = ln.x_fc_part_catalog_id
|
||||
if pc and 'product_id' in pc._fields and pc.product_id:
|
||||
product = pc.product_id
|
||||
break
|
||||
if not product:
|
||||
product = self.env['product.product'].search(
|
||||
[('default_code', '=', 'FP-WIDGET')], limit=1,
|
||||
)
|
||||
if not product:
|
||||
self.env.cr.execute('RELEASE SAVEPOINT %s' % savepoint_name)
|
||||
self.message_post(body=_(
|
||||
'Auto-MO skipped (group %s) — no manufacturable '
|
||||
'product available.'
|
||||
) % (tag or 'single-line'))
|
||||
continue
|
||||
|
||||
# Recipe: first line's coating -> recipe_id.
|
||||
recipe = False
|
||||
for ln in lines:
|
||||
cc = ln.x_fc_coating_config_id
|
||||
if cc and 'recipe_id' in cc._fields and cc.recipe_id:
|
||||
recipe = cc.recipe_id
|
||||
break
|
||||
if not recipe:
|
||||
recipe = self.env['fusion.plating.process.node'].search(
|
||||
[('node_type', '=', 'recipe')], limit=1,
|
||||
)
|
||||
|
||||
qty = sum(ln.product_uom_qty for ln in lines) or 1
|
||||
# Start-at-node: first non-blank wins
|
||||
start_node = False
|
||||
for ln in lines:
|
||||
if ln.x_fc_start_at_node_id:
|
||||
start_node = ln.x_fc_start_at_node_id
|
||||
break
|
||||
|
||||
mo_vals = {
|
||||
'product_id': product.id,
|
||||
'product_qty': qty,
|
||||
'product_uom_id': product.uom_id.id,
|
||||
'origin': self.name,
|
||||
'x_fc_wo_group_tag': tag or False,
|
||||
'x_fc_sale_order_line_ids': [(6, 0, [ln.id for ln in lines])],
|
||||
}
|
||||
if recipe and 'x_fc_recipe_id' in Production._fields:
|
||||
mo_vals['x_fc_recipe_id'] = recipe.id
|
||||
if start_node:
|
||||
mo_vals['x_fc_start_at_node_id'] = start_node.id
|
||||
mo = Production.create(mo_vals)
|
||||
created.append((mo, tag, len(lines)))
|
||||
self.env.cr.execute('RELEASE SAVEPOINT %s' % savepoint_name)
|
||||
except Exception as exc:
|
||||
self.env.cr.execute('ROLLBACK TO SAVEPOINT %s' % savepoint_name)
|
||||
self.message_post(body=_(
|
||||
'Auto-MO skipped (group %s) — no manufacturable '
|
||||
'product available.'
|
||||
) % (tag or 'single-line'))
|
||||
'Auto-MO group %s failed: %s'
|
||||
) % (tag or 'single-line', exc))
|
||||
continue
|
||||
|
||||
# Recipe: first line's coating -> recipe_id.
|
||||
recipe = False
|
||||
for ln in lines:
|
||||
cc = ln.x_fc_coating_config_id
|
||||
if cc and 'recipe_id' in cc._fields and cc.recipe_id:
|
||||
recipe = cc.recipe_id
|
||||
break
|
||||
if not recipe:
|
||||
recipe = self.env['fusion.plating.process.node'].search(
|
||||
[('node_type', '=', 'recipe')], limit=1,
|
||||
if created or adopted:
|
||||
msg_parts = []
|
||||
if created:
|
||||
lines_html = '<br/>'.join([
|
||||
_('MO <a href="/odoo/manufacturing/%s">%s</a> '
|
||||
'(%s, %d source line%s)') % (
|
||||
mo.id, mo.name, tag or 'untagged',
|
||||
n, 's' if n != 1 else ''
|
||||
)
|
||||
for mo, tag, n in created
|
||||
])
|
||||
msg_parts.append(
|
||||
_('%d draft MO(s) auto-created:<br/>%s') % (
|
||||
len(created), lines_html,
|
||||
)
|
||||
)
|
||||
|
||||
qty = sum(ln.product_uom_qty for ln in lines) or 1
|
||||
# Start-at-node: first non-blank wins
|
||||
start_node = False
|
||||
for ln in lines:
|
||||
if ln.x_fc_start_at_node_id:
|
||||
start_node = ln.x_fc_start_at_node_id
|
||||
break
|
||||
|
||||
mo_vals = {
|
||||
'product_id': product.id,
|
||||
'product_qty': qty,
|
||||
'product_uom_id': product.uom_id.id,
|
||||
'origin': self.name,
|
||||
'x_fc_wo_group_tag': tag or False,
|
||||
'x_fc_sale_order_line_ids': [(6, 0, [ln.id for ln in lines])],
|
||||
}
|
||||
if recipe and 'x_fc_recipe_id' in Production._fields:
|
||||
mo_vals['x_fc_recipe_id'] = recipe.id
|
||||
if start_node:
|
||||
mo_vals['x_fc_start_at_node_id'] = start_node.id
|
||||
mo = Production.create(mo_vals)
|
||||
created.append((mo, tag, len(lines)))
|
||||
|
||||
if created:
|
||||
lines_html = '<br/>'.join([
|
||||
_('MO <a href="/odoo/manufacturing/%s">%s</a> '
|
||||
'(%s, %d source line%s)') % (
|
||||
mo.id, mo.name, tag or 'untagged',
|
||||
n, 's' if n != 1 else ''
|
||||
)
|
||||
for mo, tag, n in created
|
||||
])
|
||||
self.message_post(body=Markup(_(
|
||||
'%d draft manufacturing order(s) auto-created:<br/>%s'
|
||||
)) % (len(created), lines_html))
|
||||
if adopted:
|
||||
adopted_html = '<br/>'.join([
|
||||
_('MO <a href="/odoo/manufacturing/%s">%s</a> '
|
||||
'(legacy, now line-linked)') % (mo.id, mo.name)
|
||||
for mo in adopted
|
||||
])
|
||||
msg_parts.append(
|
||||
_('%d legacy MO(s) adopted:<br/>%s') % (
|
||||
len(adopted), adopted_html,
|
||||
)
|
||||
)
|
||||
self.message_post(body=Markup('<br/><br/>'.join(msg_parts)))
|
||||
|
||||
def _fp_auto_create_mo_legacy(self):
|
||||
"""Fallback for SOs with no plating order_line data (service lines).
|
||||
|
||||
@@ -131,18 +131,44 @@ class SaleOrder(models.Model):
|
||||
currency_field='currency_id',
|
||||
)
|
||||
|
||||
@api.depends('name')
|
||||
def _compute_wo_completion(self):
|
||||
"""Batched: one grouped query across all records in self."""
|
||||
for rec in self:
|
||||
rec.x_fc_wo_completion = '0/0'
|
||||
names = [so.name for so in self if so.name]
|
||||
if not names:
|
||||
return
|
||||
WO = self.env['mrp.workorder'].sudo()
|
||||
rows = WO.read_group(
|
||||
[('production_id.origin', 'in', names)],
|
||||
['production_id.origin', 'state'],
|
||||
['production_id', 'state'],
|
||||
lazy=False,
|
||||
)
|
||||
# Build {origin: {'done': n, 'total': n}}
|
||||
# read_group returns production_id as (id, name) tuples; we need
|
||||
# to translate back to origin. Do a small lookup.
|
||||
mos = self.env['mrp.production'].sudo().search(
|
||||
[('origin', 'in', names)]
|
||||
)
|
||||
mo_to_origin = {m.id: m.origin for m in mos}
|
||||
totals = {} # {origin: [total, done]}
|
||||
for r in rows:
|
||||
mo_id = r['production_id'][0] if r['production_id'] else False
|
||||
origin = mo_to_origin.get(mo_id)
|
||||
if not origin:
|
||||
continue
|
||||
cnt = r['__count']
|
||||
bucket = totals.setdefault(origin, [0, 0])
|
||||
bucket[0] += cnt
|
||||
if r['state'] == 'done':
|
||||
bucket[1] += cnt
|
||||
for rec in self:
|
||||
if not rec.name:
|
||||
rec.x_fc_wo_completion = '0/0'
|
||||
continue
|
||||
total = WO.search_count([('production_id.origin', '=', rec.name)])
|
||||
done = WO.search_count([
|
||||
('production_id.origin', '=', rec.name),
|
||||
('state', '=', 'done'),
|
||||
])
|
||||
rec.x_fc_wo_completion = '%d/%d' % (done, total) if total else '0/0'
|
||||
tot, done = totals.get(rec.name, [0, 0])
|
||||
rec.x_fc_wo_completion = '%d/%d' % (done, tot) if tot else '0/0'
|
||||
|
||||
# ---- Phase F: quotes list view polish ----
|
||||
x_fc_follow_up_date = fields.Date(
|
||||
@@ -195,10 +221,14 @@ class SaleOrder(models.Model):
|
||||
def _compute_email_status(self):
|
||||
"""Map state + mail tracking to a single visible pill.
|
||||
|
||||
- draft SO with no tracked email sent => draft
|
||||
- sent (Odoo state) => sent
|
||||
- sent + mail opened => opened (detected via mail.message)
|
||||
- state=sale/done => won
|
||||
- state draft => draft
|
||||
- state sent => sent (or 'opened' if the customer partner has
|
||||
a read notification for any email message on this SO)
|
||||
- state sale / done => won
|
||||
|
||||
'Opened' is scoped to the CUSTOMER partner's notifications —
|
||||
not internal CCs — to avoid false positives from sales-ops
|
||||
viewing the thread.
|
||||
"""
|
||||
for rec in self:
|
||||
if rec.state in ('sale', 'done'):
|
||||
@@ -209,19 +239,17 @@ class SaleOrder(models.Model):
|
||||
continue
|
||||
# state == 'sent'
|
||||
opened = False
|
||||
if rec.id:
|
||||
msgs = self.env['mail.message'].sudo().search([
|
||||
('model', '=', 'sale.order'),
|
||||
('res_id', '=', rec.id),
|
||||
('message_type', '=', 'email'),
|
||||
], limit=10)
|
||||
# mail.notification tracks read timestamps
|
||||
for m in msgs:
|
||||
if m.notification_ids.filtered(
|
||||
lambda n: n.is_read
|
||||
):
|
||||
opened = True
|
||||
break
|
||||
if rec.id and rec.partner_id:
|
||||
# Look for any read notification on any email message
|
||||
# of this SO that targeted the customer.
|
||||
notif_count = self.env['mail.notification'].sudo().search_count([
|
||||
('mail_message_id.model', '=', 'sale.order'),
|
||||
('mail_message_id.res_id', '=', rec.id),
|
||||
('mail_message_id.message_type', '=', 'email'),
|
||||
('res_partner_id', '=', rec.partner_id.id),
|
||||
('is_read', '=', True),
|
||||
])
|
||||
opened = notif_count > 0
|
||||
rec.x_fc_email_status = 'opened' if opened else 'sent'
|
||||
|
||||
@api.depends('order_line.x_fc_part_catalog_id.part_number')
|
||||
@@ -254,16 +282,33 @@ class SaleOrder(models.Model):
|
||||
- sum(refunds.mapped('amount_total'))
|
||||
)
|
||||
|
||||
@api.depends('name')
|
||||
def _compute_workorder_count(self):
|
||||
WO = self.env['mrp.workorder'].sudo()
|
||||
for rec in self:
|
||||
if not rec.name:
|
||||
rec.x_fc_workorder_count = 0
|
||||
continue
|
||||
rec.x_fc_workorder_count = WO.search_count([
|
||||
('production_id.origin', '=', rec.name),
|
||||
('state', 'not in', ('done', 'cancel')),
|
||||
])
|
||||
rec.x_fc_workorder_count = 0
|
||||
names = [so.name for so in self if so.name]
|
||||
if not names:
|
||||
return
|
||||
WO = self.env['mrp.workorder'].sudo()
|
||||
rows = WO.read_group(
|
||||
[('production_id.origin', 'in', names),
|
||||
('state', 'not in', ('done', 'cancel'))],
|
||||
['production_id'],
|
||||
['production_id'],
|
||||
lazy=False,
|
||||
)
|
||||
mos = self.env['mrp.production'].sudo().search(
|
||||
[('origin', 'in', names)]
|
||||
)
|
||||
mo_to_origin = {m.id: m.origin for m in mos}
|
||||
totals = {}
|
||||
for r in rows:
|
||||
mo_id = r['production_id'][0] if r['production_id'] else False
|
||||
origin = mo_to_origin.get(mo_id)
|
||||
if origin:
|
||||
totals[origin] = totals.get(origin, 0) + r['__count']
|
||||
for rec in self:
|
||||
rec.x_fc_workorder_count = totals.get(rec.name, 0)
|
||||
|
||||
def action_view_workorders(self):
|
||||
self.ensure_one()
|
||||
@@ -290,21 +335,41 @@ class SaleOrder(models.Model):
|
||||
string='Files', compute='_compute_nav_counts',
|
||||
)
|
||||
|
||||
@api.depends('invoice_ids', 'picking_ids')
|
||||
def _compute_nav_counts(self):
|
||||
NCR = self.env.get('fusion.plating.ncr')
|
||||
# Invoice + picking counts are cheap (related collections).
|
||||
for rec in self:
|
||||
rec.x_fc_invoice_count = len(rec.invoice_ids)
|
||||
rec.x_fc_picking_count = len(rec.picking_ids)
|
||||
rec.x_fc_attachment_count = self.env['ir.attachment'].sudo().search_count([
|
||||
('res_model', '=', 'sale.order'),
|
||||
('res_id', '=', rec.id),
|
||||
])
|
||||
if NCR and 'sale_order_id' in NCR._fields:
|
||||
rec.x_fc_ncr_count = NCR.sudo().search_count([
|
||||
('sale_order_id', '=', rec.id),
|
||||
])
|
||||
else:
|
||||
rec.x_fc_ncr_count = 0
|
||||
|
||||
# Attachment counts — batched read_group.
|
||||
ids = self.ids
|
||||
att_counts = {}
|
||||
if ids:
|
||||
rows = self.env['ir.attachment'].sudo().read_group(
|
||||
[('res_model', '=', 'sale.order'),
|
||||
('res_id', 'in', ids)],
|
||||
['res_id'], ['res_id'], lazy=False,
|
||||
)
|
||||
att_counts = {r['res_id']: r['__count'] for r in rows}
|
||||
for rec in self:
|
||||
rec.x_fc_attachment_count = att_counts.get(rec.id, 0)
|
||||
|
||||
# NCR counts — only if the module is installed.
|
||||
NCR = self.env.get('fusion.plating.ncr')
|
||||
ncr_counts = {}
|
||||
if ids and NCR is not None and 'sale_order_id' in NCR._fields:
|
||||
rows = NCR.sudo().read_group(
|
||||
[('sale_order_id', 'in', ids)],
|
||||
['sale_order_id'], ['sale_order_id'], lazy=False,
|
||||
)
|
||||
ncr_counts = {
|
||||
(r['sale_order_id'][0] if r['sale_order_id'] else False):
|
||||
r['__count']
|
||||
for r in rows
|
||||
}
|
||||
for rec in self:
|
||||
rec.x_fc_ncr_count = ncr_counts.get(rec.id, 0)
|
||||
|
||||
def action_view_invoices(self):
|
||||
self.ensure_one()
|
||||
@@ -421,19 +486,23 @@ class SaleOrder(models.Model):
|
||||
|
||||
@api.depends('order_line.price_subtotal', 'amount_untaxed')
|
||||
def _compute_margin(self):
|
||||
"""Simple margin: untaxed total minus rolled-up cost from coating configs."""
|
||||
"""Simple margin: untaxed total minus rolled-up cost from coating configs.
|
||||
|
||||
x_fc_margin_percent is stored as a fraction (0.0 - 1.0) so the
|
||||
widget='percentage' formats it correctly (a 100% margin reads
|
||||
as 100%, not 10000%).
|
||||
"""
|
||||
for rec in self:
|
||||
cost = 0.0
|
||||
for line in rec.order_line:
|
||||
if line.x_fc_coating_config_id:
|
||||
# If coating_config has a cost field, use it; otherwise 0.
|
||||
cost_per_unit = getattr(
|
||||
line.x_fc_coating_config_id, 'unit_cost', 0.0,
|
||||
) or 0.0
|
||||
cost += cost_per_unit * (line.product_uom_qty or 0)
|
||||
rec.x_fc_margin_amount = (rec.amount_untaxed or 0) - cost
|
||||
rec.x_fc_margin_percent = (
|
||||
(rec.x_fc_margin_amount / rec.amount_untaxed * 100.0)
|
||||
(rec.x_fc_margin_amount / rec.amount_untaxed)
|
||||
if rec.amount_untaxed else 0.0
|
||||
)
|
||||
|
||||
|
||||
@@ -96,15 +96,20 @@
|
||||
<br/>
|
||||
<small t-field="line.name"/>
|
||||
</td>
|
||||
<td t-field="line.x_fc_coating_config_id"/>
|
||||
<td class="text-end"
|
||||
t-field="line.product_uom_qty"/>
|
||||
<td class="text-end"
|
||||
t-field="line.price_unit"
|
||||
t-options='{"widget": "monetary", "display_currency": doc.currency_id}'/>
|
||||
<td class="text-end"
|
||||
t-field="line.price_subtotal"
|
||||
t-options='{"widget": "monetary", "display_currency": doc.currency_id}'/>
|
||||
<td>
|
||||
<span t-field="line.x_fc_coating_config_id"/>
|
||||
</td>
|
||||
<td class="text-end">
|
||||
<span t-field="line.product_uom_qty"/>
|
||||
</td>
|
||||
<td class="text-end">
|
||||
<span t-field="line.price_unit"
|
||||
t-options='{"widget": "monetary", "display_currency": doc.currency_id}'/>
|
||||
</td>
|
||||
<td class="text-end">
|
||||
<span t-field="line.price_subtotal"
|
||||
t-options='{"widget": "monetary", "display_currency": doc.currency_id}'/>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
<tfoot>
|
||||
@@ -113,8 +118,10 @@
|
||||
<strong>Total</strong>
|
||||
</td>
|
||||
<td class="text-end">
|
||||
<strong t-field="doc.amount_total"
|
||||
t-options='{"widget": "monetary", "display_currency": doc.currency_id}'/>
|
||||
<strong>
|
||||
<span t-field="doc.amount_total"
|
||||
t-options='{"widget": "monetary", "display_currency": doc.currency_id}'/>
|
||||
</strong>
|
||||
</td>
|
||||
</tr>
|
||||
</tfoot>
|
||||
|
||||
@@ -94,9 +94,11 @@ class FpDirectOrderLine(models.TransientModel):
|
||||
start_at_node_id = fields.Many2one(
|
||||
'fusion.plating.process.node',
|
||||
string='Start at Node',
|
||||
domain="[('parent_id', 'child_of', coating_config_id and coating_config_id.recipe_id.id)]",
|
||||
domain="[('id', 'child_of', coating_config_id and coating_config_id.recipe_id.id or 0)]",
|
||||
help='For re-work jobs: pick the recipe step where this job should '
|
||||
'begin. Skips ancestor steps in the generated work order.',
|
||||
'begin. Pick a coating first — nodes are scoped to its '
|
||||
'recipe tree. Skips earlier steps in the generated WO but '
|
||||
'keeps later siblings and sub-processes.',
|
||||
)
|
||||
is_one_off = fields.Boolean(
|
||||
string='One-off Part',
|
||||
|
||||
@@ -235,9 +235,13 @@ class FpDirectOrderWizard(models.TransientModel):
|
||||
'order_line': [],
|
||||
}
|
||||
|
||||
# 4. One SO line per wizard line
|
||||
# 4. One SO line per wizard line. Cache resolved parts (post
|
||||
# rev-bump) so the push-to-defaults pass writes to the right
|
||||
# catalog entry.
|
||||
resolved_parts = {} # {wizard_line_id: resolved part record}
|
||||
for line in self.line_ids:
|
||||
part = line._get_or_bump_revision()
|
||||
resolved_parts[line.id] = part
|
||||
header = '%s - %s Rev %s (x%d)' % (
|
||||
line.coating_config_id.name,
|
||||
part.name,
|
||||
@@ -270,14 +274,14 @@ class FpDirectOrderWizard(models.TransientModel):
|
||||
so = self.env['sale.order'].create(so_vals)
|
||||
so.action_confirm()
|
||||
|
||||
# 6. Push-to-defaults (C4) — after the part has been resolved /
|
||||
# revision-bumped, write coating + treatments back onto the part
|
||||
# catalog entry so the next order inherits the same defaults.
|
||||
# 6. Push-to-defaults (C4) — uses the resolved part cached
|
||||
# during the build loop so rev-bumped lines write defaults to
|
||||
# the NEW revision, not the pre-bump one.
|
||||
for line in self.line_ids:
|
||||
if not line.push_to_defaults:
|
||||
if not line.push_to_defaults or line.is_one_off:
|
||||
continue
|
||||
part = line.part_catalog_id
|
||||
if not part or line.is_one_off:
|
||||
part = resolved_parts.get(line.id) or line.part_catalog_id
|
||||
if not part:
|
||||
continue
|
||||
part.write({
|
||||
'x_fc_default_coating_config_id': line.coating_config_id.id or False,
|
||||
|
||||
Reference in New Issue
Block a user