Compare commits
13 Commits
fusion_acc
...
06dafc31c1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
06dafc31c1 | ||
|
|
2ddc600d65 | ||
|
|
207c857e6b | ||
|
|
05de855cea | ||
|
|
9ae9161892 | ||
|
|
1829f0584f | ||
|
|
63f3e0ec14 | ||
|
|
397fb238c5 | ||
|
|
d4ef19858d | ||
|
|
4ce0edc698 | ||
|
|
ea2f44287f | ||
|
|
b4558a223c | ||
|
|
7a53012f09 |
140
fusion_accounting/PHASE_4_PLAN.md
Normal file
140
fusion_accounting/PHASE_4_PLAN.md
Normal file
@@ -0,0 +1,140 @@
|
|||||||
|
# Phase 4 — Fusion Accounting Follow-up Implementation Plan
|
||||||
|
|
||||||
|
**Module:** `fusion_accounting_followup`
|
||||||
|
**Branch:** `fusion_accounting/phase-4-followup`
|
||||||
|
**Pre-phase tag:** `fusion_accounting/pre-phase-4`
|
||||||
|
**Estimated tasks:** ~35
|
||||||
|
**Reference:** `/Users/gurpreet/Github/RePackaged-Odoo/accounting/account_followup/` (~1318 LOC Python)
|
||||||
|
|
||||||
|
## Goal
|
||||||
|
|
||||||
|
Replace Enterprise's `account_followup` module — multi-level dunning sequences for unpaid invoices, with AI augmentation: contextually-appropriate follow-up text generation + payment-risk scoring + tone adjustment based on customer history. Coexists with Enterprise.
|
||||||
|
|
||||||
|
## Architecture (HYBRID engine, Phases 1-3 pattern)
|
||||||
|
|
||||||
|
```
|
||||||
|
fusion.followup.engine (AbstractModel) ← shared primitives
|
||||||
|
├── compute_followup_level(partner)
|
||||||
|
├── get_overdue_for_partner(partner)
|
||||||
|
├── send_followup_email(partner, level=None)
|
||||||
|
├── escalate_to_next_level(partner)
|
||||||
|
├── pause_followup(partner, until_date)
|
||||||
|
├── reset_followup(partner)
|
||||||
|
└── snapshot_followup_history(partner) ← audit/history
|
||||||
|
|
||||||
|
services/ ← pure-Python
|
||||||
|
├── overdue_aging.py → bucket overdue lines (current/30/60/90/120+)
|
||||||
|
├── level_resolver.py → match aging buckets to follow-up levels
|
||||||
|
├── risk_scorer.py → payment-history risk score (0-100)
|
||||||
|
├── tone_selector.py → gentle/firm/legal based on level + risk
|
||||||
|
├── followup_text_generator.py → LLM-generated follow-up text
|
||||||
|
└── followup_text_prompt.py → provider-agnostic LLM prompt
|
||||||
|
|
||||||
|
models/
|
||||||
|
├── fusion_followup_level.py → level definition (delay days, template, action)
|
||||||
|
├── fusion_followup_run.py → execution record (per-partner per-level)
|
||||||
|
├── fusion_followup_text_cache.py → LLM-generated text cache (cost-saving)
|
||||||
|
├── fusion_followup_engine.py → AbstractModel orchestrator
|
||||||
|
├── res_partner.py (inherit) → fusion_followup_status, fusion_followup_paused_until
|
||||||
|
└── account_move_line.py (inherit) → followup_level_id (which level last contacted at)
|
||||||
|
|
||||||
|
controllers/followup_controller.py ← 6 JSON-RPC endpoints
|
||||||
|
├── /fusion/followup/list_overdue → list partners with overdue
|
||||||
|
├── /fusion/followup/get_partner_detail → single partner with aging + history
|
||||||
|
├── /fusion/followup/generate_text → AI-generate follow-up text
|
||||||
|
├── /fusion/followup/send → send a follow-up email
|
||||||
|
├── /fusion/followup/pause → pause follow-ups for a partner
|
||||||
|
└── /fusion/followup/reset → reset follow-up state
|
||||||
|
|
||||||
|
static/src/
|
||||||
|
├── scss/ ← follow-up design tokens
|
||||||
|
├── services/followup_service.js ← reactive state + RPC wrappers
|
||||||
|
├── views/followup_dashboard/ ← top-level OWL controller
|
||||||
|
└── components/ ← partner_card, aging_bucket_strip, ai_text_panel,
|
||||||
|
followup_history_table, risk_badge
|
||||||
|
```
|
||||||
|
|
||||||
|
## Coexistence
|
||||||
|
|
||||||
|
`group_fusion_show_when_enterprise_absent`. Follow-up menu visible only when `account_followup` NOT installed.
|
||||||
|
|
||||||
|
## Tasks (~35 total)
|
||||||
|
|
||||||
|
### Group 1: Foundation (1-2)
|
||||||
|
1. Safety net (DONE)
|
||||||
|
2. Plan doc + module skeleton
|
||||||
|
|
||||||
|
### Group 2: Pure-Python services TDD (3-7)
|
||||||
|
3. `services/overdue_aging.py` (TDD: bucket lines into 0/30/60/90/120+)
|
||||||
|
4. `services/level_resolver.py` (TDD: match aging to level)
|
||||||
|
5. `services/risk_scorer.py` (TDD: payment-history risk 0-100)
|
||||||
|
6. `services/tone_selector.py` (TDD: gentle/firm/legal)
|
||||||
|
7. `services/followup_text_generator.py` + `followup_text_prompt.py` (LLM)
|
||||||
|
|
||||||
|
### Group 3: Persisted models (8-12)
|
||||||
|
8. `models/fusion_followup_level.py` (level definition)
|
||||||
|
9. `models/fusion_followup_run.py` (execution record)
|
||||||
|
10. `models/fusion_followup_text_cache.py` (LLM cache)
|
||||||
|
11. `models/res_partner.py` (inherit: fusion_followup_status, paused_until)
|
||||||
|
12. `models/account_move_line.py` (inherit: followup_level_id)
|
||||||
|
|
||||||
|
### Group 4: Engine + integration tests (13-14)
|
||||||
|
13. `models/fusion_followup_engine.py` (7-method API)
|
||||||
|
14. Engine integration tests
|
||||||
|
|
||||||
|
### Group 5: Backend wiring (15-18)
|
||||||
|
15. JSON-RPC controller (6 endpoints)
|
||||||
|
16. FollowupAdapter wiring `_via_fusion` paths
|
||||||
|
17. 4 new AI tools (list_overdue, generate_text, send_followup, get_risk_score)
|
||||||
|
18. Cron — daily scan + escalate
|
||||||
|
|
||||||
|
### Group 6: Tests + perf (19-21)
|
||||||
|
19. Property-based tests (Hypothesis: aging buckets sum to total)
|
||||||
|
20. Integration tests (full follow-up flow: scan → escalate → send → reset)
|
||||||
|
21. Performance benchmarks (P95: scan < 500ms, generate_text < 5s incl. LLM)
|
||||||
|
|
||||||
|
### Group 7: Frontend (22-26)
|
||||||
|
22. SCSS tokens + main stylesheet
|
||||||
|
23. `followup_service.js`
|
||||||
|
24. `followup_dashboard` (top-level)
|
||||||
|
25. `partner_card` + `aging_bucket_strip` + `risk_badge`
|
||||||
|
26. `ai_text_panel` (Fusion-only) + `followup_history_table`
|
||||||
|
|
||||||
|
### Group 8: Wizards + data (27-29)
|
||||||
|
27. Default follow-up levels XML data (7-day reminder, 30-day, 60-day, legal)
|
||||||
|
28. Default mail templates XML data (3 escalation levels)
|
||||||
|
29. "Send batch follow-ups" wizard
|
||||||
|
|
||||||
|
### Group 9: Migration + coexistence (30-32)
|
||||||
|
30. Migration wizard inheritance — backfill from account_followup tables
|
||||||
|
31. Menu + window action with coexistence group filter
|
||||||
|
32. Coexistence test
|
||||||
|
|
||||||
|
### Group 10: Final tests + polish (33-37)
|
||||||
|
33. 5 OWL tour tests
|
||||||
|
34. Local LLM compat test for text_generator
|
||||||
|
35. Update meta-module manifest
|
||||||
|
36. CLAUDE.md, UPGRADE_NOTES.md, README.md
|
||||||
|
37. End-to-end smoke + tag phase-4-complete + push
|
||||||
|
|
||||||
|
## Performance Targets (P95)
|
||||||
|
|
||||||
|
- `compute_followup_level`: <50ms
|
||||||
|
- `get_overdue_for_partner`: <100ms
|
||||||
|
- `send_followup_email` (no LLM): <200ms
|
||||||
|
- `generate_text` (with LLM): <5s
|
||||||
|
- Controller `list_overdue` (50 partners): <500ms
|
||||||
|
|
||||||
|
## V19 Conventions (Phases 1-3 lessons)
|
||||||
|
|
||||||
|
- `models.Constraint` not `_sql_constraints`
|
||||||
|
- No `@api.depends('id')` on stored compute fields
|
||||||
|
- `@route(type='jsonrpc')` not `type='json'`
|
||||||
|
- `ir.cron` no `numbercall` field
|
||||||
|
- `res.groups.user_ids` not `users`
|
||||||
|
- `ir.ui.menu.group_ids` not `groups_id`
|
||||||
|
- `from odoo.exceptions import UserError, ValidationError` (NOT `self.env['ir.exceptions'].UserError`)
|
||||||
|
|
||||||
|
## Test Targets
|
||||||
|
|
||||||
|
Match Phases 1-3 test pyramid. Phase 4 target: ~80-100 additional tests → ~510-530 total project tests.
|
||||||
5
fusion_accounting_followup/__init__.py
Normal file
5
fusion_accounting_followup/__init__.py
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
from . import models
|
||||||
|
from . import services
|
||||||
|
from . import controllers
|
||||||
|
from . import wizards
|
||||||
|
from . import reports
|
||||||
45
fusion_accounting_followup/__manifest__.py
Normal file
45
fusion_accounting_followup/__manifest__.py
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
{
|
||||||
|
'name': 'Fusion Accounting Follow-up',
|
||||||
|
'version': '19.0.1.0.10',
|
||||||
|
'category': 'Accounting/Accounting',
|
||||||
|
'summary': 'AI-augmented customer follow-ups (dunning) for unpaid invoices.',
|
||||||
|
'description': """
|
||||||
|
Fusion Accounting Follow-up
|
||||||
|
===========================
|
||||||
|
|
||||||
|
A Fusion-native replacement for Odoo Enterprise's account_followup module.
|
||||||
|
|
||||||
|
CORE scope (Phase 4):
|
||||||
|
- Multi-level dunning sequences (gentle reminder, firm warning, legal)
|
||||||
|
- Per-partner follow-up state (current level, paused-until, history)
|
||||||
|
- Automated daily scan + escalation cron
|
||||||
|
- Mail templates per level
|
||||||
|
|
||||||
|
AI augmentation:
|
||||||
|
- Contextually-appropriate follow-up text generation (LLM)
|
||||||
|
- Payment-risk scoring from invoice/payment history
|
||||||
|
- Tone selection (gentle/firm/legal) based on level + risk
|
||||||
|
|
||||||
|
Coexists with Enterprise: when account_followup is installed, the Fusion
|
||||||
|
menu hides; the engine + AI tools remain available for the chat.
|
||||||
|
""",
|
||||||
|
'author': 'Fusion Accounting',
|
||||||
|
'license': 'LGPL-3',
|
||||||
|
'depends': [
|
||||||
|
'fusion_accounting_core',
|
||||||
|
'fusion_accounting_ai',
|
||||||
|
'account',
|
||||||
|
'mail',
|
||||||
|
],
|
||||||
|
'data': [
|
||||||
|
'security/ir.model.access.csv',
|
||||||
|
],
|
||||||
|
'assets': {
|
||||||
|
'web.assets_backend': [
|
||||||
|
],
|
||||||
|
},
|
||||||
|
'installable': True,
|
||||||
|
'auto_install': False,
|
||||||
|
'application': False,
|
||||||
|
'icon': '/fusion_accounting_followup/static/description/icon.png',
|
||||||
|
}
|
||||||
0
fusion_accounting_followup/controllers/__init__.py
Normal file
0
fusion_accounting_followup/controllers/__init__.py
Normal file
5
fusion_accounting_followup/models/__init__.py
Normal file
5
fusion_accounting_followup/models/__init__.py
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
from . import fusion_followup_level
|
||||||
|
from . import fusion_followup_run
|
||||||
|
from . import fusion_followup_text_cache
|
||||||
|
from . import res_partner
|
||||||
|
from . import account_move_line
|
||||||
14
fusion_accounting_followup/models/account_move_line.py
Normal file
14
fusion_accounting_followup/models/account_move_line.py
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
"""Inherit account.move.line: track last follow-up level."""
|
||||||
|
|
||||||
|
from odoo import _, api, fields, models
|
||||||
|
|
||||||
|
|
||||||
|
class AccountMoveLine(models.Model):
|
||||||
|
_inherit = "account.move.line"
|
||||||
|
|
||||||
|
fusion_followup_level_id = fields.Many2one(
|
||||||
|
'fusion.followup.level', copy=False,
|
||||||
|
help="Last follow-up level at which this line was contacted.")
|
||||||
|
fusion_followup_last_run_date = fields.Datetime(
|
||||||
|
copy=False,
|
||||||
|
help="When the line was most-recently included in a follow-up.")
|
||||||
42
fusion_accounting_followup/models/fusion_followup_level.py
Normal file
42
fusion_accounting_followup/models/fusion_followup_level.py
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
"""Follow-up level definition (e.g. Reminder at 7 days, Warning at 30, Legal at 60)."""
|
||||||
|
|
||||||
|
from odoo import _, api, fields, models
|
||||||
|
|
||||||
|
|
||||||
|
TONE_SELECTION = [
|
||||||
|
('gentle', 'Gentle'),
|
||||||
|
('firm', 'Firm'),
|
||||||
|
('legal', 'Legal'),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
class FusionFollowupLevel(models.Model):
|
||||||
|
_name = "fusion.followup.level"
|
||||||
|
_description = "Fusion Follow-up Level"
|
||||||
|
_order = "sequence, id"
|
||||||
|
|
||||||
|
name = fields.Char(required=True, translate=True)
|
||||||
|
sequence = fields.Integer(required=True, default=10,
|
||||||
|
help="Order in which levels escalate (1, 2, 3...).")
|
||||||
|
delay_days = fields.Integer(required=True,
|
||||||
|
help="Min days overdue to trigger this level.")
|
||||||
|
tone = fields.Selection(TONE_SELECTION, required=True, default='gentle')
|
||||||
|
description = fields.Text()
|
||||||
|
company_id = fields.Many2one('res.company', default=lambda self: self.env.company)
|
||||||
|
|
||||||
|
mail_template_id = fields.Many2one('mail.template',
|
||||||
|
domain=[('model', '=', 'res.partner')])
|
||||||
|
|
||||||
|
requires_manual_review = fields.Boolean(default=False,
|
||||||
|
help="If True, follow-ups at this level need human approval before send.")
|
||||||
|
|
||||||
|
active = fields.Boolean(default=True)
|
||||||
|
|
||||||
|
_check_delay_positive = models.Constraint(
|
||||||
|
'CHECK(delay_days >= 0)',
|
||||||
|
'delay_days must be non-negative.',
|
||||||
|
)
|
||||||
|
_unique_sequence_per_company = models.Constraint(
|
||||||
|
'UNIQUE(company_id, sequence)',
|
||||||
|
'Sequence must be unique per company.',
|
||||||
|
)
|
||||||
54
fusion_accounting_followup/models/fusion_followup_run.py
Normal file
54
fusion_accounting_followup/models/fusion_followup_run.py
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
"""Audit record of one follow-up execution (per partner per level)."""
|
||||||
|
|
||||||
|
from odoo import _, api, fields, models
|
||||||
|
|
||||||
|
|
||||||
|
STATE_SELECTION = [
|
||||||
|
('draft', 'Draft'),
|
||||||
|
('sent', 'Sent'),
|
||||||
|
('manual_review', 'Manual Review'),
|
||||||
|
('skipped', 'Skipped'),
|
||||||
|
('failed', 'Failed'),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
class FusionFollowupRun(models.Model):
|
||||||
|
_name = "fusion.followup.run"
|
||||||
|
_description = "Fusion Follow-up Run (Per-Partner Audit)"
|
||||||
|
_order = "execution_date desc, id desc"
|
||||||
|
|
||||||
|
partner_id = fields.Many2one('res.partner', required=True, ondelete='cascade')
|
||||||
|
company_id = fields.Many2one('res.company', required=True,
|
||||||
|
default=lambda self: self.env.company)
|
||||||
|
level_id = fields.Many2one('fusion.followup.level', ondelete='restrict')
|
||||||
|
|
||||||
|
execution_date = fields.Datetime(default=fields.Datetime.now, required=True)
|
||||||
|
state = fields.Selection(STATE_SELECTION, default='draft', required=True)
|
||||||
|
|
||||||
|
overdue_amount = fields.Float()
|
||||||
|
longest_overdue_days = fields.Integer()
|
||||||
|
|
||||||
|
risk_score = fields.Integer()
|
||||||
|
risk_band = fields.Selection([
|
||||||
|
('low', 'Low'), ('medium', 'Medium'),
|
||||||
|
('high', 'High'), ('critical', 'Critical'),
|
||||||
|
])
|
||||||
|
|
||||||
|
subject = fields.Char()
|
||||||
|
body = fields.Text()
|
||||||
|
tone_used = fields.Selection([
|
||||||
|
('gentle', 'Gentle'), ('firm', 'Firm'), ('legal', 'Legal'),
|
||||||
|
])
|
||||||
|
sent_to_email = fields.Char()
|
||||||
|
|
||||||
|
text_was_ai_generated = fields.Boolean(default=False)
|
||||||
|
ai_provider = fields.Char(help="LLM provider name (openai, claude, etc.) if AI was used.")
|
||||||
|
|
||||||
|
notes = fields.Text()
|
||||||
|
error_message = fields.Text()
|
||||||
|
|
||||||
|
def action_mark_sent(self):
|
||||||
|
self.write({'state': 'sent'})
|
||||||
|
|
||||||
|
def action_mark_failed(self, error: str = ''):
|
||||||
|
self.write({'state': 'failed', 'error_message': error})
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
"""Cache of AI-generated follow-up text to avoid LLM cost on repeats."""
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
|
||||||
|
from odoo import _, api, fields, models
|
||||||
|
|
||||||
|
|
||||||
|
class FusionFollowupTextCache(models.Model):
|
||||||
|
_name = "fusion.followup.text.cache"
|
||||||
|
_description = "Cache of AI-generated follow-up text"
|
||||||
|
_order = "generated_at desc"
|
||||||
|
|
||||||
|
partner_id = fields.Many2one('res.partner', required=True, ondelete='cascade')
|
||||||
|
level_id = fields.Many2one('fusion.followup.level', ondelete='cascade')
|
||||||
|
company_id = fields.Many2one('res.company', required=True,
|
||||||
|
default=lambda self: self.env.company)
|
||||||
|
|
||||||
|
fingerprint = fields.Char(required=True, index=True,
|
||||||
|
help="SHA-256 of input parameters")
|
||||||
|
|
||||||
|
subject = fields.Char()
|
||||||
|
body = fields.Text()
|
||||||
|
tone_used = fields.Selection([
|
||||||
|
('gentle', 'Gentle'), ('firm', 'Firm'), ('legal', 'Legal'),
|
||||||
|
])
|
||||||
|
key_points = fields.Json()
|
||||||
|
|
||||||
|
generated_at = fields.Datetime(default=fields.Datetime.now, required=True)
|
||||||
|
expires_at = fields.Datetime()
|
||||||
|
use_count = fields.Integer(default=0)
|
||||||
|
provider = fields.Char()
|
||||||
|
|
||||||
|
@api.model
|
||||||
|
def compute_fingerprint(self, *, partner_id: int, level_id: int,
|
||||||
|
overdue_amount: float, longest_overdue_days: int,
|
||||||
|
invoice_count: int, tone: str) -> str:
|
||||||
|
"""Stable hash of the inputs that determine the generated text."""
|
||||||
|
s = f"{partner_id}|{level_id}|{round(overdue_amount, 2)}|" \
|
||||||
|
f"{longest_overdue_days}|{invoice_count}|{tone}"
|
||||||
|
return hashlib.sha256(s.encode('utf-8')).hexdigest()
|
||||||
|
|
||||||
|
@api.model
|
||||||
|
def lookup(self, *, partner_id: int, level_id: int,
|
||||||
|
overdue_amount: float, longest_overdue_days: int,
|
||||||
|
invoice_count: int, tone: str):
|
||||||
|
"""Find a cached entry matching these inputs, or empty recordset."""
|
||||||
|
fp = self.compute_fingerprint(
|
||||||
|
partner_id=partner_id, level_id=level_id,
|
||||||
|
overdue_amount=overdue_amount,
|
||||||
|
longest_overdue_days=longest_overdue_days,
|
||||||
|
invoice_count=invoice_count, tone=tone,
|
||||||
|
)
|
||||||
|
return self.search([
|
||||||
|
('partner_id', '=', partner_id),
|
||||||
|
('fingerprint', '=', fp),
|
||||||
|
], limit=1)
|
||||||
|
|
||||||
|
def action_increment_use(self):
|
||||||
|
for rec in self:
|
||||||
|
rec.use_count += 1
|
||||||
52
fusion_accounting_followup/models/res_partner.py
Normal file
52
fusion_accounting_followup/models/res_partner.py
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
"""Inherit res.partner: add follow-up state fields."""
|
||||||
|
|
||||||
|
from odoo import _, api, fields, models
|
||||||
|
|
||||||
|
|
||||||
|
FOLLOWUP_STATUS = [
|
||||||
|
('no_action', 'No Action Needed'),
|
||||||
|
('action_due', 'Action Due'),
|
||||||
|
('paused', 'Paused'),
|
||||||
|
('blocked', 'Blocked'),
|
||||||
|
('with_credit_team', 'With Credit Team'),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
class ResPartner(models.Model):
|
||||||
|
_inherit = "res.partner"
|
||||||
|
|
||||||
|
fusion_followup_status = fields.Selection(
|
||||||
|
FOLLOWUP_STATUS, default='no_action', tracking=True,
|
||||||
|
help="Current follow-up status as computed by the engine.")
|
||||||
|
fusion_followup_paused_until = fields.Date(
|
||||||
|
tracking=True,
|
||||||
|
help="Pause follow-ups for this partner until this date.")
|
||||||
|
fusion_followup_last_level_id = fields.Many2one(
|
||||||
|
'fusion.followup.level',
|
||||||
|
help="The most-recent follow-up level this partner has been contacted at.")
|
||||||
|
fusion_followup_last_run_date = fields.Datetime(readonly=True)
|
||||||
|
fusion_followup_run_ids = fields.One2many(
|
||||||
|
'fusion.followup.run', 'partner_id', string='Follow-up History')
|
||||||
|
fusion_followup_run_count = fields.Integer(
|
||||||
|
compute='_compute_fusion_followup_run_count')
|
||||||
|
fusion_followup_risk_score = fields.Integer(
|
||||||
|
readonly=True, default=0,
|
||||||
|
help="Latest computed payment risk (0-100). Updated by cron.")
|
||||||
|
fusion_followup_risk_band = fields.Selection([
|
||||||
|
('low', 'Low'), ('medium', 'Medium'),
|
||||||
|
('high', 'High'), ('critical', 'Critical'),
|
||||||
|
], default='low', readonly=True)
|
||||||
|
|
||||||
|
def _compute_fusion_followup_run_count(self):
|
||||||
|
for partner in self:
|
||||||
|
partner.fusion_followup_run_count = len(partner.fusion_followup_run_ids)
|
||||||
|
|
||||||
|
def action_view_followup_history(self):
|
||||||
|
self.ensure_one()
|
||||||
|
return {
|
||||||
|
'type': 'ir.actions.act_window',
|
||||||
|
'res_model': 'fusion.followup.run',
|
||||||
|
'view_mode': 'list,form',
|
||||||
|
'domain': [('partner_id', '=', self.id)],
|
||||||
|
'context': {'default_partner_id': self.id},
|
||||||
|
}
|
||||||
0
fusion_accounting_followup/reports/__init__.py
Normal file
0
fusion_accounting_followup/reports/__init__.py
Normal file
7
fusion_accounting_followup/security/ir.model.access.csv
Normal file
7
fusion_accounting_followup/security/ir.model.access.csv
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink
|
||||||
|
access_fusion_followup_level_user,fusion.followup.level.user,model_fusion_followup_level,base.group_user,1,0,0,0
|
||||||
|
access_fusion_followup_level_admin,fusion.followup.level.admin,model_fusion_followup_level,fusion_accounting_core.group_fusion_accounting_admin,1,1,1,1
|
||||||
|
access_fusion_followup_run_user,fusion.followup.run.user,model_fusion_followup_run,base.group_user,1,0,0,0
|
||||||
|
access_fusion_followup_run_admin,fusion.followup.run.admin,model_fusion_followup_run,fusion_accounting_core.group_fusion_accounting_admin,1,1,1,1
|
||||||
|
access_fusion_followup_text_cache_user,fusion.followup.text.cache.user,model_fusion_followup_text_cache,base.group_user,1,0,0,0
|
||||||
|
access_fusion_followup_text_cache_admin,fusion.followup.text.cache.admin,model_fusion_followup_text_cache,fusion_accounting_core.group_fusion_accounting_admin,1,1,1,1
|
||||||
|
6
fusion_accounting_followup/services/__init__.py
Normal file
6
fusion_accounting_followup/services/__init__.py
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
from . import overdue_aging
|
||||||
|
from . import level_resolver
|
||||||
|
from . import risk_scorer
|
||||||
|
from . import tone_selector
|
||||||
|
from . import followup_text_prompt
|
||||||
|
from . import followup_text_generator
|
||||||
123
fusion_accounting_followup/services/followup_text_generator.py
Normal file
123
fusion_accounting_followup/services/followup_text_generator.py
Normal file
@@ -0,0 +1,123 @@
|
|||||||
|
"""AI-generated follow-up text with templated fallback."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
|
||||||
|
_logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
TEMPLATES = {
|
||||||
|
'gentle': {
|
||||||
|
'subject': 'Friendly reminder: invoice payment',
|
||||||
|
'body': 'Dear {partner_name},\n\nThis is a friendly reminder that you have '
|
||||||
|
'{currency_code} {total_overdue:,.2f} outstanding on invoices that '
|
||||||
|
'are now {longest_overdue_days} days past due. We understand things '
|
||||||
|
'happen — please let us know if there is anything we can do to help '
|
||||||
|
'resolve this.\n\nBest regards.',
|
||||||
|
},
|
||||||
|
'firm': {
|
||||||
|
'subject': 'Outstanding invoices — action required',
|
||||||
|
'body': 'Dear {partner_name},\n\nOur records show {currency_code} '
|
||||||
|
'{total_overdue:,.2f} outstanding on {invoice_count} invoice(s), '
|
||||||
|
'with the longest now {longest_overdue_days} days overdue. We '
|
||||||
|
'request immediate payment to avoid further action.\n\nRegards.',
|
||||||
|
},
|
||||||
|
'legal': {
|
||||||
|
'subject': 'FINAL NOTICE — outstanding balance',
|
||||||
|
'body': 'Dear {partner_name},\n\nDespite previous reminders, '
|
||||||
|
'{currency_code} {total_overdue:,.2f} remains outstanding on your '
|
||||||
|
'account, with the longest invoice {longest_overdue_days} days '
|
||||||
|
'overdue. If full payment is not received within 7 days, we will '
|
||||||
|
'be forced to refer this matter for legal collection.\n\n'
|
||||||
|
'Regards.',
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def generate_followup_text(env, *, partner_name: str, total_overdue: float,
|
||||||
|
currency_code: str, longest_overdue_days: int,
|
||||||
|
tone: str, invoice_count: int = 0,
|
||||||
|
last_payment_date: str = None,
|
||||||
|
risk_drivers: list[str] = None,
|
||||||
|
provider=None) -> dict:
|
||||||
|
"""Generate follow-up text via LLM, with templated fallback.
|
||||||
|
|
||||||
|
Returns: {subject, body, tone_used, key_points}"""
|
||||||
|
if provider is None:
|
||||||
|
provider = _get_provider(env)
|
||||||
|
if provider is None:
|
||||||
|
return _templated_fallback(
|
||||||
|
partner_name=partner_name, total_overdue=total_overdue,
|
||||||
|
currency_code=currency_code,
|
||||||
|
longest_overdue_days=longest_overdue_days,
|
||||||
|
tone=tone, invoice_count=invoice_count,
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
from .followup_text_prompt import build_prompt
|
||||||
|
system, user = build_prompt(
|
||||||
|
partner_name=partner_name, total_overdue=total_overdue,
|
||||||
|
currency_code=currency_code,
|
||||||
|
longest_overdue_days=longest_overdue_days, tone=tone,
|
||||||
|
invoice_count=invoice_count, last_payment_date=last_payment_date,
|
||||||
|
risk_drivers=risk_drivers,
|
||||||
|
)
|
||||||
|
response = provider.complete(
|
||||||
|
system=system,
|
||||||
|
messages=[{'role': 'user', 'content': user}],
|
||||||
|
max_tokens=800, temperature=0.3,
|
||||||
|
)
|
||||||
|
content = response.get('content') if isinstance(response, dict) else response
|
||||||
|
parsed = json.loads(content)
|
||||||
|
for key in ('subject', 'body', 'tone_used'):
|
||||||
|
if key not in parsed:
|
||||||
|
raise ValueError(f"Missing key: {key}")
|
||||||
|
parsed.setdefault('key_points', [])
|
||||||
|
return parsed
|
||||||
|
except Exception as e:
|
||||||
|
_logger.warning("Follow-up text LLM generation failed (%s); falling back", e)
|
||||||
|
return _templated_fallback(
|
||||||
|
partner_name=partner_name, total_overdue=total_overdue,
|
||||||
|
currency_code=currency_code,
|
||||||
|
longest_overdue_days=longest_overdue_days,
|
||||||
|
tone=tone, invoice_count=invoice_count,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _templated_fallback(*, partner_name, total_overdue, currency_code,
|
||||||
|
longest_overdue_days, tone, invoice_count) -> dict:
|
||||||
|
template = TEMPLATES.get(tone, TEMPLATES['gentle'])
|
||||||
|
return {
|
||||||
|
'subject': template['subject'],
|
||||||
|
'body': template['body'].format(
|
||||||
|
partner_name=partner_name, total_overdue=total_overdue,
|
||||||
|
currency_code=currency_code,
|
||||||
|
longest_overdue_days=longest_overdue_days,
|
||||||
|
invoice_count=invoice_count or 0,
|
||||||
|
),
|
||||||
|
'tone_used': tone,
|
||||||
|
'key_points': [
|
||||||
|
f"${total_overdue:,.2f} outstanding",
|
||||||
|
f"{longest_overdue_days} days overdue",
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _get_provider(env):
|
||||||
|
"""Look up provider for 'followup_text' feature."""
|
||||||
|
param = env['ir.config_parameter'].sudo()
|
||||||
|
name = param.get_param('fusion_accounting.provider.followup_text')
|
||||||
|
if not name:
|
||||||
|
name = param.get_param('fusion_accounting.provider.default')
|
||||||
|
if not name:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
from odoo.addons.fusion_accounting_ai.services.adapters.openai_adapter import OpenAIAdapter
|
||||||
|
from odoo.addons.fusion_accounting_ai.services.adapters.claude import ClaudeAdapter
|
||||||
|
except ImportError:
|
||||||
|
return None
|
||||||
|
if name.startswith('openai'):
|
||||||
|
return OpenAIAdapter(env)
|
||||||
|
elif name.startswith('claude'):
|
||||||
|
return ClaudeAdapter(env)
|
||||||
|
return None
|
||||||
56
fusion_accounting_followup/services/followup_text_prompt.py
Normal file
56
fusion_accounting_followup/services/followup_text_prompt.py
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
"""LLM prompt for AI-generated follow-up text.
|
||||||
|
|
||||||
|
Output contract: {
|
||||||
|
"subject": str,
|
||||||
|
"body": str,
|
||||||
|
"tone_used": str,
|
||||||
|
"key_points": [str, ...]
|
||||||
|
}"""
|
||||||
|
|
||||||
|
|
||||||
|
SYSTEM_PROMPT = """You are an experienced credit collections specialist writing a
|
||||||
|
follow-up email for an unpaid invoice. Output MUST be valid JSON of this
|
||||||
|
exact shape:
|
||||||
|
|
||||||
|
{
|
||||||
|
"subject": "<email subject line>",
|
||||||
|
"body": "<plain-text or simple HTML body, no <html> wrapper>",
|
||||||
|
"tone_used": "gentle" | "firm" | "legal",
|
||||||
|
"key_points": ["<point 1>", "<point 2>", ...]
|
||||||
|
}
|
||||||
|
|
||||||
|
Tone guide:
|
||||||
|
- gentle: friendly reminder, assume oversight, propose easy paths to pay
|
||||||
|
- firm: state amount + days overdue clearly, request immediate action,
|
||||||
|
hint at consequences
|
||||||
|
- legal: formal language, reference contract obligations, mention possible
|
||||||
|
legal action / collections agency, demand payment by specific date
|
||||||
|
|
||||||
|
Always:
|
||||||
|
- Use the actual amounts and partner name from the data provided
|
||||||
|
- Don't invent contract terms or interest rates
|
||||||
|
- Don't include markdown code fences
|
||||||
|
- No prose outside the JSON
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def build_prompt(*, partner_name: str, total_overdue: float, currency_code: str,
|
||||||
|
longest_overdue_days: int, tone: str,
|
||||||
|
invoice_count: int = 0, last_payment_date: str = None,
|
||||||
|
risk_drivers: list[str] = None) -> tuple[str, str]:
|
||||||
|
parts = [
|
||||||
|
f"PARTNER: {partner_name}",
|
||||||
|
f"TOTAL OVERDUE: {currency_code} {total_overdue:,.2f}",
|
||||||
|
f"LONGEST OVERDUE: {longest_overdue_days} days",
|
||||||
|
f"OPEN INVOICE COUNT: {invoice_count}",
|
||||||
|
f"REQUESTED TONE: {tone}",
|
||||||
|
]
|
||||||
|
if last_payment_date:
|
||||||
|
parts.append(f"LAST PAYMENT: {last_payment_date}")
|
||||||
|
if risk_drivers:
|
||||||
|
parts.append("RISK FACTORS:")
|
||||||
|
for d in risk_drivers[:5]:
|
||||||
|
parts.append(f" - {d}")
|
||||||
|
parts.append("")
|
||||||
|
parts.append("Write the follow-up email per the system prompt.")
|
||||||
|
return (SYSTEM_PROMPT, "\n".join(parts))
|
||||||
52
fusion_accounting_followup/services/level_resolver.py
Normal file
52
fusion_accounting_followup/services/level_resolver.py
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
"""Level resolver: which follow-up level should fire for this partner?
|
||||||
|
|
||||||
|
Pure-Python: caller passes the aging report + the configured levels list,
|
||||||
|
and we pick the highest-numbered level whose threshold is met."""
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class FollowupLevelSpec:
|
||||||
|
sequence: int
|
||||||
|
name: str
|
||||||
|
delay_days: int
|
||||||
|
tone: str
|
||||||
|
|
||||||
|
def __post_init__(self):
|
||||||
|
if self.tone not in ('gentle', 'firm', 'legal'):
|
||||||
|
raise ValueError(f"Invalid tone: {self.tone}")
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_level(*, aging_report, levels: list[FollowupLevelSpec]) -> FollowupLevelSpec | None:
|
||||||
|
"""Pick the highest-sequence level whose delay_days has been crossed by
|
||||||
|
the most-overdue line in the aging report. Returns None if no overdue
|
||||||
|
lines or no levels configured."""
|
||||||
|
if not levels or not aging_report:
|
||||||
|
return None
|
||||||
|
max_days_overdue = _max_days_overdue(aging_report)
|
||||||
|
if max_days_overdue <= 0:
|
||||||
|
return None
|
||||||
|
levels_sorted = sorted(levels, key=lambda l: l.sequence, reverse=True)
|
||||||
|
for level in levels_sorted:
|
||||||
|
if level.delay_days <= max_days_overdue:
|
||||||
|
return level
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _max_days_overdue(aging_report) -> int:
|
||||||
|
"""Return the actual max days-overdue tracked on the report, falling
|
||||||
|
back to the highest populated bucket's lower bound when an older
|
||||||
|
aging report (without `max_days_overdue`) is passed in."""
|
||||||
|
tracked = getattr(aging_report, 'max_days_overdue', 0) or 0
|
||||||
|
if tracked:
|
||||||
|
return tracked
|
||||||
|
max_days = 0
|
||||||
|
for b in aging_report.buckets:
|
||||||
|
if b.name == 'current' or b.amount <= 0:
|
||||||
|
continue
|
||||||
|
if b.days_max is None:
|
||||||
|
max_days = max(max_days, b.days_min)
|
||||||
|
else:
|
||||||
|
max_days = max(max_days, b.days_min)
|
||||||
|
return max_days
|
||||||
92
fusion_accounting_followup/services/overdue_aging.py
Normal file
92
fusion_accounting_followup/services/overdue_aging.py
Normal file
@@ -0,0 +1,92 @@
|
|||||||
|
"""Aging bucket primitives.
|
||||||
|
|
||||||
|
Pure-Python: callers pass a list of move-line dicts with `date_maturity`
|
||||||
|
and `amount_residual`; we bucket them into 0/30/60/90/120+ days overdue."""
|
||||||
|
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
|
|
||||||
|
BUCKETS = [
|
||||||
|
('current', 0, 0),
|
||||||
|
('1_30', 1, 30),
|
||||||
|
('31_60', 31, 60),
|
||||||
|
('61_90', 61, 90),
|
||||||
|
('91_120', 91, 120),
|
||||||
|
('120_plus', 121, None),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class AgingBucket:
|
||||||
|
name: str
|
||||||
|
days_min: int
|
||||||
|
days_max: int | None
|
||||||
|
amount: float = 0.0
|
||||||
|
line_count: int = 0
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class AgingReport:
|
||||||
|
as_of: date
|
||||||
|
buckets: list[AgingBucket] = field(default_factory=list)
|
||||||
|
total_amount: float = 0.0
|
||||||
|
total_overdue_amount: float = 0.0
|
||||||
|
line_count: int = 0
|
||||||
|
max_days_overdue: int = 0
|
||||||
|
|
||||||
|
def to_dict(self):
|
||||||
|
return {
|
||||||
|
'as_of': str(self.as_of),
|
||||||
|
'total_amount': self.total_amount,
|
||||||
|
'total_overdue_amount': self.total_overdue_amount,
|
||||||
|
'line_count': self.line_count,
|
||||||
|
'max_days_overdue': self.max_days_overdue,
|
||||||
|
'buckets': [{
|
||||||
|
'name': b.name, 'days_min': b.days_min, 'days_max': b.days_max,
|
||||||
|
'amount': b.amount, 'line_count': b.line_count,
|
||||||
|
} for b in self.buckets],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def compute_aging(*, move_lines: list[dict], as_of: date | None = None) -> AgingReport:
|
||||||
|
"""Bucket move-line dicts into aging brackets.
|
||||||
|
|
||||||
|
Each dict needs: date_maturity (date), amount_residual (float).
|
||||||
|
`as_of` defaults to today."""
|
||||||
|
as_of = as_of or date.today()
|
||||||
|
report = AgingReport(as_of=as_of)
|
||||||
|
for name, days_min, days_max in BUCKETS:
|
||||||
|
report.buckets.append(AgingBucket(name=name, days_min=days_min, days_max=days_max))
|
||||||
|
|
||||||
|
for ml in move_lines:
|
||||||
|
maturity = ml.get('date_maturity')
|
||||||
|
amount = ml.get('amount_residual', 0.0)
|
||||||
|
if not maturity:
|
||||||
|
continue
|
||||||
|
days_overdue = (as_of - maturity).days
|
||||||
|
bucket = _find_bucket(report.buckets, days_overdue)
|
||||||
|
if bucket:
|
||||||
|
bucket.amount += amount
|
||||||
|
bucket.line_count += 1
|
||||||
|
report.total_amount += amount
|
||||||
|
if days_overdue > 0:
|
||||||
|
report.total_overdue_amount += amount
|
||||||
|
if days_overdue > report.max_days_overdue:
|
||||||
|
report.max_days_overdue = days_overdue
|
||||||
|
report.line_count += 1
|
||||||
|
|
||||||
|
return report
|
||||||
|
|
||||||
|
|
||||||
|
def _find_bucket(buckets: list[AgingBucket], days_overdue: int) -> AgingBucket | None:
|
||||||
|
if days_overdue <= 0:
|
||||||
|
return next((b for b in buckets if b.name == 'current'), None)
|
||||||
|
for b in buckets:
|
||||||
|
if b.name == 'current':
|
||||||
|
continue
|
||||||
|
if b.days_max is None and days_overdue >= b.days_min:
|
||||||
|
return b
|
||||||
|
if b.days_max is not None and b.days_min <= days_overdue <= b.days_max:
|
||||||
|
return b
|
||||||
|
return None
|
||||||
62
fusion_accounting_followup/services/risk_scorer.py
Normal file
62
fusion_accounting_followup/services/risk_scorer.py
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
"""Payment-history risk scorer.
|
||||||
|
|
||||||
|
Pure-Python: takes payment history (list of payment events) + average days-late
|
||||||
|
and returns a risk score 0-100. Higher = more risky."""
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class PartnerRiskScore:
|
||||||
|
score: int
|
||||||
|
band: str
|
||||||
|
drivers: list[str]
|
||||||
|
|
||||||
|
|
||||||
|
def score_partner(*, total_invoices: int = 0, paid_late_count: int = 0,
|
||||||
|
avg_days_late: float = 0.0,
|
||||||
|
longest_overdue_days: int = 0,
|
||||||
|
open_overdue_amount: float = 0.0,
|
||||||
|
average_invoice_amount: float = 1000.0) -> PartnerRiskScore:
|
||||||
|
"""Compute a 0-100 risk score from payment-history primitives.
|
||||||
|
|
||||||
|
Heuristic weights:
|
||||||
|
- 30% : late-payment ratio (paid_late_count / total_invoices)
|
||||||
|
- 25% : avg days late (capped at 60 days)
|
||||||
|
- 25% : longest current overdue (capped at 120 days)
|
||||||
|
- 20% : open overdue amount as multiple of average invoice
|
||||||
|
"""
|
||||||
|
drivers: list[str] = []
|
||||||
|
score = 0.0
|
||||||
|
|
||||||
|
if total_invoices > 0:
|
||||||
|
late_ratio = paid_late_count / total_invoices
|
||||||
|
score += min(late_ratio * 100, 100) * 0.30
|
||||||
|
if late_ratio > 0.5:
|
||||||
|
drivers.append(f"{paid_late_count}/{total_invoices} invoices paid late")
|
||||||
|
|
||||||
|
score += min(avg_days_late / 60, 1) * 100 * 0.25
|
||||||
|
if avg_days_late > 14:
|
||||||
|
drivers.append(f"Avg {avg_days_late:.1f} days late on payment")
|
||||||
|
|
||||||
|
score += min(longest_overdue_days / 120, 1) * 100 * 0.25
|
||||||
|
if longest_overdue_days > 30:
|
||||||
|
drivers.append(f"Longest currently overdue: {longest_overdue_days} days")
|
||||||
|
|
||||||
|
if average_invoice_amount > 0:
|
||||||
|
ratio = open_overdue_amount / average_invoice_amount
|
||||||
|
score += min(ratio / 5, 1) * 100 * 0.20
|
||||||
|
if ratio > 1.5:
|
||||||
|
drivers.append(f"Open overdue ${open_overdue_amount:,.2f} ({ratio:.1f}x avg invoice)")
|
||||||
|
|
||||||
|
final = int(round(score))
|
||||||
|
if final >= 80:
|
||||||
|
band = 'critical'
|
||||||
|
elif final >= 60:
|
||||||
|
band = 'high'
|
||||||
|
elif final >= 30:
|
||||||
|
band = 'medium'
|
||||||
|
else:
|
||||||
|
band = 'low'
|
||||||
|
|
||||||
|
return PartnerRiskScore(score=final, band=band, drivers=drivers)
|
||||||
18
fusion_accounting_followup/services/tone_selector.py
Normal file
18
fusion_accounting_followup/services/tone_selector.py
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
"""Tone selector: pick gentle/firm/legal based on follow-up level + risk score."""
|
||||||
|
|
||||||
|
TONE_BY_LEVEL = {
|
||||||
|
1: 'gentle',
|
||||||
|
2: 'firm',
|
||||||
|
3: 'legal',
|
||||||
|
4: 'legal',
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def select_tone(*, level_sequence: int, risk_score: int = 0) -> str:
|
||||||
|
"""Default tone follows level sequence; high risk can escalate."""
|
||||||
|
base_tone = TONE_BY_LEVEL.get(level_sequence, 'gentle')
|
||||||
|
if risk_score >= 80 and base_tone == 'gentle':
|
||||||
|
return 'firm'
|
||||||
|
if risk_score >= 90 and base_tone == 'firm':
|
||||||
|
return 'legal'
|
||||||
|
return base_tone
|
||||||
BIN
fusion_accounting_followup/static/description/icon.png
Normal file
BIN
fusion_accounting_followup/static/description/icon.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 72 KiB |
10
fusion_accounting_followup/tests/__init__.py
Normal file
10
fusion_accounting_followup/tests/__init__.py
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
from . import test_overdue_aging
|
||||||
|
from . import test_level_resolver
|
||||||
|
from . import test_risk_scorer
|
||||||
|
from . import test_tone_selector
|
||||||
|
from . import test_followup_text_generator
|
||||||
|
from . import test_fusion_followup_level
|
||||||
|
from . import test_fusion_followup_run
|
||||||
|
from . import test_fusion_followup_text_cache
|
||||||
|
from . import test_res_partner_inherit
|
||||||
|
from . import test_account_move_line_inherit
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
from odoo import fields as odoo_fields
|
||||||
|
from odoo.tests.common import TransactionCase
|
||||||
|
from odoo.tests import tagged
|
||||||
|
|
||||||
|
|
||||||
|
@tagged('post_install', '-at_install')
|
||||||
|
class TestAccountMoveLineFollowup(TransactionCase):
|
||||||
|
"""Verify follow-up tracking fields are added to account.move.line."""
|
||||||
|
|
||||||
|
def test_fields_exist_on_model(self):
|
||||||
|
"""Both new fields are declared on account.move.line."""
|
||||||
|
AML = self.env['account.move.line']
|
||||||
|
self.assertIn('fusion_followup_level_id', AML._fields)
|
||||||
|
self.assertIn('fusion_followup_last_run_date', AML._fields)
|
||||||
|
self.assertEqual(
|
||||||
|
AML._fields['fusion_followup_level_id'].comodel_name,
|
||||||
|
'fusion.followup.level',
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_assign_level_and_date_on_existing_line(self):
|
||||||
|
"""We can write the new fields onto an existing move line."""
|
||||||
|
line = self.env['account.move.line'].search([], limit=1)
|
||||||
|
if not line:
|
||||||
|
self.skipTest("No account.move.line records present in DB to test against.")
|
||||||
|
level = self.env['fusion.followup.level'].create({
|
||||||
|
'name': 'Reminder', 'sequence': 601, 'delay_days': 7, 'tone': 'gentle',
|
||||||
|
})
|
||||||
|
when = odoo_fields.Datetime.now()
|
||||||
|
line.write({
|
||||||
|
'fusion_followup_level_id': level.id,
|
||||||
|
'fusion_followup_last_run_date': when,
|
||||||
|
})
|
||||||
|
self.assertEqual(line.fusion_followup_level_id, level)
|
||||||
|
self.assertEqual(line.fusion_followup_last_run_date, when)
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
from odoo.tests.common import TransactionCase
|
||||||
|
from odoo.tests import tagged
|
||||||
|
from odoo.addons.fusion_accounting_followup.services.followup_text_generator import (
|
||||||
|
generate_followup_text,
|
||||||
|
)
|
||||||
|
from odoo.addons.fusion_accounting_followup.services.followup_text_prompt import (
|
||||||
|
SYSTEM_PROMPT, build_prompt,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@tagged('post_install', '-at_install')
|
||||||
|
class TestFollowupTextGenerator(TransactionCase):
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
super().setUp()
|
||||||
|
self.env['ir.config_parameter'].sudo().search([
|
||||||
|
('key', 'in', ['fusion_accounting.provider.followup_text',
|
||||||
|
'fusion_accounting.provider.default'])
|
||||||
|
]).unlink()
|
||||||
|
|
||||||
|
def test_fallback_gentle(self):
|
||||||
|
result = generate_followup_text(
|
||||||
|
self.env, partner_name='Acme Corp', total_overdue=1500,
|
||||||
|
currency_code='USD', longest_overdue_days=15, tone='gentle',
|
||||||
|
invoice_count=2,
|
||||||
|
)
|
||||||
|
self.assertEqual(result['tone_used'], 'gentle')
|
||||||
|
self.assertIn('Acme Corp', result['body'])
|
||||||
|
self.assertIn('1,500.00', result['body'])
|
||||||
|
|
||||||
|
def test_fallback_firm(self):
|
||||||
|
result = generate_followup_text(
|
||||||
|
self.env, partner_name='Acme', total_overdue=5000,
|
||||||
|
currency_code='USD', longest_overdue_days=45, tone='firm',
|
||||||
|
invoice_count=3,
|
||||||
|
)
|
||||||
|
self.assertEqual(result['tone_used'], 'firm')
|
||||||
|
|
||||||
|
def test_fallback_legal(self):
|
||||||
|
result = generate_followup_text(
|
||||||
|
self.env, partner_name='Acme', total_overdue=10000,
|
||||||
|
currency_code='USD', longest_overdue_days=90, tone='legal',
|
||||||
|
invoice_count=5,
|
||||||
|
)
|
||||||
|
self.assertEqual(result['tone_used'], 'legal')
|
||||||
|
self.assertIn('FINAL NOTICE', result['subject'])
|
||||||
|
|
||||||
|
def test_returns_required_keys(self):
|
||||||
|
result = generate_followup_text(
|
||||||
|
self.env, partner_name='X', total_overdue=100,
|
||||||
|
currency_code='USD', longest_overdue_days=10, tone='gentle',
|
||||||
|
)
|
||||||
|
for key in ('subject', 'body', 'tone_used', 'key_points'):
|
||||||
|
self.assertIn(key, result)
|
||||||
|
|
||||||
|
|
||||||
|
@tagged('post_install', '-at_install')
|
||||||
|
class TestFollowupTextPrompt(TransactionCase):
|
||||||
|
|
||||||
|
def test_system_prompt_requires_json(self):
|
||||||
|
self.assertIn('JSON', SYSTEM_PROMPT)
|
||||||
|
self.assertIn('"subject"', SYSTEM_PROMPT)
|
||||||
|
self.assertIn('"body"', SYSTEM_PROMPT)
|
||||||
|
|
||||||
|
def test_build_prompt_returns_tuple(self):
|
||||||
|
result = build_prompt(
|
||||||
|
partner_name='X', total_overdue=100, currency_code='USD',
|
||||||
|
longest_overdue_days=10, tone='gentle',
|
||||||
|
)
|
||||||
|
self.assertEqual(len(result), 2)
|
||||||
|
self.assertIn('100.00', result[1])
|
||||||
|
|
||||||
|
def test_build_prompt_includes_risk_drivers(self):
|
||||||
|
_, user = build_prompt(
|
||||||
|
partner_name='X', total_overdue=100, currency_code='USD',
|
||||||
|
longest_overdue_days=10, tone='firm',
|
||||||
|
risk_drivers=['Chronic late payer', '5/10 paid late'],
|
||||||
|
)
|
||||||
|
self.assertIn('RISK FACTORS', user)
|
||||||
|
self.assertIn('Chronic late payer', user)
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
from odoo.tests.common import TransactionCase
|
||||||
|
from odoo.tests import tagged
|
||||||
|
|
||||||
|
|
||||||
|
@tagged('post_install', '-at_install')
|
||||||
|
class TestFusionFollowupLevel(TransactionCase):
|
||||||
|
|
||||||
|
def test_create_minimal(self):
|
||||||
|
level = self.env['fusion.followup.level'].create({
|
||||||
|
'name': 'Reminder', 'sequence': 1, 'delay_days': 7, 'tone': 'gentle',
|
||||||
|
})
|
||||||
|
self.assertEqual(level.name, 'Reminder')
|
||||||
|
self.assertTrue(level.active)
|
||||||
|
|
||||||
|
def test_negative_delay_rejected(self):
|
||||||
|
with self.assertRaises(Exception):
|
||||||
|
self.env['fusion.followup.level'].create({
|
||||||
|
'name': 'Bad', 'sequence': 1, 'delay_days': -5, 'tone': 'gentle',
|
||||||
|
})
|
||||||
|
|
||||||
|
def test_duplicate_sequence_rejected(self):
|
||||||
|
self.env['fusion.followup.level'].create({
|
||||||
|
'name': 'A', 'sequence': 100, 'delay_days': 7, 'tone': 'gentle',
|
||||||
|
})
|
||||||
|
with self.assertRaises(Exception):
|
||||||
|
self.env['fusion.followup.level'].create({
|
||||||
|
'name': 'B', 'sequence': 100, 'delay_days': 30, 'tone': 'firm',
|
||||||
|
})
|
||||||
|
|
||||||
|
def test_three_levels_escalate(self):
|
||||||
|
for seq, name, days, tone in [(1, 'R', 7, 'gentle'),
|
||||||
|
(2, 'W', 30, 'firm'),
|
||||||
|
(3, 'L', 60, 'legal')]:
|
||||||
|
self.env['fusion.followup.level'].create({
|
||||||
|
'name': name, 'sequence': seq + 200,
|
||||||
|
'delay_days': days, 'tone': tone,
|
||||||
|
})
|
||||||
|
levels = self.env['fusion.followup.level'].search([
|
||||||
|
('sequence', '>', 200),
|
||||||
|
], order='sequence')
|
||||||
|
self.assertEqual(len(levels), 3)
|
||||||
|
self.assertEqual(levels.mapped('tone'), ['gentle', 'firm', 'legal'])
|
||||||
44
fusion_accounting_followup/tests/test_fusion_followup_run.py
Normal file
44
fusion_accounting_followup/tests/test_fusion_followup_run.py
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
from odoo.tests.common import TransactionCase
|
||||||
|
from odoo.tests import tagged
|
||||||
|
|
||||||
|
|
||||||
|
@tagged('post_install', '-at_install')
|
||||||
|
class TestFusionFollowupRun(TransactionCase):
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def setUpClass(cls):
|
||||||
|
super().setUpClass()
|
||||||
|
cls.partner = cls.env['res.partner'].create({'name': 'Run Test Partner'})
|
||||||
|
cls.level = cls.env['fusion.followup.level'].create({
|
||||||
|
'name': 'Reminder', 'sequence': 301, 'delay_days': 7, 'tone': 'gentle',
|
||||||
|
})
|
||||||
|
|
||||||
|
def test_create_minimal(self):
|
||||||
|
run = self.env['fusion.followup.run'].create({
|
||||||
|
'partner_id': self.partner.id,
|
||||||
|
'level_id': self.level.id,
|
||||||
|
})
|
||||||
|
self.assertEqual(run.state, 'draft')
|
||||||
|
self.assertTrue(run.execution_date)
|
||||||
|
|
||||||
|
def test_action_mark_sent(self):
|
||||||
|
run = self.env['fusion.followup.run'].create({
|
||||||
|
'partner_id': self.partner.id,
|
||||||
|
'level_id': self.level.id,
|
||||||
|
})
|
||||||
|
run.action_mark_sent()
|
||||||
|
self.assertEqual(run.state, 'sent')
|
||||||
|
|
||||||
|
def test_action_mark_failed_records_error(self):
|
||||||
|
run = self.env['fusion.followup.run'].create({
|
||||||
|
'partner_id': self.partner.id,
|
||||||
|
})
|
||||||
|
run.action_mark_failed(error='SMTP unreachable')
|
||||||
|
self.assertEqual(run.state, 'failed')
|
||||||
|
self.assertEqual(run.error_message, 'SMTP unreachable')
|
||||||
|
|
||||||
|
def test_partner_required(self):
|
||||||
|
with self.assertRaises(Exception):
|
||||||
|
self.env['fusion.followup.run'].create({
|
||||||
|
'level_id': self.level.id,
|
||||||
|
})
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
from odoo.tests.common import TransactionCase
|
||||||
|
from odoo.tests import tagged
|
||||||
|
|
||||||
|
|
||||||
|
@tagged('post_install', '-at_install')
|
||||||
|
class TestFusionFollowupTextCache(TransactionCase):
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def setUpClass(cls):
|
||||||
|
super().setUpClass()
|
||||||
|
cls.partner = cls.env['res.partner'].create({'name': 'Cache Test Partner'})
|
||||||
|
cls.level = cls.env['fusion.followup.level'].create({
|
||||||
|
'name': 'Reminder', 'sequence': 401, 'delay_days': 7, 'tone': 'gentle',
|
||||||
|
})
|
||||||
|
cls.cache = cls.env['fusion.followup.text.cache']
|
||||||
|
|
||||||
|
def _kwargs(self, **overrides):
|
||||||
|
base = dict(
|
||||||
|
partner_id=self.partner.id, level_id=self.level.id,
|
||||||
|
overdue_amount=1234.56, longest_overdue_days=10,
|
||||||
|
invoice_count=3, tone='gentle',
|
||||||
|
)
|
||||||
|
base.update(overrides)
|
||||||
|
return base
|
||||||
|
|
||||||
|
def test_fingerprint_stable_and_unique(self):
|
||||||
|
fp1 = self.cache.compute_fingerprint(**self._kwargs())
|
||||||
|
fp2 = self.cache.compute_fingerprint(**self._kwargs())
|
||||||
|
fp3 = self.cache.compute_fingerprint(**self._kwargs(tone='firm'))
|
||||||
|
self.assertEqual(fp1, fp2)
|
||||||
|
self.assertNotEqual(fp1, fp3)
|
||||||
|
self.assertEqual(len(fp1), 64)
|
||||||
|
|
||||||
|
def test_lookup_returns_empty_when_missing(self):
|
||||||
|
result = self.cache.lookup(**self._kwargs())
|
||||||
|
self.assertFalse(result)
|
||||||
|
|
||||||
|
def test_lookup_finds_cached_entry(self):
|
||||||
|
kwargs = self._kwargs()
|
||||||
|
fp = self.cache.compute_fingerprint(**kwargs)
|
||||||
|
entry = self.cache.create({
|
||||||
|
'partner_id': self.partner.id,
|
||||||
|
'level_id': self.level.id,
|
||||||
|
'fingerprint': fp,
|
||||||
|
'subject': 'Hi',
|
||||||
|
'body': 'Please pay.',
|
||||||
|
'tone_used': 'gentle',
|
||||||
|
})
|
||||||
|
found = self.cache.lookup(**kwargs)
|
||||||
|
self.assertEqual(found.id, entry.id)
|
||||||
|
|
||||||
|
def test_action_increment_use(self):
|
||||||
|
entry = self.cache.create({
|
||||||
|
'partner_id': self.partner.id,
|
||||||
|
'fingerprint': 'abc123',
|
||||||
|
})
|
||||||
|
self.assertEqual(entry.use_count, 0)
|
||||||
|
entry.action_increment_use()
|
||||||
|
entry.action_increment_use()
|
||||||
|
self.assertEqual(entry.use_count, 2)
|
||||||
58
fusion_accounting_followup/tests/test_level_resolver.py
Normal file
58
fusion_accounting_followup/tests/test_level_resolver.py
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
from datetime import date, timedelta
|
||||||
|
from odoo.tests.common import TransactionCase
|
||||||
|
from odoo.tests import tagged
|
||||||
|
from odoo.addons.fusion_accounting_followup.services.level_resolver import (
|
||||||
|
FollowupLevelSpec, resolve_level,
|
||||||
|
)
|
||||||
|
from odoo.addons.fusion_accounting_followup.services.overdue_aging import compute_aging
|
||||||
|
|
||||||
|
|
||||||
|
@tagged('post_install', '-at_install')
|
||||||
|
class TestLevelResolver(TransactionCase):
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
super().setUp()
|
||||||
|
self.levels = [
|
||||||
|
FollowupLevelSpec(sequence=1, name='Reminder', delay_days=7, tone='gentle'),
|
||||||
|
FollowupLevelSpec(sequence=2, name='Warning', delay_days=30, tone='firm'),
|
||||||
|
FollowupLevelSpec(sequence=3, name='Legal Notice', delay_days=60, tone='legal'),
|
||||||
|
]
|
||||||
|
|
||||||
|
def test_no_overdue_returns_none(self):
|
||||||
|
as_of = date(2026, 4, 19)
|
||||||
|
lines = [{'date_maturity': as_of + timedelta(days=10), 'amount_residual': 100}]
|
||||||
|
report = compute_aging(move_lines=lines, as_of=as_of)
|
||||||
|
result = resolve_level(aging_report=report, levels=self.levels)
|
||||||
|
self.assertIsNone(result)
|
||||||
|
|
||||||
|
def test_15_days_overdue_picks_reminder(self):
|
||||||
|
as_of = date(2026, 4, 19)
|
||||||
|
lines = [{'date_maturity': as_of - timedelta(days=15), 'amount_residual': 100}]
|
||||||
|
report = compute_aging(move_lines=lines, as_of=as_of)
|
||||||
|
result = resolve_level(aging_report=report, levels=self.levels)
|
||||||
|
self.assertEqual(result.name, 'Reminder')
|
||||||
|
|
||||||
|
def test_45_days_overdue_picks_warning(self):
|
||||||
|
as_of = date(2026, 4, 19)
|
||||||
|
lines = [{'date_maturity': as_of - timedelta(days=45), 'amount_residual': 200}]
|
||||||
|
report = compute_aging(move_lines=lines, as_of=as_of)
|
||||||
|
result = resolve_level(aging_report=report, levels=self.levels)
|
||||||
|
self.assertEqual(result.name, 'Warning')
|
||||||
|
|
||||||
|
def test_75_days_overdue_picks_legal(self):
|
||||||
|
as_of = date(2026, 4, 19)
|
||||||
|
lines = [{'date_maturity': as_of - timedelta(days=75), 'amount_residual': 300}]
|
||||||
|
report = compute_aging(move_lines=lines, as_of=as_of)
|
||||||
|
result = resolve_level(aging_report=report, levels=self.levels)
|
||||||
|
self.assertEqual(result.name, 'Legal Notice')
|
||||||
|
|
||||||
|
def test_no_levels_returns_none(self):
|
||||||
|
as_of = date(2026, 4, 19)
|
||||||
|
lines = [{'date_maturity': as_of - timedelta(days=30), 'amount_residual': 100}]
|
||||||
|
report = compute_aging(move_lines=lines, as_of=as_of)
|
||||||
|
result = resolve_level(aging_report=report, levels=[])
|
||||||
|
self.assertIsNone(result)
|
||||||
|
|
||||||
|
def test_invalid_tone_raises(self):
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
FollowupLevelSpec(sequence=1, name='X', delay_days=7, tone='invalid')
|
||||||
69
fusion_accounting_followup/tests/test_overdue_aging.py
Normal file
69
fusion_accounting_followup/tests/test_overdue_aging.py
Normal file
@@ -0,0 +1,69 @@
|
|||||||
|
from datetime import date, timedelta
|
||||||
|
from odoo.tests.common import TransactionCase
|
||||||
|
from odoo.tests import tagged
|
||||||
|
from odoo.addons.fusion_accounting_followup.services.overdue_aging import (
|
||||||
|
compute_aging, BUCKETS,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@tagged('post_install', '-at_install')
|
||||||
|
class TestOverdueAging(TransactionCase):
|
||||||
|
|
||||||
|
def test_empty_lines_returns_zero_buckets(self):
|
||||||
|
report = compute_aging(move_lines=[], as_of=date(2026, 4, 19))
|
||||||
|
self.assertEqual(report.total_amount, 0)
|
||||||
|
self.assertEqual(len(report.buckets), len(BUCKETS))
|
||||||
|
for b in report.buckets:
|
||||||
|
self.assertEqual(b.amount, 0)
|
||||||
|
|
||||||
|
def test_current_bucket_for_future_maturity(self):
|
||||||
|
as_of = date(2026, 4, 19)
|
||||||
|
lines = [{'date_maturity': date(2026, 5, 19), 'amount_residual': 100}]
|
||||||
|
report = compute_aging(move_lines=lines, as_of=as_of)
|
||||||
|
current = next(b for b in report.buckets if b.name == 'current')
|
||||||
|
self.assertEqual(current.amount, 100)
|
||||||
|
self.assertEqual(report.total_overdue_amount, 0)
|
||||||
|
|
||||||
|
def test_30_day_bucket(self):
|
||||||
|
as_of = date(2026, 4, 19)
|
||||||
|
lines = [{'date_maturity': as_of - timedelta(days=15), 'amount_residual': 200}]
|
||||||
|
report = compute_aging(move_lines=lines, as_of=as_of)
|
||||||
|
b = next(b for b in report.buckets if b.name == '1_30')
|
||||||
|
self.assertEqual(b.amount, 200)
|
||||||
|
|
||||||
|
def test_60_day_bucket(self):
|
||||||
|
as_of = date(2026, 4, 19)
|
||||||
|
lines = [{'date_maturity': as_of - timedelta(days=45), 'amount_residual': 300}]
|
||||||
|
report = compute_aging(move_lines=lines, as_of=as_of)
|
||||||
|
b = next(b for b in report.buckets if b.name == '31_60')
|
||||||
|
self.assertEqual(b.amount, 300)
|
||||||
|
|
||||||
|
def test_120_plus_bucket(self):
|
||||||
|
as_of = date(2026, 4, 19)
|
||||||
|
lines = [{'date_maturity': as_of - timedelta(days=200), 'amount_residual': 500}]
|
||||||
|
report = compute_aging(move_lines=lines, as_of=as_of)
|
||||||
|
b = next(b for b in report.buckets if b.name == '120_plus')
|
||||||
|
self.assertEqual(b.amount, 500)
|
||||||
|
|
||||||
|
def test_total_overdue_excludes_current(self):
|
||||||
|
as_of = date(2026, 4, 19)
|
||||||
|
lines = [
|
||||||
|
{'date_maturity': as_of + timedelta(days=10), 'amount_residual': 100},
|
||||||
|
{'date_maturity': as_of - timedelta(days=10), 'amount_residual': 200},
|
||||||
|
{'date_maturity': as_of - timedelta(days=50), 'amount_residual': 300},
|
||||||
|
]
|
||||||
|
report = compute_aging(move_lines=lines, as_of=as_of)
|
||||||
|
self.assertEqual(report.total_amount, 600)
|
||||||
|
self.assertEqual(report.total_overdue_amount, 500)
|
||||||
|
|
||||||
|
def test_buckets_sum_equals_total(self):
|
||||||
|
as_of = date(2026, 4, 19)
|
||||||
|
lines = [
|
||||||
|
{'date_maturity': as_of + timedelta(days=10), 'amount_residual': 100},
|
||||||
|
{'date_maturity': as_of - timedelta(days=15), 'amount_residual': 200},
|
||||||
|
{'date_maturity': as_of - timedelta(days=75), 'amount_residual': 300},
|
||||||
|
{'date_maturity': as_of - timedelta(days=200), 'amount_residual': 500},
|
||||||
|
]
|
||||||
|
report = compute_aging(move_lines=lines, as_of=as_of)
|
||||||
|
bucket_sum = sum(b.amount for b in report.buckets)
|
||||||
|
self.assertAlmostEqual(bucket_sum, report.total_amount, places=2)
|
||||||
27
fusion_accounting_followup/tests/test_res_partner_inherit.py
Normal file
27
fusion_accounting_followup/tests/test_res_partner_inherit.py
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
from odoo.tests.common import TransactionCase
|
||||||
|
from odoo.tests import tagged
|
||||||
|
|
||||||
|
|
||||||
|
@tagged('post_install', '-at_install')
|
||||||
|
class TestResPartnerFollowup(TransactionCase):
|
||||||
|
|
||||||
|
def test_default_status_no_action(self):
|
||||||
|
partner = self.env['res.partner'].create({'name': 'Default Status'})
|
||||||
|
self.assertEqual(partner.fusion_followup_status, 'no_action')
|
||||||
|
self.assertEqual(partner.fusion_followup_risk_band, 'low')
|
||||||
|
self.assertEqual(partner.fusion_followup_risk_score, 0)
|
||||||
|
|
||||||
|
def test_run_count_reflects_history(self):
|
||||||
|
partner = self.env['res.partner'].create({'name': 'History Partner'})
|
||||||
|
self.assertEqual(partner.fusion_followup_run_count, 0)
|
||||||
|
for _ in range(3):
|
||||||
|
self.env['fusion.followup.run'].create({'partner_id': partner.id})
|
||||||
|
partner.invalidate_recordset(['fusion_followup_run_count', 'fusion_followup_run_ids'])
|
||||||
|
self.assertEqual(partner.fusion_followup_run_count, 3)
|
||||||
|
|
||||||
|
def test_action_view_followup_history_returns_action(self):
|
||||||
|
partner = self.env['res.partner'].create({'name': 'Action Partner'})
|
||||||
|
action = partner.action_view_followup_history()
|
||||||
|
self.assertEqual(action['res_model'], 'fusion.followup.run')
|
||||||
|
self.assertEqual(action['domain'], [('partner_id', '=', partner.id)])
|
||||||
|
self.assertEqual(action['context']['default_partner_id'], partner.id)
|
||||||
48
fusion_accounting_followup/tests/test_risk_scorer.py
Normal file
48
fusion_accounting_followup/tests/test_risk_scorer.py
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
from odoo.tests.common import TransactionCase
|
||||||
|
from odoo.tests import tagged
|
||||||
|
from odoo.addons.fusion_accounting_followup.services.risk_scorer import (
|
||||||
|
score_partner, PartnerRiskScore,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@tagged('post_install', '-at_install')
|
||||||
|
class TestRiskScorer(TransactionCase):
|
||||||
|
|
||||||
|
def test_no_history_returns_low(self):
|
||||||
|
result = score_partner()
|
||||||
|
self.assertEqual(result.band, 'low')
|
||||||
|
self.assertLess(result.score, 30)
|
||||||
|
|
||||||
|
def test_chronic_late_pays_returns_high(self):
|
||||||
|
result = score_partner(
|
||||||
|
total_invoices=20, paid_late_count=18,
|
||||||
|
avg_days_late=45, longest_overdue_days=90,
|
||||||
|
open_overdue_amount=15000, average_invoice_amount=2000,
|
||||||
|
)
|
||||||
|
self.assertIn(result.band, ('high', 'critical'))
|
||||||
|
self.assertGreater(len(result.drivers), 0)
|
||||||
|
|
||||||
|
def test_one_off_overdue_returns_medium(self):
|
||||||
|
result = score_partner(
|
||||||
|
total_invoices=10, paid_late_count=1,
|
||||||
|
avg_days_late=20, longest_overdue_days=45,
|
||||||
|
open_overdue_amount=2000, average_invoice_amount=2000,
|
||||||
|
)
|
||||||
|
self.assertIn(result.band, ('low', 'medium'))
|
||||||
|
|
||||||
|
def test_score_capped_at_100(self):
|
||||||
|
result = score_partner(
|
||||||
|
total_invoices=10, paid_late_count=10,
|
||||||
|
avg_days_late=180, longest_overdue_days=300,
|
||||||
|
open_overdue_amount=999999, average_invoice_amount=1000,
|
||||||
|
)
|
||||||
|
self.assertLessEqual(result.score, 100)
|
||||||
|
|
||||||
|
def test_score_floored_at_0(self):
|
||||||
|
result = score_partner()
|
||||||
|
self.assertGreaterEqual(result.score, 0)
|
||||||
|
|
||||||
|
def test_band_thresholds(self):
|
||||||
|
for s, expected_band in [(10, 'low'), (40, 'medium'), (70, 'high'), (90, 'critical')]:
|
||||||
|
r = PartnerRiskScore(score=s, band=expected_band, drivers=[])
|
||||||
|
self.assertEqual(r.band, expected_band)
|
||||||
25
fusion_accounting_followup/tests/test_tone_selector.py
Normal file
25
fusion_accounting_followup/tests/test_tone_selector.py
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
from odoo.tests.common import TransactionCase
|
||||||
|
from odoo.tests import tagged
|
||||||
|
from odoo.addons.fusion_accounting_followup.services.tone_selector import select_tone
|
||||||
|
|
||||||
|
|
||||||
|
@tagged('post_install', '-at_install')
|
||||||
|
class TestToneSelector(TransactionCase):
|
||||||
|
|
||||||
|
def test_level_1_default_gentle(self):
|
||||||
|
self.assertEqual(select_tone(level_sequence=1), 'gentle')
|
||||||
|
|
||||||
|
def test_level_2_default_firm(self):
|
||||||
|
self.assertEqual(select_tone(level_sequence=2), 'firm')
|
||||||
|
|
||||||
|
def test_level_3_default_legal(self):
|
||||||
|
self.assertEqual(select_tone(level_sequence=3), 'legal')
|
||||||
|
|
||||||
|
def test_critical_risk_escalates_gentle_to_firm(self):
|
||||||
|
self.assertEqual(select_tone(level_sequence=1, risk_score=85), 'firm')
|
||||||
|
|
||||||
|
def test_extreme_risk_escalates_firm_to_legal(self):
|
||||||
|
self.assertEqual(select_tone(level_sequence=2, risk_score=95), 'legal')
|
||||||
|
|
||||||
|
def test_unknown_level_defaults_gentle(self):
|
||||||
|
self.assertEqual(select_tone(level_sequence=99), 'gentle')
|
||||||
0
fusion_accounting_followup/wizards/__init__.py
Normal file
0
fusion_accounting_followup/wizards/__init__.py
Normal file
@@ -19,6 +19,8 @@ access_fp_quote_configurator_estimator,fp.quote.configurator.estimator,model_fp_
|
|||||||
access_fp_quote_configurator_manager,fp.quote.configurator.manager,model_fp_quote_configurator,fusion_plating.group_fusion_plating_manager,1,1,1,1
|
access_fp_quote_configurator_manager,fp.quote.configurator.manager,model_fp_quote_configurator,fusion_plating.group_fusion_plating_manager,1,1,1,1
|
||||||
access_fp_direct_order_wizard_estimator,fp.direct.order.wizard.estimator,model_fp_direct_order_wizard,fusion_plating_configurator.group_fp_estimator,1,1,1,1
|
access_fp_direct_order_wizard_estimator,fp.direct.order.wizard.estimator,model_fp_direct_order_wizard,fusion_plating_configurator.group_fp_estimator,1,1,1,1
|
||||||
access_fp_direct_order_wizard_manager,fp.direct.order.wizard.manager,model_fp_direct_order_wizard,fusion_plating.group_fusion_plating_manager,1,1,1,1
|
access_fp_direct_order_wizard_manager,fp.direct.order.wizard.manager,model_fp_direct_order_wizard,fusion_plating.group_fusion_plating_manager,1,1,1,1
|
||||||
|
access_fp_direct_order_line_estimator,fp.direct.order.line.estimator,model_fp_direct_order_line,fusion_plating_configurator.group_fp_estimator,1,1,1,1
|
||||||
|
access_fp_direct_order_line_manager,fp.direct.order.line.manager,model_fp_direct_order_line,fusion_plating.group_fusion_plating_manager,1,1,1,1
|
||||||
access_fp_part_import_wizard_estimator,fp.part.catalog.import.wizard.estimator,model_fp_part_catalog_import_wizard,fusion_plating_configurator.group_fp_estimator,1,1,1,1
|
access_fp_part_import_wizard_estimator,fp.part.catalog.import.wizard.estimator,model_fp_part_catalog_import_wizard,fusion_plating_configurator.group_fp_estimator,1,1,1,1
|
||||||
access_fp_part_import_wizard_manager,fp.part.catalog.import.wizard.manager,model_fp_part_catalog_import_wizard,fusion_plating.group_fusion_plating_manager,1,1,1,1
|
access_fp_part_import_wizard_manager,fp.part.catalog.import.wizard.manager,model_fp_part_catalog_import_wizard,fusion_plating.group_fusion_plating_manager,1,1,1,1
|
||||||
access_fp_customer_price_list_operator,fp.customer.price.list.operator,model_fp_customer_price_list,fusion_plating.group_fusion_plating_operator,1,0,0,0
|
access_fp_customer_price_list_operator,fp.customer.price.list.operator,model_fp_customer_price_list,fusion_plating.group_fusion_plating_operator,1,0,0,0
|
||||||
|
|||||||
|
@@ -3,4 +3,5 @@
|
|||||||
# License OPL-1 (Odoo Proprietary License v1.0)
|
# License OPL-1 (Odoo Proprietary License v1.0)
|
||||||
|
|
||||||
from . import fp_direct_order_wizard
|
from . import fp_direct_order_wizard
|
||||||
|
from . import fp_direct_order_line
|
||||||
from . import fp_part_catalog_import_wizard
|
from . import fp_part_catalog_import_wizard
|
||||||
|
|||||||
@@ -0,0 +1,46 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# Copyright 2026 Nexa Systems Inc.
|
||||||
|
# License OPL-1 (Odoo Proprietary License v1.0)
|
||||||
|
# Part of the Fusion Plating product family.
|
||||||
|
|
||||||
|
from odoo import api, fields, models
|
||||||
|
|
||||||
|
|
||||||
|
class FpDirectOrderLine(models.TransientModel):
|
||||||
|
_name = 'fp.direct.order.line'
|
||||||
|
_description = 'Fusion Plating - Direct Order Line'
|
||||||
|
_order = 'sequence, id'
|
||||||
|
|
||||||
|
wizard_id = fields.Many2one(
|
||||||
|
'fp.direct.order.wizard',
|
||||||
|
required=True,
|
||||||
|
ondelete='cascade',
|
||||||
|
)
|
||||||
|
sequence = fields.Integer(default=10)
|
||||||
|
|
||||||
|
part_catalog_id = fields.Many2one(
|
||||||
|
'fp.part.catalog',
|
||||||
|
string='Part',
|
||||||
|
required=True,
|
||||||
|
)
|
||||||
|
coating_config_id = fields.Many2one(
|
||||||
|
'fp.coating.config',
|
||||||
|
string='Primary Treatment',
|
||||||
|
required=True,
|
||||||
|
)
|
||||||
|
quantity = fields.Integer(string='Qty', default=1, required=True)
|
||||||
|
currency_id = fields.Many2one(related='wizard_id.currency_id')
|
||||||
|
unit_price = fields.Monetary(
|
||||||
|
string='Unit Price',
|
||||||
|
currency_field='currency_id',
|
||||||
|
)
|
||||||
|
line_subtotal = fields.Monetary(
|
||||||
|
string='Subtotal',
|
||||||
|
currency_field='currency_id',
|
||||||
|
compute='_compute_line_subtotal',
|
||||||
|
)
|
||||||
|
|
||||||
|
@api.depends('quantity', 'unit_price')
|
||||||
|
def _compute_line_subtotal(self):
|
||||||
|
for rec in self:
|
||||||
|
rec.line_subtotal = (rec.quantity or 0) * (rec.unit_price or 0.0)
|
||||||
Reference in New Issue
Block a user