diff --git a/purchase.py b/purchase.py index c0423011f3..99c75cb5d0 100644 --- a/purchase.py +++ b/purchase.py @@ -1,5 +1,6 @@ # This file is part of Tryton. The COPYRIGHT file at the top level of # this repository contains the full copyright notices and license terms. +from trytond.model import fields from trytond.pool import Pool, PoolMeta from trytond.modules.analytic_account import AnalyticMixin @@ -16,21 +17,30 @@ class Purchase: super(Purchase, cls).__setup__() cls._error_messages.update({ 'analytic_account_required': ('Analytic account is required ' - 'on line "%s".'), + 'for "%(roots)s" on line "%(line)s".'), }) def check_for_quotation(self): pool = Pool() - AnalyticAccountEntry = pool.get('analytic.account.entry') + Account = pool.get('analytic_account.account') + mandatory_roots = {a for a in Account.search([ + ('type', '=', 'root'), + ('mandatory', '=', True), + ])} super(Purchase, self).check_for_quotation() for line in self.lines: if line.type != 'line': continue - if not AnalyticAccountEntry.check_root(line.analytic_accounts): - self.raise_user_error('analytic_account_required', - line.rec_name) + analytic_roots = {e.root for e in line.analytic_accounts + if e.account} + if not mandatory_roots <= analytic_roots: + self.raise_user_error('analytic_account_required', { + 'line': line.rec_name, + 'roots': ', '.join(x.rec_name + for x in mandatory_roots - analytic_roots), + }) class PurchaseLine(AnalyticMixin): @@ -58,3 +68,14 @@ class AnalyticAccountEntry: def _get_origin(cls): origins = super(AnalyticAccountEntry, cls)._get_origin() return origins + ['purchase.line'] + + @fields.depends('origin') + def on_change_with_required(self, name=None): + pool = Pool() + PurchaseLine = pool.get('purchase.line') + required = super(AnalyticAccountEntry, self).on_change_with_required( + name) + if (self.origin and isinstance(self.origin, PurchaseLine) + and self.origin.purchase.state in ['cancel', 'draft']): + return False + return required