odoo_account_ebics/account_ebics/models/ebics_file.py

470 lines
16 KiB
Python
Raw Normal View History

2022-05-10 19:40:54 +00:00
# Copyright 2009-2022 Noviat.
2019-12-22 09:54:00 +00:00
# License LGPL-3 or later (http://www.gnu.org/licenses/lpgl).
2018-08-14 15:04:39 +00:00
import base64
2018-08-14 15:04:39 +00:00
import logging
from odoo import _, fields, models
2018-08-14 15:04:39 +00:00
from odoo.exceptions import UserError
2022-05-10 19:40:54 +00:00
from odoo.tools.safe_eval import safe_eval
2018-08-14 15:04:39 +00:00
_logger = logging.getLogger(__name__)
class EbicsFile(models.Model):
2022-05-10 19:40:54 +00:00
_name = "ebics.file"
_description = "Object to store EBICS Data Files"
_order = "date desc"
_sql_constraints = [
2022-05-10 19:40:54 +00:00
(
"name_uniq",
"unique (name, format_id)",
"This File has already been down- or uploaded !",
)
]
2018-08-14 15:04:39 +00:00
2022-05-10 19:40:54 +00:00
name = fields.Char(string="Filename")
data = fields.Binary(string="File", readonly=True)
2018-08-14 15:04:39 +00:00
format_id = fields.Many2one(
2022-05-10 19:40:54 +00:00
comodel_name="ebics.file.format", string="EBICS File Formats", readonly=True
)
type = fields.Selection(related="format_id.type", readonly=True)
2018-08-14 15:04:39 +00:00
date_from = fields.Date(
2022-05-10 19:40:54 +00:00
readonly=True, help="'Date From' as entered in the download wizard."
)
2018-08-14 15:04:39 +00:00
date_to = fields.Date(
2022-05-10 19:40:54 +00:00
readonly=True, help="'Date To' as entered in the download wizard."
)
2018-08-14 15:04:39 +00:00
date = fields.Datetime(
2022-05-10 19:40:54 +00:00
required=True, readonly=True, help="File Upload/Download date"
)
2018-08-14 15:04:39 +00:00
bank_statement_ids = fields.One2many(
2022-05-10 19:40:54 +00:00
comodel_name="account.bank.statement",
inverse_name="ebics_file_id",
string="Generated Bank Statements",
readonly=True,
)
2018-08-14 15:04:39 +00:00
state = fields.Selection(
2022-05-10 19:40:54 +00:00
[("draft", "Draft"), ("done", "Done")],
default="draft",
required=True,
readonly=True,
)
2018-08-14 15:04:39 +00:00
user_id = fields.Many2one(
2022-05-10 19:40:54 +00:00
comodel_name="res.users",
string="User",
2018-08-14 15:04:39 +00:00
default=lambda self: self.env.user,
2022-05-10 19:40:54 +00:00
readonly=True,
)
ebics_userid_id = fields.Many2one(
2022-05-10 19:40:54 +00:00
comodel_name="ebics.userid",
string="EBICS UserID",
ondelete="restrict",
readonly=True,
)
note = fields.Text(string="Notes")
note_process = fields.Text(string="Notes")
company_ids = fields.Many2many(
2022-05-10 19:40:54 +00:00
comodel_name="res.company",
string="Companies",
help="Companies sharing this EBICS file.",
)
2018-08-14 15:04:39 +00:00
def unlink(self):
ff_methods = self._file_format_methods()
for ebics_file in self:
2022-05-10 19:40:54 +00:00
if ebics_file.state == "done":
raise UserError(_("You can only remove EBICS files in state 'Draft'."))
2018-08-14 15:04:39 +00:00
# execute format specific actions
ff = ebics_file.format_id.download_process_method
2018-08-14 15:04:39 +00:00
if ff in ff_methods:
2022-05-10 19:40:54 +00:00
if ff_methods[ff].get("unlink"):
ff_methods[ff]["unlink"](ebics_file)
2018-08-14 15:04:39 +00:00
# remove bank statements
ebics_file.bank_statement_ids.unlink()
return super(EbicsFile, self).unlink()
def set_to_draft(self):
2022-05-10 19:40:54 +00:00
return self.write({"state": "draft"})
2018-08-14 15:04:39 +00:00
def set_to_done(self):
2022-05-10 19:40:54 +00:00
return self.write({"state": "done"})
2018-08-14 15:04:39 +00:00
def process(self):
self.ensure_one()
2022-10-27 21:48:16 +00:00
self = self.with_context(allowed_company_ids=self.env.user.company_ids.ids)
2022-05-10 19:40:54 +00:00
self.note_process = ""
2018-08-14 15:04:39 +00:00
ff_methods = self._file_format_methods()
ff = self.format_id.download_process_method
2018-08-14 15:04:39 +00:00
if ff in ff_methods:
2022-05-10 19:40:54 +00:00
if ff_methods[ff].get("process"):
res = ff_methods[ff]["process"](self)
self.state = "done"
2018-08-14 15:04:39 +00:00
return res
else:
return self._process_undefined_format()
def action_open_bank_statements(self):
self.ensure_one()
2022-05-10 19:40:54 +00:00
action = self.env["ir.actions.act_window"]._for_xml_id(
"account.action_bank_statement_tree"
)
domain = safe_eval(action.get("domain") or "[]")
domain += [("id", "in", self._context.get("statement_ids"))]
action.update({"domain": domain})
2018-08-14 15:04:39 +00:00
return action
def button_close(self):
self.ensure_one()
2022-05-10 19:40:54 +00:00
return {"type": "ir.actions.act_window_close"}
2018-08-14 15:04:39 +00:00
def _file_format_methods(self):
"""
Extend this dictionary in order to add support
for extra file formats.
"""
res = {
2022-05-10 19:40:54 +00:00
"cfonb120": {
"process": self._process_cfonb120,
"unlink": self._unlink_cfonb120,
},
"camt.052": {
"process": self._process_camt052,
"unlink": self._unlink_camt052,
},
"camt.053": {
"process": self._process_camt053,
"unlink": self._unlink_camt053,
},
"camt.054": {
"process": self._process_camt054,
"unlink": self._unlink_camt054,
},
"pain.002": {
"process": self._process_pain002,
"unlink": self._unlink_pain002,
},
2018-08-14 15:04:39 +00:00
}
return res
2021-01-30 18:16:52 +00:00
def _check_import_module(self, module, raise_if_not_found=True):
2022-05-10 19:40:54 +00:00
mod = (
self.env["ir.module.module"]
.sudo()
.search([("name", "=like", module), ("state", "=", "installed")])
)
2018-08-14 15:04:39 +00:00
if not mod:
2021-01-30 18:16:52 +00:00
if raise_if_not_found:
2022-05-10 19:40:54 +00:00
raise UserError(
_(
2022-10-27 21:48:16 +00:00
"The module to process the '%(ebics_format)s' format is not installed "
2022-05-10 19:40:54 +00:00
"on your system. "
2022-10-27 21:48:16 +00:00
"\nPlease install module '%(module)s'",
ebics_format=self.format_id.name,
module=module,
2022-05-10 19:40:54 +00:00
)
)
2021-01-30 18:16:52 +00:00
return False
return True
2018-08-14 15:04:39 +00:00
def _process_result_action(self, res):
2020-07-15 18:48:15 +00:00
notifications = []
st_line_ids = []
statement_ids = []
sts_data = []
if res.get("type") and res["type"] == "ir.actions.client":
notifications = res["context"].get("notifications", [])
st_line_ids = res["context"].get("statement_line_ids", [])
if notifications:
for notif in notifications:
parts = []
for k in ["type", "message", "details"]:
if notif.get(k):
msg = "{}: {}".format(k, notif[k])
parts.append(msg)
self.note_process += "\n".join(parts)
self.note_process += "\n"
2022-05-10 19:40:54 +00:00
self.note_process += "\n"
if st_line_ids:
self.flush()
self.env.cr.execute(
"""
SELECT DISTINCT
absl.statement_id,
abs.name, abs.date, abs.company_id,
rc.name AS company_name
FROM account_bank_statement_line absl
INNER JOIN account_bank_statement abs
ON abs.id = absl.statement_id
INNER JOIN res_company rc
ON rc.id = abs.company_id
WHERE absl.id IN %s
ORDER BY date, company_id
""",
(tuple(st_line_ids),),
)
sts_data = self.env.cr.dictfetchall()
else:
if res.get("res_id"):
st_ids = res["res_id"]
else:
st_ids = res["domain"][2]
statements = self.env["account.bank.statement"].browse(st_ids)
for statement in statements:
sts_data.append(
{
"statement_id": statement.id,
"date": statement.date,
"name": statement.name,
"company_name": statement.company_id.name,
}
)
2020-07-18 15:43:35 +00:00
st_cnt = len(sts_data)
if st_cnt:
2022-05-10 19:40:54 +00:00
self.note_process += _("%s bank statements have been imported: ") % st_cnt
self.note_process += "\n"
2020-07-18 15:43:35 +00:00
for st_data in sts_data:
self.note_process += ("\n%s, %s (%s)") % (
2022-05-10 19:40:54 +00:00
st_data["date"],
st_data["name"],
st_data["company_name"],
)
statement_ids = [x["statement_id"] for x in sts_data]
2020-07-15 18:48:15 +00:00
if statement_ids:
self.sudo().bank_statement_ids = [(6, 0, statement_ids)]
ctx = dict(self.env.context, statement_ids=statement_ids)
2022-05-10 19:40:54 +00:00
module = __name__.split("addons.")[1].split(".")[0]
result_view = self.env.ref("%s.ebics_file_view_form_result" % module)
2018-08-14 15:04:39 +00:00
return {
2022-05-10 19:40:54 +00:00
"name": _("Import EBICS File"),
"res_id": self.id,
"view_type": "form",
"view_mode": "form",
"res_model": self._name,
"view_id": result_view.id,
"target": "new",
"context": ctx,
"type": "ir.actions.act_window",
2018-08-14 15:04:39 +00:00
}
@staticmethod
def _process_cfonb120(self):
"""
2020-07-16 21:32:20 +00:00
We do not support the standard _journal_creation_wizard since a single
cfonb120 file may contain statements from different legal entities.
2018-08-14 15:04:39 +00:00
"""
2022-05-10 19:40:54 +00:00
import_module = "account_statement_import_fr_cfonb"
2018-08-14 15:04:39 +00:00
self._check_import_module(import_module)
2022-05-10 19:40:54 +00:00
wiz_model = "account.statement.import"
data_file = base64.b64decode(self.data)
2022-05-10 19:40:54 +00:00
lines = data_file.split(b"\n")
2020-12-14 17:32:49 +00:00
wiz_vals_list = []
2022-05-10 19:40:54 +00:00
st_lines = b""
2020-07-16 21:32:20 +00:00
transactions = False
for line in lines:
rec_type = line[0:2]
acc_number = line[21:32]
2022-05-10 19:40:54 +00:00
st_lines += line + b"\n"
if rec_type == b"04":
2020-07-16 21:32:20 +00:00
transactions = True
2022-05-10 19:40:54 +00:00
if rec_type == b"07":
2020-07-16 21:32:20 +00:00
if transactions:
2022-05-10 19:40:54 +00:00
fn = "_".join([acc_number.decode(), self.name])
wiz_vals_list.append(
{
"statement_filename": fn,
"statement_file": base64.b64encode(st_lines),
}
)
st_lines = b""
2020-07-16 21:32:20 +00:00
transactions = False
result = {
2022-05-10 19:40:54 +00:00
"type": "ir.actions.client",
"tag": "bank_statement_reconciliation_view",
"context": {
"statement_line_ids": [],
"company_ids": self.env.user.company_ids.ids,
"notifications": [],
},
2020-07-16 21:32:20 +00:00
}
2020-12-14 17:32:49 +00:00
for i, wiz_vals in enumerate(wiz_vals_list, start=1):
2022-10-27 21:48:16 +00:00
wiz = (
self.env[wiz_model]
.with_context(active_model="ebics.file")
.create(wiz_vals)
)
2020-12-14 17:32:49 +00:00
res = wiz.import_file_button()
2022-05-10 19:40:54 +00:00
ctx = res.get("context")
if res.get("res_model") == "account.bank.statement.import.journal.creation":
message = _("Error detected while importing statement number %s.\n") % i
message += _("No financial journal found.")
2022-05-10 19:40:54 +00:00
details = _("Bank account number: %s") % ctx.get(
"default_bank_acc_number"
)
result["context"]["notifications"].extend(
[
{
"type": "warning",
"message": message,
"details": details,
}
]
)
continue
2022-05-10 19:40:54 +00:00
result["context"]["statement_line_ids"].extend(ctx["statement_line_ids"])
result["context"]["notifications"].extend(ctx["notifications"])
2020-07-16 21:32:20 +00:00
return self._process_result_action(result)
2018-08-14 15:04:39 +00:00
@staticmethod
def _unlink_cfonb120(self):
"""
Placeholder for cfonb120 specific actions before removing the
EBICS data file and its related bank statements.
"""
2019-12-18 20:23:15 +00:00
@staticmethod
def _process_camt052(self):
2022-05-10 19:40:54 +00:00
import_module = "account_statement_import_camt"
2019-12-18 20:23:15 +00:00
self._check_import_module(import_module)
return self._process_camt053(self)
@staticmethod
def _unlink_camt052(self):
"""
Placeholder for camt052 specific actions before removing the
EBICS data file and its related bank statements.
"""
@staticmethod
def _process_camt054(self):
2022-05-10 19:40:54 +00:00
import_module = "account_statement_import_camt"
self._check_import_module(import_module)
return self._process_camt053(self)
@staticmethod
def _unlink_camt054(self):
"""
Placeholder for camt054 specific actions before removing the
EBICS data file and its related bank statements.
"""
2018-08-14 15:04:39 +00:00
@staticmethod
def _process_camt053(self):
2021-01-30 18:16:52 +00:00
modules = [
2022-05-10 19:40:54 +00:00
("oca", "account_statement_import_camt"),
("oe", "account_bank_statement_import_camt"),
2021-01-30 18:16:52 +00:00
]
found = False
2022-05-10 19:40:54 +00:00
for _src, mod in modules:
2021-01-30 18:16:52 +00:00
if self._check_import_module(mod, raise_if_not_found=False):
found = True
break
if not found:
2022-05-10 19:40:54 +00:00
raise UserError(
_(
2022-10-27 21:48:16 +00:00
"The module to process the '%(ebics_format)s' format is "
"not installed on your system. "
"\nPlease install one of the following modules: \n%(modules)s.",
ebics_format=self.format_id.name,
modules=", ".join([x[1] for x in modules]),
2022-05-10 19:40:54 +00:00
)
2021-01-30 18:16:52 +00:00
)
2022-05-10 19:40:54 +00:00
if _src == "oca":
2021-01-30 18:16:52 +00:00
self._process_camt053_oca()
else:
self._process_camt053_oe()
2021-01-30 18:16:52 +00:00
def _process_camt053_oca(self):
2022-05-10 19:40:54 +00:00
wiz_model = "account.statement.import"
2021-01-30 18:16:52 +00:00
wiz_vals = {
2022-05-10 19:40:54 +00:00
"statement_filename": self.name,
"statement_file": self.data,
2021-01-30 18:16:52 +00:00
}
result = {
2022-05-10 19:40:54 +00:00
"type": "ir.actions.client",
"tag": "bank_statement_reconciliation_view",
"context": {
"statement_line_ids": [],
"company_ids": self.env.user.company_ids.ids,
"notifications": [],
},
2021-01-30 18:16:52 +00:00
}
2022-10-27 21:48:16 +00:00
wiz = (
self.env[wiz_model].with_context(active_model="ebics.file").create(wiz_vals)
)
2021-01-30 18:16:52 +00:00
res = wiz.import_file_button()
2022-05-10 19:40:54 +00:00
ctx = res.get("context")
if res.get("res_model") == "account.bank.statement.import.journal.creation":
message = _("Error detected while importing statement %s.\n") % self.name
2021-01-30 18:16:52 +00:00
message += _("No financial journal found.")
2022-05-10 19:40:54 +00:00
details = _("Bank account number: %s") % ctx.get("default_bank_acc_number")
result["context"]["notifications"].extend(
[
{
"type": "warning",
"message": message,
"details": details,
}
]
)
result["context"]["statement_line_ids"].extend(ctx["statement_line_ids"])
result["context"]["notifications"].extend(ctx["notifications"])
2021-01-30 18:16:52 +00:00
return self._process_result_action(result)
def _process_camt053_oe(self):
2022-05-10 19:40:54 +00:00
wiz_model = "account.bank.statement.import"
2018-08-14 15:04:39 +00:00
wiz_vals = {
2022-05-10 19:40:54 +00:00
"attachment_ids": [
(
0,
0,
{"name": self.name, "datas": self.data, "store_fname": self.name},
)
]
}
2022-10-27 21:48:16 +00:00
wiz = (
self.env[wiz_model].with_context(active_model="ebics.file").create(wiz_vals)
)
2018-08-14 15:04:39 +00:00
res = wiz.import_file()
2022-05-10 19:40:54 +00:00
if res.get("res_model") == "account.bank.statement.import.journal.creation":
if res.get("context"):
bank_account = res["context"].get("default_bank_acc_number")
raise UserError(
_("No financial journal found for Company Bank Account %s")
% bank_account
)
return self._process_result_action(res)
2018-08-14 15:04:39 +00:00
@staticmethod
def _unlink_camt053(self):
"""
Placeholder for camt053 specific actions before removing the
EBICS data file and its related bank statements.
"""
@staticmethod
def _process_pain002(self):
"""
Placeholder for processing pain.002 files.
TODO:
add import logic based upon OCA 'account_payment_return_import'
"""
@staticmethod
def _unlink_pain002(self):
"""
Placeholder for pain.002 specific actions before removing the
EBICS data file.
"""
raise NotImplementedError
2018-08-14 15:04:39 +00:00
def _process_undefined_format(self):
2022-05-10 19:40:54 +00:00
raise UserError(
_(
"The current version of the 'account_ebics' module "
"has no support to automatically process EBICS files "
"with format %s."
)
% self.format_id.name
)