[IMP] account_move_base_import: black, isort, prettier

This commit is contained in:
Damien Crier
2020-07-15 11:43:01 +02:00
committed by Florian da Costa
parent b6902bbaad
commit 8b9256054a
16 changed files with 653 additions and 571 deletions

View File

@@ -3,14 +3,13 @@
# Copyright 2013 Savoir-faire Linux
# Copyright 2014 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html)
import traceback
import sys
import logging
import sys
import traceback
from odoo import _, api, fields, models
from odoo.exceptions import ValidationError
_logger = logging.getLogger(__name__)
@@ -38,68 +37,81 @@ class AccountMoveCompletionRule(models.Model):
process. The reference should contain the invoice number or the SO number
or any reference that will be matched by the invoice accounting move.
"""
_name = "account.move.completion.rule"
_order = "sequence asc"
_description = "Account move completion method"
sequence = fields.Integer(
string='Sequence',
help="Lower means parsed first.")
name = fields.Char(
string='Name')
sequence = fields.Integer(string="Sequence", help="Lower means parsed first.")
name = fields.Char(string="Name")
journal_ids = fields.Many2many(
comodel_name='account.journal',
relation='account_journal_completion_rule_rel',
string='Related journals')
function_to_call = fields.Selection([
('get_from_name_and_invoice',
'From line name (based on customer invoice number)'),
('get_from_name_and_supplier_invoice',
'From line name (based on supplier invoice number)'),
('get_from_name_and_partner_field',
'From line name (based on partner field)'),
('get_from_name_and_partner_name',
'From line name (based on partner name)')
], string='Method'
comodel_name="account.journal",
relation="account_journal_completion_rule_rel",
string="Related journals",
)
function_to_call = fields.Selection(
[
(
"get_from_name_and_invoice",
"From line name (based on customer invoice number)",
),
(
"get_from_name_and_supplier_invoice",
"From line name (based on supplier invoice number)",
),
(
"get_from_name_and_partner_field",
"From line name (based on partner field)",
),
(
"get_from_name_and_partner_name",
"From line name (based on partner name)",
),
],
string="Method",
)
def _find_invoice(self, line, inv_type):
"""Find invoice related to statement line"""
inv_obj = self.env['account.invoice']
if inv_type == 'supplier':
type_domain = ('in_invoice', 'in_refund')
number_field = 'reference'
elif inv_type == 'customer':
type_domain = ('out_invoice', 'out_refund')
number_field = 'number'
inv_obj = self.env["account.invoice"]
if inv_type == "supplier":
type_domain = ("in_invoice", "in_refund")
number_field = "reference"
elif inv_type == "customer":
type_domain = ("out_invoice", "out_refund")
number_field = "number"
else:
raise ValidationError(
_('Invalid invoice type for completion: %s') % inv_type)
_("Invalid invoice type for completion: %s") % inv_type
)
invoices = inv_obj.search([(number_field, '=', line.name.strip()),
('type', 'in', type_domain)])
invoices = inv_obj.search(
[(number_field, "=", line.name.strip()), ("type", "in", type_domain)]
)
if invoices:
if len(invoices) == 1:
return invoices
else:
raise ErrorTooManyPartner(
_('Line named "%s" was matched by more than one '
'partner while looking on %s invoices') %
(line.name, inv_type))
_(
'Line named "%s" was matched by more than one '
"partner while looking on %s invoices"
)
% (line.name, inv_type)
)
return False
def _from_invoice(self, line, inv_type):
"""Populate statement line values"""
if inv_type not in ('supplier', 'customer'):
if inv_type not in ("supplier", "customer"):
raise ValidationError(
_('Invalid invoice type for completion: %s') %
inv_type)
_("Invalid invoice type for completion: %s") % inv_type
)
res = {}
invoice = self._find_invoice(line, inv_type)
if invoice:
partner_id = invoice.commercial_partner_id.id
res = {'partner_id': partner_id,
'account_id': invoice.account_id.id}
res = {"partner_id": partner_id, "account_id": invoice.account_id.id}
return res
# Should be private but data are initialised with no update XML
@@ -117,7 +129,7 @@ class AccountMoveCompletionRule(models.Model):
'account_id': value,
...}
"""
return self._from_invoice(line, 'supplier')
return self._from_invoice(line, "supplier")
# Should be private but data are initialised with no update XML
def get_from_name_and_invoice(self, line):
@@ -134,7 +146,7 @@ class AccountMoveCompletionRule(models.Model):
'account_id': value,
...}
"""
return self._from_invoice(line, 'customer')
return self._from_invoice(line, "customer")
# Should be private but data are initialised with no update XML
def get_from_name_and_partner_field(self, line):
@@ -155,21 +167,20 @@ class AccountMoveCompletionRule(models.Model):
...}
"""
res = {}
partner_obj = self.env['res.partner']
partner_obj = self.env["res.partner"]
or_regex = ".*;? *%s *;?.*" % line.name
sql = ("SELECT id from res_partner"
" WHERE bank_statement_label ~* %s")
self.env.cr.execute(sql, (or_regex, ))
sql = "SELECT id from res_partner" " WHERE bank_statement_label ~* %s"
self.env.cr.execute(sql, (or_regex,))
partner_ids = self.env.cr.fetchall()
partners = partner_obj.browse([x[0] for x in partner_ids])
if partners:
if len(partners) > 1:
msg = (_('Line named "%s" was matched by more than '
'one partner while looking on partner label: %s') %
(line.name,
','.join([x.name for x in partners])))
msg = _(
'Line named "%s" was matched by more than '
"one partner while looking on partner label: %s"
) % (line.name, ",".join([x.name for x in partners]))
raise ErrorTooManyPartner(msg)
res['partner_id'] = partners[0].id
res["partner_id"] = partners[0].id
return res
def get_from_name_and_partner_name(self, line):
@@ -210,10 +221,13 @@ class AccountMoveCompletionRule(models.Model):
if result:
if len(result) > 1:
raise ErrorTooManyPartner(
_('Line named "%s" was matched by more than one '
'partner while looking on partner by name') %
line.name)
res['partner_id'] = result[0][0]
_(
'Line named "%s" was matched by more than one '
"partner while looking on partner by name"
)
% line.name
)
res["partner_id"] = result[0][0]
return res
@@ -227,6 +241,7 @@ class AccountMoveLine(models.Model):
Have a look in account_move_base_import module to see how we've done
it.
"""
_inherit = "account.move.line"
_order = "already_completed desc, date asc"
@@ -234,7 +249,8 @@ class AccountMoveLine(models.Model):
string="Auto-Completed",
default=False,
help="When this checkbox is ticked, the auto-completion "
"process/button will ignore this line.")
"process/button will ignore this line.",
)
def _get_line_values_from_rules(self):
"""We'll try to find out the values related to the line based on rules
@@ -268,12 +284,11 @@ class AccountMoveLine(models.Model):
rules = self.journal_id.rule_ids
for rule in rules:
method_to_call = getattr(
self.env['account.move.completion.rule'],
rule.function_to_call
self.env["account.move.completion.rule"], rule.function_to_call
)
result = method_to_call(self)
if result:
result['already_completed'] = True
result["already_completed"] = True
return result
return None
@@ -282,17 +297,17 @@ class AccountMove(models.Model):
"""We add a basic button and stuff to support the auto-completion
of the bank statement once line have been imported or manually fulfill.
"""
_name = 'account.move'
_inherit = ['account.move', 'mail.thread']
_name = "account.move"
_inherit = ["account.move", "mail.thread"]
used_for_completion = fields.Boolean(
related='journal_id.used_for_completion',
readonly=True)
completion_logs = fields.Text(string='Completion Log', readonly=True)
import_partner_id = fields.Many2one('res.partner',
string="Partner from import")
related="journal_id.used_for_completion", readonly=True
)
completion_logs = fields.Text(string="Completion Log", readonly=True)
import_partner_id = fields.Many2one("res.partner", string="Partner from import")
@api.depends('line_ids.partner_id', 'import_partner_id')
@api.depends("line_ids.partner_id", "import_partner_id")
def _compute_partner_id(self):
for move in self:
if move.import_partner_id:
@@ -314,14 +329,25 @@ class AccountMove(models.Model):
number_line = len(self.line_ids)
log = self.completion_logs or ""
completion_date = fields.Datetime.now()
message = (_("%s Account Move %s has %s/%s lines completed by "
"%s \n%s\n%s\n") % (completion_date, self.name,
number_imported, number_line,
user_name, error_msg, log))
self.write({'completion_logs': message})
message = _(
"%s Account Move %s has %s/%s lines completed by " "%s \n%s\n%s\n"
) % (
completion_date,
self.name,
number_imported,
number_line,
user_name,
error_msg,
log,
)
self.write({"completion_logs": message})
body = (_('Statement ID %s auto-completed for %s/%s lines completed') %
(self.name, number_imported, number_line)),
body = (
(
_("Statement ID %s auto-completed for %s/%s lines completed")
% (self.name, number_imported, number_line)
),
)
self.message_post(body=body)
return True
@@ -345,9 +371,10 @@ class AccountMove(models.Model):
except Exception as exc:
msg_lines.append(repr(exc))
error_type, error_value, trbk = sys.exc_info()
st = "Error: %s\nDescription: %s\nTraceback:" % (
error_type.__name__, error_value)
st += ''.join(traceback.format_tb(trbk, 30))
st = "Error: {}\nDescription: {}\nTraceback:".format(
error_type.__name__, error_value,
)
st += "".join(traceback.format_tb(trbk, 30))
_logger.error(st)
if res:
try:
@@ -355,10 +382,11 @@ class AccountMove(models.Model):
except Exception as exc:
msg_lines.append(repr(exc))
error_type, error_value, trbk = sys.exc_info()
st = "Error: %s\nDescription: %s\nTraceback:" % (
error_type.__name__, error_value)
st += ''.join(traceback.format_tb(trbk, 30))
st = "Error: {}\nDescription: {}\nTraceback:".format(
error_type.__name__, error_value,
)
st += "".join(traceback.format_tb(trbk, 30))
_logger.error(st)
msg = '\n'.join(msg_lines)
msg = "\n".join(msg_lines)
self.write_completion_log(msg, compl_lines)
return True