size
int64 0
304k
| ext
stringclasses 1
value | lang
stringclasses 1
value | branch
stringclasses 1
value | content
stringlengths 0
304k
| avg_line_length
float64 0
238
| max_line_length
int64 0
304k
|
---|---|---|---|---|---|---|
2,308 |
py
|
PYTHON
|
15.0
|
# Copyright 2017-2021 Akretion France (http://www.akretion.com/)
# @author: Alexis de Lattre <[email protected]>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import base64
from odoo import fields, models, tools
class ResCompany(models.Model):
_inherit = "res.company"
xml_format_in_pdf_invoice = fields.Selection(
selection_add=[("factur-x", "Factur-X (CII)")],
default="factur-x",
ondelete={"factur-x": "set null"},
)
facturx_level = fields.Selection(
[
("minimum", "Minimum"),
("basicwl", "Basic without lines"),
("basic", "Basic"),
("en16931", "EN 16931 (Comfort)"),
("extended", "Extended"),
],
string="Factur-X Level",
default="en16931",
help="Unless if you have a good reason, you should always "
"select 'EN 16931 (Comfort)', which is the default value.",
)
facturx_refund_type = fields.Selection(
[
("380", "Type 380 with negative amounts"),
("381", "Type 381 with positive amounts"),
],
string="Factur-X Refund Type",
default="381",
)
facturx_logo = fields.Binary(
compute="_compute_facturx_logo",
string="Factur-X Logo",
help="Logo to include in the visible part of Factur-X invoices",
)
def _compute_facturx_logo(self):
level2logo = {
"minimum": "factur-x-minimum.png",
"basicwl": "factur-x-basicwl.png",
"basic": "factur-x-basic.png",
"en16931": "factur-x-en16931.png",
"extended": "factur-x-extended.png",
}
for company in self:
facturx_logo = False
if (
company.xml_format_in_pdf_invoice == "factur-x"
and company.facturx_level
and company.facturx_level in level2logo
):
fname = level2logo[company.facturx_level]
fname_path = "account_invoice_facturx/static/logos/%s" % fname
f = tools.file_open(fname_path, "rb")
f_binary = f.read()
if f_binary:
facturx_logo = base64.b64encode(f_binary)
company.facturx_logo = facturx_logo
| 34.447761 | 2,308 |
518 |
py
|
PYTHON
|
15.0
|
# Copyright 2017-2021 Akretion France (http://www.akretion.com/)
# @author: Alexis de Lattre <[email protected]>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import fields, models
class ResConfigSettings(models.TransientModel):
_inherit = "res.config.settings"
facturx_level = fields.Selection(related="company_id.facturx_level", readonly=False)
facturx_refund_type = fields.Selection(
related="company_id.facturx_refund_type", readonly=False
)
| 37 | 518 |
781 |
py
|
PYTHON
|
15.0
|
# Copyright 2020 ACSONE
# @author: Simone Orsi <[email protected]>
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
{
"name": "EDI Storage backend support",
"summary": """
Base module to allow exchanging files via storage backend (eg: SFTP).
""",
"version": "15.0.1.2.0",
"development_status": "Beta",
"license": "LGPL-3",
"website": "https://github.com/OCA/edi",
"author": "ACSONE,Odoo Community Association (OCA)",
"depends": ["edi_oca", "storage_backend", "component"],
"data": [
"data/cron.xml",
"data/job_channel_data.xml",
"data/queue_job_function_data.xml",
"security/ir_model_access.xml",
"views/edi_backend_views.xml",
],
"demo": ["demo/edi_backend_demo.xml"],
}
| 32.541667 | 781 |
2,758 |
py
|
PYTHON
|
15.0
|
# Copyright 2021 ForgeFlow S.L. (https://www.forgeflow.com)
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
import base64
import mock
from odoo.addons.edi_oca.tests.common import EDIBackendCommonComponentRegistryTestCase
from odoo.addons.edi_oca.tests.fake_components import FakeInputProcess
LISTENER_MOCK_PATH = (
"odoo.addons.edi_storage_oca.components.listener.EdiStorageListener"
)
class EDIBackendTestCase(EDIBackendCommonComponentRegistryTestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls._load_module_components(cls, "edi_storage_oca")
cls._build_components(
cls,
FakeInputProcess,
)
vals = {
"model": cls.partner._name,
"res_id": cls.partner.id,
"exchange_file": base64.b64encode(b"1234"),
}
cls.record = cls.backend.create_record("test_csv_input", vals)
cls.fake_move_args = None
@classmethod
def _get_backend(cls):
return cls.env.ref("edi_storage_oca.demo_edi_backend_storage")
def setUp(self):
super().setUp()
FakeInputProcess.reset_faked()
def _move_file_mocked(self, *args):
self.fake_move_args = [*args]
if not all([*args]):
return False
return True
def _mock_listener_move_file(self):
return mock.patch(LISTENER_MOCK_PATH + "._move_file", self._move_file_mocked)
def test_01_process_record_success(self):
with self._mock_listener_move_file():
self.record.write({"edi_exchange_state": "input_received"})
self.record.action_exchange_process()
storage, from_dir_str, to_dir_str, filename = self.fake_move_args
self.assertEqual(storage, self.backend.storage_id)
self.assertEqual(from_dir_str, self.backend.input_dir_pending)
self.assertEqual(to_dir_str, self.backend.input_dir_done)
self.assertEqual(filename, self.record.exchange_filename)
def test_02_process_record_with_error(self):
with self._mock_listener_move_file():
self.record.write({"edi_exchange_state": "input_received"})
self.record._set_file_content("TEST %d" % self.record.id)
self.record.with_context(
test_break_process="OOPS! Something went wrong :("
).action_exchange_process()
storage, from_dir_str, to_dir_str, filename = self.fake_move_args
self.assertEqual(storage, self.backend.storage_id)
self.assertEqual(from_dir_str, self.backend.input_dir_pending)
self.assertEqual(to_dir_str, self.backend.input_dir_error)
self.assertEqual(filename, self.record.exchange_filename)
| 38.84507 | 2,758 |
3,182 |
py
|
PYTHON
|
15.0
|
# Copyright 2020 ACSONE
# @author: Simone Orsi <[email protected]>
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
from odoo.addons.component.core import Component
from odoo.addons.edi_oca.tests.common import EDIBackendCommonComponentRegistryTestCase
class EDIBackendTestCase(EDIBackendCommonComponentRegistryTestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls._load_module_components(cls, "edi_storage_oca")
@classmethod
def _get_backend(cls):
return cls.env.ref("edi_storage_oca.demo_edi_backend_storage")
def test_component_match(self):
"""Lookup with special match method."""
class SFTPCheck(Component):
_name = "sftp.check"
_inherit = "edi.storage.component.check"
_usage = "storage.check"
# _backend_type = "demo_backend"
_storage_backend_type = "sftp"
class SFTPSend(Component):
_name = "sftp.send"
_inherit = "edi.storage.component.send"
_usage = "storage.send"
# _backend_type = "demo_backend"
_storage_backend_type = "sftp"
class S3Check(Component):
_name = "s3.check"
_inherit = "edi.storage.component.check"
_usage = "storage.check"
# _exchange_type = "test_csv_output"
_storage_backend_type = "s3"
class S3Send(Component):
_name = "s3.send"
_inherit = "edi.storage.component.send"
_usage = "storage.send"
# _exchange_type = "test_csv_output"
_storage_backend_type = "s3"
self._build_components(SFTPCheck, SFTPSend, S3Check, S3Send)
# Record not relevant for these tests
work_ctx = {"exchange_record": self.env["edi.exchange.record"].browse()}
component = self.backend._find_component(
"res.partner",
["storage.check"],
work_ctx=work_ctx,
backend_type="demo_backend",
exchange_type="test_csv_output",
storage_backend_type="s3",
)
self.assertEqual(component._name, S3Check._name)
component = self.backend._find_component(
"res.partner",
["storage.check"],
work_ctx=work_ctx,
backend_type="demo_backend",
exchange_type="test_csv_output",
storage_backend_type="sftp",
)
self.assertEqual(component._name, SFTPCheck._name)
component = self.backend._find_component(
"res.partner",
["storage.send"],
work_ctx=work_ctx,
backend_type="demo_backend",
exchange_type="test_csv_output",
storage_backend_type="sftp",
)
self.assertEqual(component._name, SFTPSend._name)
component = self.backend._find_component(
"res.partner",
["storage.send"],
work_ctx=work_ctx,
backend_type="demo_backend",
exchange_type="test_csv_output",
storage_backend_type="s3",
)
self.assertEqual(component._name, S3Send._name)
| 34.215054 | 3,182 |
9,036 |
py
|
PYTHON
|
15.0
|
# Copyright 2020 ACSONE SA/NV (<http://acsone.eu>)
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html).
from freezegun import freeze_time
from odoo.tools import mute_logger
from .common import TestEDIStorageBase
LOGGERS = (
"odoo.addons.edi_storage_oca.components.check",
"odoo.addons.edi_oca.models.edi_backend",
)
@freeze_time("2020-10-21 10:30:00")
class TestEDIBackendOutput(TestEDIStorageBase):
@mute_logger(*LOGGERS)
def test_export_file_sent(self):
"""Send, no errors."""
self.record.edi_exchange_state = "output_pending"
mocked_paths = {self._file_fullpath("pending"): self.fakepath}
# TODO: test send only w/out cron (make sure check works)
# self._test_send(self.record, mocked_paths=mocked_paths)
self._test_run_cron(mocked_paths)
self._test_result(
self.record,
{"edi_exchange_state": "output_sent"},
expected_messages=[
{
"message": self.record._exchange_status_message("send_ok"),
"level": "info",
}
],
)
@mute_logger(*LOGGERS)
def test_export_file_already_done(self):
"""Already sent, successfully."""
self.record.edi_exchange_state = "output_sent"
mocked_paths = {self._file_fullpath("done"): self.fakepath}
# TODO: test send only w/out cron (make sure check works)
self._test_run_cron(mocked_paths)
# As we simulate to find a file in `done` folder,
# we should get the final good state
# and only one call to ftp
self._test_result(
self.record,
{"edi_exchange_state": "output_sent_and_processed"},
state_paths=("done",),
expected_messages=[
{
"message": self.record._exchange_status_message("process_ok"),
"level": "info",
}
],
)
# FIXME: ack should be handle as an incoming record (new machinery to be added)
# @mute_logger(*LOGGERS)
# def test_export_file_already_done_ack_needed_not_found(self):
# self.record.edi_exchange_state = "output_sent"
# self.record.type_id.ack_needed = True
# mocked_paths = {
# self._file_fullpath("done"): self.fakepath,
# }
# self._test_run_cron(mocked_paths)
# # No ack file found, warning message is posted
# self._test_result(
# self.record,
# {"edi_exchange_state": "output_sent_and_processed"},
# state_paths=("done",),
# expected_messages=[
# {
# "message": self.record._exchange_status_message("ack_missing"),
# "level": "warning",
# },
# {
# "message": self.record._exchange_status_message("process_ok"),
# "level": "info",
# },
# ],
# )
# @mute_logger(*LOGGERS)
# def test_export_file_already_done_ack_needed_found(self):
# self.record.edi_exchange_state = "output_sent"
# self.record.type_id.ack_needed = True
# mocked_paths = {
# self._file_fullpath("done"): self.fakepath,
# self._file_fullpath("done", ack=True): self.fakepath_ack,
# }
# self._test_run_cron(mocked_paths)
# # Found ack file, set on record
# self._test_result(
# self.record,
# {
# "edi_exchange_state": "output_sent_and_processed",
# "ack_file": base64.b64encode(b"ACK filecontent"),
# },
# state_paths=("done",),
# expected_messages=[
# {
# "message": self.record._exchange_status_message("ack_received"),
# "level": "info",
# },
# {
# "message": self.record._exchange_status_message("process_ok"),
# "level": "info",
# },
# ],
# )
@mute_logger(*LOGGERS)
def test_already_sent_process_error(self):
"""Already sent, error process."""
self.record.edi_exchange_state = "output_sent"
mocked_paths = {
self._file_fullpath("error"): self.fakepath,
self._file_fullpath("error-report"): self.fakepath_error,
}
self._test_run_cron(mocked_paths)
# As we simulate to find a file in `error` folder,
# we should get a call for: done, error and then the read of the report.
self._test_result(
self.record,
{
"edi_exchange_state": "output_sent_and_error",
"exchange_error": "ERROR XYZ: line 2 broken on bla bla",
},
state_paths=("done", "error", "error-report"),
expected_messages=[
{
"message": self.record._exchange_status_message("process_ko"),
"level": "error",
}
],
)
@mute_logger(*LOGGERS)
def test_cron_full_flow(self):
"""Already sent, update the state via cron."""
self.record.edi_exchange_state = "output_sent"
rec1 = self.record
partner2 = self.env.ref("base.res_partner_2")
partner3 = self.env.ref("base.res_partner_3")
rec2 = self.record.copy(
{
"model": partner2._name,
"res_id": partner2.id,
"exchange_filename": "rec2.csv",
}
)
rec3 = self.record.copy(
{
"model": partner3._name,
"res_id": partner3.id,
"exchange_filename": "rec3.csv",
"edi_exchange_state": "output_sent_and_error",
}
)
mocked_paths = {
self._file_fullpath("done", record=rec1): self.fakepath,
self._file_fullpath("error", record=rec2): self.fakepath,
self._file_fullpath("error-report", record=rec2): self.fakepath_error,
self._file_fullpath("done", record=rec3): self.fakepath,
}
self._test_run_cron(mocked_paths)
self._test_result(
rec1,
{"edi_exchange_state": "output_sent_and_processed"},
state_paths=("done",),
expected_messages=[
{
"message": rec1._exchange_status_message("process_ok"),
"level": "info",
}
],
)
self._test_result(
rec2,
{
"edi_exchange_state": "output_sent_and_error",
"exchange_error": "ERROR XYZ: line 2 broken on bla bla",
},
state_paths=("done", "error", "error-report"),
expected_messages=[
{
"message": rec2._exchange_status_message("process_ko"),
"level": "error",
}
],
)
self._test_result(
rec3,
{"edi_exchange_state": "output_sent_and_processed"},
state_paths=("done",),
expected_messages=[
{
"message": rec3._exchange_status_message("process_ok"),
"level": "info",
}
],
)
@mute_logger(*LOGGERS)
def test_create_input_exchange_file_from_file_received_no_pattern(self):
exch_type = self.exchange_type_in
exch_type.exchange_filename_pattern = ""
input_dir = "/test_input/pending/"
file_names = ["some-file.csv", "another-file.csv"]
self.backend.input_dir_pending = input_dir
mocked_paths = {
input_dir: "/tmp/",
self._file_fullpath(
"pending", fname=file_names[0], checker=self.checker_input
): self.fakepath_input_pending_1,
self._file_fullpath(
"pending", fname=file_names[1], checker=self.checker_input
): self.fakepath_input_pending_2,
}
existing_records = self.env["edi.exchange.record"].search(
[("backend_id", "=", self.backend.id), ("type_id", "=", exch_type.id)]
)
# Run cron action:
found_files = [input_dir + fname for fname in file_names]
with self._mock_storage_backend_find_files(found_files):
self._test_run_cron_pending_input(mocked_paths)
new_records = self.env["edi.exchange.record"].search(
[
("backend_id", "=", self.backend.id),
("type_id", "=", exch_type.id),
("id", "not in", existing_records.ids),
]
)
self.assertEqual(len(new_records), 2)
for rec in new_records:
self.assertIn(rec.exchange_filename, file_names)
self.assertEqual(rec.edi_exchange_state, "input_pending")
| 37.966387 | 9,036 |
6,607 |
py
|
PYTHON
|
15.0
|
# Copyright 2020 ACSONE SA/NV (<http://acsone.eu>)
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html).
import base64
import functools
import mock
from odoo.addons.edi_oca.tests.common import EDIBackendCommonComponentTestCase
STORAGE_BACKEND_MOCK_PATH = (
"odoo.addons.storage_backend.models.storage_backend.StorageBackend"
)
class TestEDIStorageBase(EDIBackendCommonComponentTestCase):
@classmethod
def _get_backend(cls):
return cls.env.ref("edi_storage_oca.demo_edi_backend_storage")
@classmethod
def _setup_records(cls):
super()._setup_records()
cls.filedata = base64.b64encode(b"This is a simple file")
vals = {
"model": cls.partner._name,
"res_id": cls.partner.id,
"exchange_file": cls.filedata,
}
cls.record = cls.backend.create_record("test_csv_output", vals)
cls.record_input = cls.backend.create_record("test_csv_input", vals)
cls.fakepath = "/tmp/{}".format(cls._filename(cls))
with open(cls.fakepath, "w+b") as fakefile:
fakefile.write(b"filecontent")
cls.fakepath_ack = "/tmp/{}.ack".format(cls._filename(cls))
with open(cls.fakepath_ack, "w+b") as fakefile:
fakefile.write(b"ACK filecontent")
cls.fakepath_error = "/tmp/{}.error".format(cls._filename(cls))
with open(cls.fakepath_error, "w+b") as fakefile:
fakefile.write(b"ERROR XYZ: line 2 broken on bla bla")
cls.fakepath_input_pending_1 = "/tmp/test-input-001.csv"
with open(cls.fakepath_input_pending_1, "w+b") as fakefile:
fakefile.write(b"I received this in my storage.")
cls.fakepath_input_pending_2 = "/tmp/test-input-002.csv"
with open(cls.fakepath_input_pending_2, "w+b") as fakefile:
fakefile.write(b"I received that in my storage.")
cls.checker = cls.backend._find_component(
cls.partner._name,
["storage.check"],
work_ctx={"exchange_record": cls.record},
)
cls.checker_input = cls.backend._find_component(
cls.partner._name,
["storage.check"],
work_ctx={"exchange_record": cls.record_input},
)
cls.sender = cls.backend._find_component(
cls.partner._name,
["storage.send"],
work_ctx={"exchange_record": cls.record},
)
return
def setUp(self):
super().setUp()
self._storage_backend_calls = []
def _filename(self, record=None, ack=False):
record = record or self.record
if ack:
record.type_id.ack_type_id._make_exchange_filename(record)
return record.exchange_filename
def _file_fullpath(self, state, record=None, ack=False, fname=None, checker=None):
record = record or self.record
checker = checker or self.checker
if not fname:
fname = self._filename(record, ack=ack)
if state == "error-report":
# Exception as we read from the same path but w/ error suffix
state = "error"
fname += ".error"
return checker._get_remote_file_path(state, filename=fname).as_posix()
def _mocked_backend_get(self, mocked_paths, path, **kwargs):
self._storage_backend_calls.append(path)
if mocked_paths.get(path):
with open(mocked_paths.get(path), "rb") as remote_file:
return remote_file.read()
raise FileNotFoundError()
def _mocked_backend_add(self, path, data, **kwargs):
self._storage_backend_calls.append(path)
def _mocked_backend_list_files(self, mocked_paths, path, **kwargs):
files = []
path_length = len(path)
for p in mocked_paths.keys():
if path in p and path != p:
files.append(p[path_length:])
return files
def _mock_storage_backend_get(self, mocked_paths):
mocked = functools.partial(self._mocked_backend_get, mocked_paths)
return mock.patch(STORAGE_BACKEND_MOCK_PATH + ".get", mocked)
def _mock_storage_backend_add(self):
return mock.patch(STORAGE_BACKEND_MOCK_PATH + ".add", self._mocked_backend_add)
def _mock_storage_backend_list_files(self, mocked_paths):
mocked = functools.partial(self._mocked_backend_list_files, mocked_paths)
return mock.patch(STORAGE_BACKEND_MOCK_PATH + ".list_files", mocked)
def _mock_storage_backend_find_files(self, result):
def _result(self, pattern, relative_path=None, **kw):
return result
return mock.patch(STORAGE_BACKEND_MOCK_PATH + ".find_files", _result)
def _test_result(
self,
record,
expected_values,
expected_messages=None,
state_paths=None,
):
state_paths = state_paths or ("done", "pending", "error")
# Paths will be something like:
# [
# 'demo_out/pending/$filename.csv',
# 'demo_out/pending/$filename.csv',
# 'demo_out/error/$filename.csv',
# ]
for state in state_paths:
path = self._file_fullpath(state, record=record)
self.assertIn(path, self._storage_backend_calls)
self.assertRecordValues(record, [expected_values])
if expected_messages:
# consider only edi related messages
messages = record.record.message_ids.filtered(
lambda x: "edi-exchange" in x.body
)
self.assertEqual(len(messages), len(expected_messages))
for msg_rec, expected in zip(messages, expected_messages):
self.assertIn(expected["message"], msg_rec.body)
self.assertIn("level-" + expected["level"], msg_rec.body)
# TODO: test content of file sent
def _test_send(self, record, mocked_paths=None):
with self._mock_storage_backend_add():
if mocked_paths:
with self._mock_storage_backend_get(mocked_paths):
self.backend.exchange_send(record)
else:
self.backend.exchange_send(record)
def _test_run_cron(self, mocked_paths):
with self._mock_storage_backend_add():
with self._mock_storage_backend_get(mocked_paths):
self.backend._cron_check_output_exchange_sync()
def _test_run_cron_pending_input(self, mocked_paths):
with self._mock_storage_backend_add():
with self._mock_storage_backend_list_files(mocked_paths):
self.backend._storage_cron_check_pending_input()
| 38.864706 | 6,607 |
1,927 |
py
|
PYTHON
|
15.0
|
# Copyright 2020 ACSONE
# @author: Simone Orsi <[email protected]>
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
import mock
from .common import STORAGE_BACKEND_MOCK_PATH, TestEDIStorageBase
class EDIStorageComponentTestCase(TestEDIStorageBase):
def test_remote_file_path(self):
to_test = (
(("input", "pending", "foo.csv"), "demo_in/pending/foo.csv"),
(("input", "done", "foo.csv"), "demo_in/done/foo.csv"),
(("input", "error", "foo.csv"), "demo_in/error/foo.csv"),
(("output", "pending", "foo.csv"), "demo_out/pending/foo.csv"),
(("output", "done", "foo.csv"), "demo_out/done/foo.csv"),
(("output", "error", "foo.csv"), "demo_out/error/foo.csv"),
)
for _args, expected in to_test:
direction, state, filename = _args
if direction == "input":
checker = self.checker_input
else:
checker = self.checker
path_obj = checker._get_remote_file_path(state, filename)
self.assertEqual(path_obj.as_posix(), expected)
with self.assertRaises(AssertionError):
self.checker_input._get_remote_file_path("WHATEVER", "foo.csv")
def test_get_remote_file(self):
with mock.patch(STORAGE_BACKEND_MOCK_PATH + ".get") as mocked:
self.checker._get_remote_file("pending")
mocked.assert_called_with(
"demo_out/pending/{}".format(self._filename(self.record)), binary=False
)
self.checker._get_remote_file("done")
mocked.assert_called_with(
"demo_out/done/{}".format(self._filename(self.record)), binary=False
)
self.checker._get_remote_file("error")
mocked.assert_called_with(
"demo_out/error/{}".format(self._filename(self.record)), binary=False
)
| 42.822222 | 1,927 |
2,539 |
py
|
PYTHON
|
15.0
|
# Copyright 2022 Camptocamp SA (https://www.camptocamp.com).
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
from odoo.addons.edi_oca.tests.common import EDIBackendCommonTestCase
class EDIExchangeTypeTestCase(EDIBackendCommonTestCase):
def _check_test_storage_fullpath(self, wanted_fullpath, directory, filename):
fullpath = self.exchange_type_out._storage_fullpath(directory, filename)
self.assertEqual(fullpath.as_posix(), wanted_fullpath)
def _do_test_storage_fullpath(self, prefix=""):
# Test with no directory and no filename
wanted_fullpath = prefix or "."
self._check_test_storage_fullpath(wanted_fullpath, None, None)
# Test with directory
directory = "test_directory"
wanted_fullpath = f"{prefix}/{directory}" if prefix else directory
self._check_test_storage_fullpath(wanted_fullpath, directory, None)
# Test with filename
filename = "test_filename.csv"
wanted_fullpath = f"{prefix}/{filename}" if prefix else filename
self._check_test_storage_fullpath(wanted_fullpath, None, filename)
# Test with directory and filename
wanted_fullpath = (
f"{prefix}/{directory}/{filename}" if prefix else f"{directory}/{filename}"
)
self._check_test_storage_fullpath(wanted_fullpath, directory, filename)
def test_storage_fullpath(self):
"""
Test storage fullpath defined into advanced settings.
Example of pattern:
storage:
# simple string
path: path/to/file
# name of the param containing the path
path_config_param: path/to/file
"""
# Test without any prefix
self._do_test_storage_fullpath()
# Force path on advanced settings
prefix = "prefix/path"
self.exchange_type_out.advanced_settings_edit = f"""
storage:
path: {prefix}
"""
self._do_test_storage_fullpath(prefix=prefix)
# Force path on advanced settings using config param, but not defined
self.exchange_type_out.advanced_settings_edit = """
storage:
path_config_param: prefix_path_config_param
"""
self._do_test_storage_fullpath()
# Define config param
prefix = "prefix/path/by/config/param"
self.env["ir.config_parameter"].sudo().set_param(
"prefix_path_config_param", prefix
)
self._do_test_storage_fullpath(prefix=prefix)
| 37.895522 | 2,539 |
6,427 |
py
|
PYTHON
|
15.0
|
# Copyright 2020 ACSONE SA
# @author Simone Orsi <[email protected]>
# Copyright 2021 ForgeFlow S.L. (https://www.forgeflow.com)
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
import logging
import os
from odoo import fields, models
_logger = logging.getLogger(__name__)
class EDIBackend(models.Model):
_inherit = "edi.backend"
storage_id = fields.Many2one(
string="Storage backend",
comodel_name="storage.backend",
help="Storage for in-out files",
ondelete="restrict",
)
"""
We assume the exchanges happen it 2 ways (input, output)
and we have a hierarchy of directory like:
from_A_to_B
|- pending
|- done
|- error
from_B_to_A
|- pending
|- done
|- error
where A and B are the partners exchanging data and they are in turn
sender and receiver and vice versa.
"""
# TODO: these paths should probably be by type instead
# Here we can maybe set a common root folder for this exchange.
input_dir_pending = fields.Char(
"Input pending directory", help="Path to folder for pending operations"
)
input_dir_done = fields.Char(
"Input done directory", help="Path to folder for doneful operations"
)
input_dir_error = fields.Char(
"Input error directory", help="Path to folder for error operations"
)
output_dir_pending = fields.Char(
"Output pending directory", help="Path to folder for pending operations"
)
output_dir_done = fields.Char(
"Output done directory", help="Path to folder for doneful operations"
)
output_dir_error = fields.Char(
"Output error directory", help="Path to folder for error operations"
)
_storage_actions = ("check", "send", "receive")
def _get_component_usage_candidates(self, exchange_record, key):
candidates = super()._get_component_usage_candidates(exchange_record, key)
if not self.storage_id or key not in self._storage_actions:
return candidates
return ["storage.{}".format(key)] + candidates
def _component_match_attrs(self, exchange_record, key):
# Override to inject storage_backend_type
res = super()._component_match_attrs(exchange_record, key)
if not self.storage_id or key not in self._storage_actions:
return res
res["storage_backend_type"] = self.storage_id.backend_type
return res
def _component_sort_key(self, component_class):
res = super()._component_sort_key(component_class)
# Override to give precedence by storage_backend_type when needed.
if not self.storage_id:
return res
return (
1 if getattr(component_class, "_storage_backend_type", False) else 0,
) + res
def _storage_cron_check_pending_input(self, **kw):
for backend in self:
backend._storage_check_pending_input(**kw)
def _storage_check_pending_input(self, **kw):
"""Create new exchange records if new files found.
Collect input exchange types and for each of them,
check by pattern if the a new exchange record is required.
"""
self.ensure_one()
if not self.storage_id or not self.input_dir_pending:
_logger.info(
"%s ignored: no storage and/or input directory specified.", self.name
)
return False
exchange_types = self.env["edi.exchange.type"].search(
self._storage_exchange_type_pending_input_domain()
)
for exchange_type in exchange_types:
# NOTE: this call might keep hanging the cron
# if the remote storage is slow (eg: too many files)
# We should probably run this code in a separate job per exchange type.
file_names = self._storage_get_input_filenames(exchange_type)
_logger.info(
"Processing exchange type '%s': found %s files to process",
exchange_type.display_name,
len(file_names),
)
for file_name in file_names:
self.with_delay()._storage_create_record_if_missing(
exchange_type, file_name
)
return True
def _storage_exchange_type_pending_input_domain(self):
"""Domain for retrieving input exchange types."""
return [
("backend_type_id", "=", self.backend_type_id.id),
("direction", "=", "input"),
"|",
("backend_id", "=", False),
("backend_id", "=", self.id),
]
def _storage_create_record_if_missing(self, exchange_type, remote_file_name):
"""Create a new exchange record for given type and file name if missing."""
file_name = os.path.basename(remote_file_name)
extra_domain = [("exchange_filename", "=", file_name)]
existing = self._find_existing_exchange_records(
exchange_type, extra_domain=extra_domain, count_only=True
)
if existing:
return
record = self.create_record(
exchange_type.code, self._storage_new_exchange_record_vals(file_name)
)
_logger.debug("%s: new exchange record generated.", self.name)
return record.identifier
def _storage_get_input_filenames(self, exchange_type):
full_input_dir_pending = exchange_type._storage_fullpath(
self.input_dir_pending
).as_posix()
if not exchange_type.exchange_filename_pattern:
# If there is not pattern, return everything
filenames = [
x
for x in self.storage_id.list_files(full_input_dir_pending)
if x.strip("/")
]
return filenames
bits = [exchange_type.exchange_filename_pattern]
if exchange_type.exchange_file_ext:
bits.append(r"\." + exchange_type.exchange_file_ext)
pattern = "".join(bits)
full_paths = self.storage_id.find_files(pattern, full_input_dir_pending)
pending_path_len = len(full_input_dir_pending)
return [p[pending_path_len:].strip("/") for p in full_paths]
def _storage_new_exchange_record_vals(self, file_name):
return {"exchange_filename": file_name, "edi_exchange_state": "input_pending"}
| 38.029586 | 6,427 |
2,171 |
py
|
PYTHON
|
15.0
|
# Copyright 2021 ForgeFlow S.L. (https://www.forgeflow.com)
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
from pathlib import PurePath
from odoo import fields, models
class EDIExchangeType(models.Model):
_inherit = "edi.exchange.type"
# Extend help to explain new usage.
exchange_filename_pattern = fields.Char(
help="For output exchange types this should be a formatting string "
"with the following variables available (to be used between "
"brackets, `{}`): `exchange_record`, `record_name`, `type` and "
"`dt`. For instance, a valid string would be "
"{record_name}-{type.code}-{dt}\n"
"For input exchange types related to storage backends "
"it should be a regex expression to filter "
"the files to be fetched from the pending directory in the related "
"storage. E.g: `.*my-type-[0-9]*.\\.csv`"
)
def _storage_path(self):
"""Retrieve specific path for current exchange type.
In your exchange type you can pass this config:
storage:
# simple string
path: path/to/file
Or
storage:
# name of the param containing the path
path_config_param: path/to/file
Thanks to the param you could even configure it by env.
"""
self.ensure_one()
storage_settings = self.advanced_settings.get("storage", {})
path = storage_settings.get("path")
if path:
return PurePath(path)
path_config_param = storage_settings.get("path_config_param")
if path_config_param:
icp = self.env["ir.config_parameter"].sudo()
path = icp.get_param(path_config_param)
if path:
return PurePath(path)
def _storage_fullpath(self, directory=None, filename=None):
self.ensure_one()
path_prefix = self._storage_path()
path = PurePath((directory or "").strip().rstrip("/"))
if path_prefix:
path = path_prefix / path
if filename:
path = path / filename.strip("/")
return path
| 35.016129 | 2,171 |
3,198 |
py
|
PYTHON
|
15.0
|
# Copyright 2020 ACSONE
# @author: Simone Orsi <[email protected]>
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
import logging
from odoo.tools import pycompat
from odoo.addons.component.core import Component
_logger = logging.getLogger(__name__)
class EDIStorageCheckComponentMixin(Component):
_name = "edi.storage.component.check"
_inherit = [
"edi.component.check.mixin",
"edi.storage.component.mixin",
]
_usage = "storage.check"
def check(self):
return self._exchange_output_check()
def _exchange_output_check(self):
"""Check status output exchange and update record.
1. check if the file has been processed already (done)
2. if yes, post message and exit
3. if not, check for errors
4. if no errors, return
:return: boolean
* False if there's nothing else to be done
* True if file still need action
"""
if self._get_remote_file("done"):
_logger.info(
"%s done",
self.exchange_record.identifier,
)
if (
not self.exchange_record.edi_exchange_state
== "output_sent_and_processed"
):
self.exchange_record.edi_exchange_state = "output_sent_and_processed"
self.exchange_record._notify_done()
return False
error = self._get_remote_file("error")
if error:
_logger.info(
"%s error",
self.exchange_record.identifier,
)
# Assume a text file will be placed there w/ the same name and error suffix
err_filename = self.exchange_record.exchange_filename + ".error"
error_report = (
self._get_remote_file("error", filename=err_filename) or "no-report"
)
if self.exchange_record.edi_exchange_state == "output_sent":
self.exchange_record.update(
{
"edi_exchange_state": "output_sent_and_error",
"exchange_error": pycompat.to_text(error_report),
}
)
self.exchange_record._notify_error("process_ko")
return False
return True
# FIXME: this is not used ATM -> should be refactored
# into an incoming exchange.
# The backend will look for records needing an ack
# and generate and ack record.
def _exchange_output_handle_ack(self):
ack_type = self.exchange_record.type_id.ack_type_id
filename = ack_type._make_exchange_filename(self.exchange_record)
ack_file = self._get_remote_file("done", filename=filename)
if ack_file:
self.backend.create_record(
ack_type.code,
{
"parent_id": self.exchange_record.id,
"exchange_file": ack_file,
"edi_exchange_state": "input_received",
},
)
self.exchange_record._notify_ack_received()
else:
self.exchange_record._notify_ack_missing()
| 34.76087 | 3,198 |
552 |
py
|
PYTHON
|
15.0
|
# Copyright 2021 ForgeFlow S.L. (https://www.forgeflow.com)
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
from odoo.addons.component.core import Component
class EDIStorageReceiveComponent(Component):
_name = "edi.storage.component.receive"
_inherit = [
"edi.component.receive.mixin",
"edi.storage.component.mixin",
]
_usage = "storage.receive"
def receive(self):
path = self._get_remote_file_path("pending")
filedata = self.storage.get(path.as_posix())
return filedata
| 29.052632 | 552 |
1,315 |
py
|
PYTHON
|
15.0
|
# Copyright 2020 ACSONE
# @author: Simone Orsi <[email protected]>
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
from odoo.addons.component.core import Component
class EDIStorageSendComponent(Component):
_name = "edi.storage.component.send"
_inherit = [
"edi.component.send.mixin",
"edi.storage.component.mixin",
]
_usage = "storage.send"
def send(self):
# If the file has been sent already, refresh its state
# TODO: double check if this is useless
# since the backend checks the state already
checker = self.component(usage="storage.check")
result = checker.check()
if not result:
# all good here
return True
filedata = self.exchange_record.exchange_file
path = self._get_remote_file_path("pending")
self.storage.add(path.as_posix(), filedata, binary=False)
# TODO: delegate this to generic storage backend
# except paramiko.ssh_exception.AuthenticationException:
# # TODO this exc handling should be moved to sftp backend IMO
# error = _("Authentication error")
# state = "error_on_send"
# TODO: catch other specific exceptions
# this will swallow all the exceptions!
return True
| 36.527778 | 1,315 |
3,809 |
py
|
PYTHON
|
15.0
|
# Copyright 2020 ACSONE
# Copyright 2022 Camptocamp
# @author: Simone Orsi <[email protected]>
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
import logging
from pathlib import PurePath
from odoo.addons.component.core import AbstractComponent
_logger = logging.getLogger(__file__)
class EDIStorageComponentMixin(AbstractComponent):
_name = "edi.storage.component.mixin"
_inherit = "edi.component.mixin"
# Components having `_storage_backend_type` will have precedence.
# If the value is not set, generic components will be used.
_storage_backend_type = None
@classmethod
def _component_match(cls, work, usage=None, model_name=None, **kw):
res = super()._component_match(work, usage=usage, model_name=model_name, **kw)
storage_type = kw.get("storage_backend_type")
if storage_type and cls._storage_backend_type:
return cls._storage_backend_type == storage_type
return res
@property
def storage(self):
return self.backend.storage_id
def _dir_by_state(self, direction, state):
"""Return remote directory path by direction and state.
:param direction: string stating direction of the exchange
:param state: string stating state of the exchange
:return: PurePath object
"""
assert direction in ("input", "output")
assert state in ("pending", "done", "error")
return PurePath(
(self.backend[direction + "_dir_" + state] or "").strip().rstrip("/")
)
def _remote_file_path(self, direction, state, filename):
"""Return remote file path by direction and state for give filename.
:param direction: string stating direction of the exchange
:param state: string stating state of the exchange
:param filename: string for file name
:return: PurePath object
"""
_logger.warning(
"Call of deprecated function `_remote_file_path`. "
"Please use `_get_remote_file_path` instead.",
)
return self._dir_by_state(direction, state) / filename.strip("/ ")
def _get_remote_file_path(self, state, filename=None):
"""Retrieve remote path for current exchange record."""
filename = filename or self.exchange_record.exchange_filename
direction = self.exchange_record.direction
directory = self._dir_by_state(direction, state).as_posix()
path = self.exchange_record.type_id._storage_fullpath(
directory=directory, filename=filename
)
return path
def _get_remote_file(self, state, filename=None, binary=False):
"""Get file for current exchange_record in the given destination state.
:param state: string ("pending", "done", "error")
:param filename: custom file name, exchange_record filename used by default
:return: remote file content as string
"""
path = self._get_remote_file_path(state, filename=filename)
try:
# TODO: support match via pattern (eg: filename-prefix-*)
# otherwise is impossible to retrieve input files and acks
# (the date will never match)
return self.storage.get(path.as_posix(), binary=binary)
except FileNotFoundError:
_logger.info(
"Ignored FileNotFoundError when trying "
"to get file %s into path %s for state %s",
filename,
path,
state,
)
return None
except OSError:
_logger.info(
"Ignored OSError when trying to get file %s into path %s for state %s",
filename,
path,
state,
)
return None
| 38.474747 | 3,809 |
2,792 |
py
|
PYTHON
|
15.0
|
# Copyright 2021 ForgeFlow S.L. (https://www.forgeflow.com)
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
import functools
from pathlib import PurePath
from odoo.addons.component.core import Component
class EdiStorageListener(Component):
_name = "edi.storage.component.listener"
_inherit = "base.event.listener"
def _move_file(self, storage, from_dir_str, to_dir_str, filename):
from_dir = PurePath(from_dir_str)
to_dir = PurePath(to_dir_str)
if filename not in storage.list_files(from_dir.as_posix()):
# The file might have been moved after a previous error.
return False
self._add_after_commit_hook(
storage._move_files, [(from_dir / filename).as_posix()], to_dir.as_posix()
)
return True
def _add_after_commit_hook(self, move_func, sftp_filepath, sftp_destination_path):
"""Add hook after commit to move the file when transaction is over."""
self.env.cr.after(
"commit",
functools.partial(move_func, sftp_filepath, sftp_destination_path),
)
def on_edi_exchange_done(self, record):
storage = record.backend_id.storage_id
res = False
if record.direction == "input" and storage:
file = record.exchange_filename
pending_dir = record.type_id._storage_fullpath(
record.backend_id.input_dir_pending
).as_posix()
done_dir = record.type_id._storage_fullpath(
record.backend_id.input_dir_done
).as_posix()
error_dir = record.type_id._storage_fullpath(
record.backend_id.input_dir_error
).as_posix()
if not done_dir:
return res
res = self._move_file(storage, pending_dir, done_dir, file)
if not res:
# If a file previously failed it should have been previously
# moved to the error dir, therefore it is not present in the
# pending dir and we need to retry from error dir.
res = self._move_file(storage, error_dir, done_dir, file)
return res
def on_edi_exchange_error(self, record):
storage = record.backend_id.storage_id
res = False
if record.direction == "input" and storage:
file = record.exchange_filename
pending_dir = record.type_id._storage_fullpath(
record.backend_id.input_dir_pending
).as_posix()
error_dir = record.type_id._storage_fullpath(
record.backend_id.input_dir_error
).as_posix()
if error_dir:
res = self._move_file(storage, pending_dir, error_dir, file)
return res
| 40.463768 | 2,792 |
993 |
py
|
PYTHON
|
15.0
|
# Copyright 2020 Tecnativa - Manuel Calero
# Copyright 2022 Quartile
# Copyright 2014-2022 Tecnativa - Pedro M. Baeza
{
"name": "Commissions",
"version": "15.0.2.1.0",
"author": "Tecnativa, Odoo Community Association (OCA)",
"category": "Invoicing",
"license": "AGPL-3",
"depends": ["product"],
"website": "https://github.com/OCA/commission",
"maintainers": ["pedrobaeza"],
"data": [
"security/commission_security.xml",
"security/ir.model.access.csv",
"data/menuitem_data.xml",
"views/commission_views.xml",
"views/commission_settlement_views.xml",
"views/commission_mixin_views.xml",
"views/product_template_views.xml",
"views/res_partner_views.xml",
"reports/commission_settlement_report.xml",
"reports/report_settlement_templates.xml",
"wizards/commission_make_settle_views.xml",
],
"demo": ["demo/commission_and_agent_demo.xml"],
"installable": True,
}
| 35.464286 | 993 |
6,122 |
py
|
PYTHON
|
15.0
|
# Copyright 2020 Tecnativa - Manuel Calero
# Copyright 2022 Quartile
# Copyright 2016-2022 Tecnativa - Pedro M. Baeza
# License AGPL-3 - See https://www.gnu.org/licenses/agpl-3.0.html
from dateutil.relativedelta import relativedelta
from odoo import fields
from odoo.exceptions import ValidationError
from odoo.tests.common import TransactionCase
class TestCommissionBase(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.commission_model = cls.env["commission"]
cls.commission_net_paid = cls.commission_model.create(
{
"name": "20% fixed commission (Net amount) - Payment Based",
"fix_qty": 20.0,
"amount_base_type": "net_amount",
}
)
cls.commission_section_paid = cls.commission_model.create(
{
"name": "Section commission - Payment Based",
"commission_type": "section",
"section_ids": [
(0, 0, {"amount_from": 1.0, "amount_to": 100.0, "percent": 10.0})
],
"amount_base_type": "net_amount",
}
)
cls.commission_section_invoice = cls.commission_model.create(
{
"name": "Section commission - Invoice Based",
"commission_type": "section",
"section_ids": [
(
0,
0,
{
"amount_from": 15000.0,
"amount_to": 16000.0,
"percent": 20.0,
},
)
],
}
)
cls.company = cls.env.ref("base.main_company")
cls.res_partner_model = cls.env["res.partner"]
cls.partner = cls.env.ref("base.res_partner_2")
cls.partner.write({"agent": False})
cls.settle_model = cls.env["commission.settlement"]
cls.make_settle_model = cls.env["commission.make.settle"]
cls.commission_product = cls.env["product.product"].create(
{"name": "Commission test product", "type": "service"}
)
cls.agent_monthly = cls.res_partner_model.create(
{
"name": "Test Agent - Monthly",
"agent": True,
"settlement": "monthly",
"lang": "en_US",
"commission_id": cls.commission_net_paid.id,
}
)
cls.agent_quaterly = cls.res_partner_model.create(
{
"name": "Test Agent - Quaterly",
"agent": True,
"settlement": "quaterly",
"lang": "en_US",
"commission_id": cls.commission_section_invoice.id,
}
)
cls.agent_semi = cls.res_partner_model.create(
{
"name": "Test Agent - Semi-annual",
"agent": True,
"settlement": "semi",
"lang": "en_US",
}
)
cls.agent_annual = cls.res_partner_model.create(
{
"name": "Test Agent - Annual",
"agent": True,
"settlement": "annual",
"lang": "en_US",
}
)
# Expected to be used in inheriting modules.
def _get_make_settle_vals(self, agent=None, period=None, date=None):
vals = {
"date_to": (
fields.Datetime.from_string(fields.Datetime.now())
+ relativedelta(months=period)
)
if period
else date,
}
if agent:
vals["agent_ids"] = [(4, agent.id)]
return vals
# Expected to be used in inheriting modules.
def _check_propagation(self, agent, commission_type, agent_partner):
self.assertTrue(agent)
self.assertTrue(agent.commission_id, commission_type)
self.assertTrue(agent.agent_id, agent_partner)
def _create_settlement(self, agent, commission):
sett_from = self.make_settle_model._get_period_start(agent, fields.Date.today())
sett_to = self.make_settle_model._get_next_period_date(agent, sett_from)
return self.settle_model.create(
{
"agent_id": agent.id,
"date_from": sett_from,
"date_to": sett_to,
"company_id": self.company.id,
"line_ids": [
(
0,
0,
{
"date": fields.Date.today(),
"agent_id": agent.id,
"commission_id": commission.id,
"settled_amount": 100.0,
"currency_id": self.company.currency_id.id,
},
)
],
}
)
class TestCommission(TestCommissionBase):
def test_wrong_section(self):
with self.assertRaises(ValidationError):
self.commission_model.create(
{
"name": "Section commission - Invoice Based",
"commission_type": "section",
"section_ids": [
(0, 0, {"amount_from": 5, "amount_to": 1, "percent": 20.0})
],
}
)
def test_res_partner_agent_propagation(self):
partner = self.env["res.partner"].create(
{
"name": "Test partner",
"agent_ids": [(4, self.agent_monthly.id), (4, self.agent_quaterly.id)],
}
)
# Create
child = self.env["res.partner"].create(
{"name": "Test child", "parent_id": partner.id}
)
self.assertEqual(set(child.agent_ids.ids), set(partner.agent_ids.ids))
# Write
partner.agent_ids = [(4, self.agent_annual.id)]
self.assertEqual(set(child.agent_ids.ids), set(partner.agent_ids.ids))
| 36.224852 | 6,122 |
2,153 |
py
|
PYTHON
|
15.0
|
# Copyright 2016-2022 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import _, api, exceptions, fields, models
class Commission(models.Model):
_name = "commission"
_description = "Commission"
name = fields.Char(required=True)
commission_type = fields.Selection(
selection=[("fixed", "Fixed percentage"), ("section", "By sections")],
string="Type",
required=True,
default="fixed",
)
fix_qty = fields.Float(string="Fixed percentage")
section_ids = fields.One2many(
string="Sections",
comodel_name="commission.section",
inverse_name="commission_id",
)
active = fields.Boolean(default=True)
amount_base_type = fields.Selection(
selection=[("gross_amount", "Gross Amount"), ("net_amount", "Net Amount")],
string="Base",
required=True,
default="gross_amount",
)
settlement_type = fields.Selection(selection="_selection_settlement_type")
@api.model
def _selection_settlement_type(self):
"""Return the same types as the settlements."""
return self.env["commission.settlement"].fields_get(
allfields=["settlement_type"]
)["settlement_type"]["selection"]
def calculate_section(self, base):
self.ensure_one()
for section in self.section_ids:
if section.amount_from <= base <= section.amount_to:
return base * section.percent / 100.0
return 0.0
class CommissionSection(models.Model):
_name = "commission.section"
_description = "Commission section"
commission_id = fields.Many2one("commission", string="Commission")
amount_from = fields.Float(string="From")
amount_to = fields.Float(string="To")
percent = fields.Float(required=True)
@api.constrains("amount_from", "amount_to")
def _check_amounts(self):
for section in self:
if section.amount_to < section.amount_from:
raise exceptions.ValidationError(
_("The lower limit cannot be greater than upper one.")
)
| 34.174603 | 2,153 |
5,504 |
py
|
PYTHON
|
15.0
|
# Copyright 2018-2022 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import _, api, fields, models
class CommissionMixin(models.AbstractModel):
_name = "commission.mixin"
_description = (
"Mixin model for applying to any object that wants to handle commissions"
)
agent_ids = fields.One2many(
comodel_name="commission.line.mixin",
inverse_name="object_id",
string="Agents & commissions",
help="Agents/Commissions related to the invoice line.",
compute="_compute_agent_ids",
readonly=False,
store=True,
copy=True,
)
product_id = fields.Many2one(comodel_name="product.product", string="Product")
commission_free = fields.Boolean(
string="Comm. free",
related="product_id.commission_free",
store=True,
readonly=True,
)
commission_status = fields.Char(
compute="_compute_commission_status",
string="Commission",
)
def _prepare_agent_vals(self, agent):
return {"agent_id": agent.id, "commission_id": agent.commission_id.id}
def _prepare_agents_vals_partner(self, partner, settlement_type=None):
"""Utility method for getting agents creation dictionary of a partner."""
agents = partner.agent_ids
if settlement_type:
agents = agents.filtered(
lambda x: not x.commission_id.settlement_type
or x.commission_id.settlement_type == settlement_type
)
return [(0, 0, self._prepare_agent_vals(agent)) for agent in agents]
@api.depends("commission_free")
def _compute_agent_ids(self):
"""Empty method that needs to be implemented in children models."""
raise NotImplementedError()
@api.depends("commission_free", "agent_ids")
def _compute_commission_status(self):
for line in self:
if line.commission_free:
line.commission_status = _("Comm. free")
elif len(line.agent_ids) == 0:
line.commission_status = _("No commission agents")
elif len(line.agent_ids) == 1:
line.commission_status = _("1 commission agent")
else:
line.commission_status = _("%s commission agents") % (
len(line.agent_ids),
)
def recompute_agents(self):
self._compute_agent_ids()
def button_edit_agents(self):
self.ensure_one()
view = self.env.ref("commission.view_commission_mixin_agent_only")
return {
"name": _("Agents"),
"type": "ir.actions.act_window",
"view_type": "form",
"view_mode": "form",
"res_model": self._name,
"views": [(view.id, "form")],
"view_id": view.id,
"target": "new",
"res_id": self.id,
"context": self.env.context,
}
class CommissionLineMixin(models.AbstractModel):
_name = "commission.line.mixin"
_description = (
"Mixin model for having commission agent lines in "
"any object inheriting from this one"
)
_rec_name = "agent_id"
_sql_constraints = [
(
"unique_agent",
"UNIQUE(object_id, agent_id)",
"You can only add one time each agent.",
)
]
object_id = fields.Many2one(
comodel_name="commission.mixin",
ondelete="cascade",
required=True,
copy=False,
string="Parent",
)
agent_id = fields.Many2one(
comodel_name="res.partner",
domain="[('agent', '=', True)]",
ondelete="restrict",
required=True,
)
commission_id = fields.Many2one(
comodel_name="commission",
ondelete="restrict",
required=True,
compute="_compute_commission_id",
store=True,
readonly=False,
copy=True,
)
amount = fields.Monetary(
string="Commission Amount",
compute="_compute_amount",
store=True,
)
# Fields to be overriden with proper source (via related or computed field)
currency_id = fields.Many2one(comodel_name="res.currency")
def _compute_amount(self):
"""Compute method to be implemented by inherited models."""
raise NotImplementedError()
def _get_commission_amount(self, commission, subtotal, product, quantity):
"""Get the commission amount for the data given. It's called by
compute methods of children models.
This means the inheritable method for modifying the amount of the commission.
"""
self.ensure_one()
if product.commission_free or not commission:
return 0.0
if commission.amount_base_type == "net_amount":
# If subtotal (sale_price * quantity) is less than
# standard_price * quantity, it means that we are selling at
# lower price than we bought, so set amount_base to 0
subtotal = max([0, subtotal - product.standard_price * quantity])
if commission.commission_type == "fixed":
return subtotal * (commission.fix_qty / 100.0)
elif commission.commission_type == "section":
return commission.calculate_section(subtotal)
@api.depends("agent_id")
def _compute_commission_id(self):
for record in self:
record.commission_id = record.agent_id.commission_id
| 34.616352 | 5,504 |
253 |
py
|
PYTHON
|
15.0
|
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ProductTemplate(models.Model):
_inherit = "product.template"
commission_free = fields.Boolean(string="Free of commission", default=False)
| 28.111111 | 253 |
4,186 |
py
|
PYTHON
|
15.0
|
# Copyright 2020 Tecnativa - Manuel Calero
# Copyright 2022 Quartile
# Copyright 2014-2022 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
class CommissionSettlement(models.Model):
_name = "commission.settlement"
_description = "Settlement"
name = fields.Char()
total = fields.Float(compute="_compute_total", readonly=True, store=True)
date_from = fields.Date(string="From", required=True)
date_to = fields.Date(string="To", required=True)
agent_id = fields.Many2one(
comodel_name="res.partner",
domain="[('agent', '=', True)]",
required=True,
)
agent_type = fields.Selection(related="agent_id.agent_type")
settlement_type = fields.Selection(
selection=[("manual", "Manual")],
default="manual",
readonly=True,
required=True,
help="The source of the settlement, e.g. 'Sales invoice', 'Sales order', "
"'Purchase order'...",
)
can_edit = fields.Boolean(
compute="_compute_can_edit",
help="Technical field for determining if user can edit settlements",
store=True,
)
line_ids = fields.One2many(
comodel_name="commission.settlement.line",
inverse_name="settlement_id",
string="Settlement lines",
)
state = fields.Selection(
selection=[
("settled", "Settled"),
("cancel", "Canceled"),
],
readonly=True,
required=True,
default="settled",
)
currency_id = fields.Many2one(
comodel_name="res.currency",
readonly=True,
default=lambda self: self._default_currency_id(),
required=True,
)
company_id = fields.Many2one(
comodel_name="res.company",
default=lambda self: self._default_company_id(),
required=True,
)
def _default_currency_id(self):
return self.env.company.currency_id.id
def _default_company_id(self):
return self.env.company.id
@api.depends("line_ids", "line_ids.settled_amount")
def _compute_total(self):
for record in self:
record.total = sum(record.mapped("line_ids.settled_amount"))
@api.depends("settlement_type")
def _compute_can_edit(self):
for record in self:
record.can_edit = record.settlement_type == "manual"
def action_cancel(self):
self.write({"state": "cancel"})
class SettlementLine(models.Model):
_name = "commission.settlement.line"
_description = "Line of a commission settlement"
settlement_id = fields.Many2one(
"commission.settlement",
readonly=True,
ondelete="cascade",
required=True,
)
date = fields.Date(
compute="_compute_date",
readonly=False,
store=True,
required=True,
)
agent_id = fields.Many2one(
comodel_name="res.partner",
related="settlement_id.agent_id",
store=True,
)
settled_amount = fields.Monetary(
compute="_compute_settled_amount", readonly=False, store=True
)
currency_id = fields.Many2one(
related="settlement_id.currency_id",
comodel_name="res.currency",
store=True,
readonly=True,
)
commission_id = fields.Many2one(
comodel_name="commission",
compute="_compute_commission_id",
readonly=False,
store=True,
required=True,
)
company_id = fields.Many2one(
comodel_name="res.company",
related="settlement_id.company_id",
store=True,
)
def _compute_date(self):
"""Empty hook for allowing in children modules to auto-compute this field
depending on the settlement line source.
"""
def _compute_commission_id(self):
"""Empty hook for allowing in children modules to auto-compute this field
depending on the settlement line source.
"""
def _compute_settled_amount(self):
"""Empty container for allowing in children modules to auto-compute this
amount depending on the settlement line source.
"""
| 30.115108 | 4,186 |
1,871 |
py
|
PYTHON
|
15.0
|
# Copyright 2018 Tecnativa - Ernesto Tejeda
# Copyright 2016-2022 Tecnativa - Pedro M. Baeza
# License AGPL-3 - See https://www.gnu.org/licenses/agpl-3.0.html
from odoo import api, fields, models
class ResPartner(models.Model):
"""Add some fields related to commissions"""
_inherit = "res.partner"
agent_ids = fields.Many2many(
comodel_name="res.partner",
relation="partner_agent_rel",
column1="partner_id",
column2="agent_id",
domain=[("agent", "=", True)],
readonly=False,
string="Agents",
)
# Fields for the partner when it acts as an agent
agent = fields.Boolean(
string="Creditor/Agent",
help="Check this field if the partner is a creditor or an agent.",
)
agent_type = fields.Selection(
selection=[("agent", "External agent")],
string="Type",
default="agent",
)
commission_id = fields.Many2one(
string="Commission",
comodel_name="commission",
help="This is the default commission used in the sales where this "
"agent is assigned. It can be changed on each operation if "
"needed.",
)
settlement = fields.Selection(
selection=[
("biweekly", "Bi-weekly"),
("monthly", "Monthly"),
("quaterly", "Quarterly"),
("semi", "Semi-annual"),
("annual", "Annual"),
],
string="Settlement period",
default="monthly",
)
settlement_ids = fields.One2many(
comodel_name="commission.settlement",
inverse_name="agent_id",
readonly=True,
)
@api.model
def _commercial_fields(self):
"""Add agents to commercial fields that are synced from parent to childs."""
res = super()._commercial_fields()
res.append("agent_ids")
return res
| 30.672131 | 1,871 |
6,461 |
py
|
PYTHON
|
15.0
|
# Copyright 2022 Quartile
# Copyright 2014-2022 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from datetime import date, timedelta
from dateutil.relativedelta import relativedelta
from odoo import _, api, fields, models
class CommissionMakeSettle(models.TransientModel):
_name = "commission.make.settle"
_description = "Wizard for settling commissions"
date_to = fields.Date("Up to", required=True, default=fields.Date.today)
agent_ids = fields.Many2many(
comodel_name="res.partner", domain="[('agent', '=', True)]"
)
settlement_type = fields.Selection(selection=[], required=True)
can_settle = fields.Boolean(
compute="_compute_can_settle",
help="Technical field for improving UX when no extra *commission is installed.",
)
@api.depends("date_to") # use this unrelated field to trigger the computation
def _compute_can_settle(self):
"""Check if there's any settlement type for making the settlements."""
self.can_settle = bool(
self.env[self._name]._fields["settlement_type"].selection
)
def _get_period_start(self, agent, date_to):
if agent.settlement == "monthly":
return date(month=date_to.month, year=date_to.year, day=1)
elif agent.settlement == "biweekly":
if date_to.day >= 16:
return date(month=date_to.month, year=date_to.year, day=16)
else:
return date(month=date_to.month, year=date_to.year, day=1)
elif agent.settlement == "quaterly":
# Get first month of the date quarter
month = (date_to.month - 1) // 3 * 3 + 1
return date(month=month, year=date_to.year, day=1)
elif agent.settlement == "semi":
if date_to.month > 6:
return date(month=7, year=date_to.year, day=1)
else:
return date(month=1, year=date_to.year, day=1)
elif agent.settlement == "annual":
return date(month=1, year=date_to.year, day=1)
def _get_next_period_date(self, agent, current_date):
if agent.settlement == "monthly":
return current_date + relativedelta(months=1)
elif agent.settlement == "biweekly":
if current_date.day == 1:
return current_date + relativedelta(days=15)
else:
return date(
month=current_date.month, year=current_date.year, day=1
) + relativedelta(months=1, days=-1)
elif agent.settlement == "quaterly":
return current_date + relativedelta(months=3)
elif agent.settlement == "semi":
return current_date + relativedelta(months=6)
elif agent.settlement == "annual":
return current_date + relativedelta(years=1)
def _get_settlement(self, agent, company, sett_from, sett_to):
self.ensure_one()
return self.env["commission.settlement"].search(
[
("agent_id", "=", agent.id),
("date_from", "=", sett_from),
("date_to", "=", sett_to),
("company_id", "=", company.id),
("state", "=", "settled"),
("settlement_type", "=", self.settlement_type),
],
limit=1,
)
def _prepare_settlement_vals(self, agent, company, sett_from, sett_to):
return {
"agent_id": agent.id,
"date_from": sett_from,
"date_to": sett_to,
"company_id": company.id,
"settlement_type": self.settlement_type,
}
def _prepare_settlement_line_vals(self, settlement, line):
"""Hook for returning the settlement line dictionary vals."""
return {
"settlement_id": settlement.id,
}
def _get_agent_lines(self, date_to_agent):
"""Need to be extended according to settlement_type."""
raise NotImplementedError()
def action_settle(self):
self.ensure_one()
settlement_obj = self.env["commission.settlement"]
settlement_line_obj = self.env["commission.settlement.line"]
settlement_ids = []
if self.agent_ids:
agents = self.agent_ids
else:
agents = self.env["res.partner"].search([("agent", "=", True)])
date_to = self.date_to
for agent in agents:
date_to_agent = self._get_period_start(agent, date_to)
# Get non settled elements
agent_lines = self._get_agent_lines(agent, date_to_agent)
for company in agent_lines.mapped("company_id"):
agent_lines_company = agent_lines.filtered(
lambda r: r.object_id.company_id == company
)
pos = 0
sett_to = date(year=1900, month=1, day=1)
while pos < len(agent_lines_company):
line = agent_lines_company[pos]
pos += 1
if line._skip_settlement():
continue
if line.invoice_date > sett_to:
sett_from = self._get_period_start(agent, line.invoice_date)
sett_to = self._get_next_period_date(agent, sett_from)
sett_to -= timedelta(days=1)
settlement = self._get_settlement(
agent, company, sett_from, sett_to
)
if not settlement:
settlement = settlement_obj.create(
self._prepare_settlement_vals(
agent, company, sett_from, sett_to
)
)
settlement_ids.append(settlement.id)
# TODO: Do creates in batch
settlement_line_obj.create(
self._prepare_settlement_line_vals(settlement, line)
)
# go to results
if len(settlement_ids):
return {
"name": _("Created Settlements"),
"type": "ir.actions.act_window",
"views": [[False, "list"], [False, "form"]],
"res_model": "commission.settlement",
"domain": [["id", "in", settlement_ids]],
}
| 42.228758 | 6,461 |
574 |
py
|
PYTHON
|
15.0
|
# Copyright 2015-2020 Tecnativa - Pedro M. Baeza
# Copyright 2021 Tecnativa - João Marques
# License AGPL-3 - See https://www.gnu.org/licenses/agpl-3.0.html
{
"name": "HR commissions",
"version": "15.0.1.0.0",
"author": "Tecnativa, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/commission",
"category": "Commissions",
"depends": ["account_commission", "hr"],
"license": "AGPL-3",
"data": [
"views/res_partner_view.xml",
"views/sale_commission_settlement_views.xml",
],
"installable": True,
}
| 31.833333 | 573 |
1,526 |
py
|
PYTHON
|
15.0
|
# Copyright 2018 Tecnativa - Pedro M. Baeza
# License AGPL-3 - See https://www.gnu.org/licenses/agpl-3.0.html
from odoo import exceptions
from odoo.addons.commission.tests.test_commission import TestCommissionBase
class TestHrCommission(TestCommissionBase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.employee = cls.env["hr.employee"].create({"name": "Test employee"})
cls.user = cls.env["res.users"].create(
{"name": "Test user", "login": "[email protected]"}
)
cls.partner = cls.user.partner_id
def test_hr_commission(self):
self.assertFalse(self.partner.employee_id)
with self.assertRaises(exceptions.ValidationError):
self.partner.agent_type = "salesman"
self.employee.user_id = self.user.id
self.assertEqual(self.partner.employee_id, self.employee)
# This shouldn't trigger exception now
self.partner.agent_type = "salesman"
self.assertTrue(self.partner.employee)
# Check that un-assigning user in employee, it raises the constraint
with self.assertRaises(exceptions.ValidationError):
self.employee.user_id = False
def test_mark_to_invoice(self):
settlements = self._create_settlement(
self.partner,
self.commission_section_paid,
)
self.assertEqual(settlements.state, "settled")
settlements.mark_as_invoiced()
self.assertEqual(settlements.state, "invoiced")
| 39.128205 | 1,526 |
747 |
py
|
PYTHON
|
15.0
|
# Copyright 2018 Tecnativa - Pedro M. Baeza
# License AGPL-3 - See https://www.gnu.org/licenses/agpl-3.0.html
from odoo import _, exceptions, models
class HrEmployee(models.Model):
_inherit = "hr.employee"
def write(self, vals):
"""Check if there's an agent linked to that employee."""
if "user_id" in vals and not vals["user_id"]:
for emp in self:
if emp.user_id.partner_id.agent_type == "salesman":
raise exceptions.ValidationError(
_(
"You can't remove the user, as it's linked to "
"a commission agent."
)
)
return super().write(vals)
| 35.571429 | 747 |
1,898 |
py
|
PYTHON
|
15.0
|
# Copyright 2015-2018 Tecnativa - Pedro M. Baeza
# Copyright 2021 Tecnativa - João Marques
# License AGPL-3 - See https://www.gnu.org/licenses/agpl-3.0.html
from odoo import _, api, exceptions, fields, models
class ResPartner(models.Model):
_inherit = "res.partner"
agent_type = fields.Selection(
selection_add=[("salesman", "Salesman (employee)")],
)
employee_id = fields.Many2one(
string="Related Employee",
comodel_name="hr.employee",
compute="_compute_employee_id",
compute_sudo=True,
)
employee = fields.Boolean(compute="_compute_employee", store=True, readonly=False)
@api.depends("user_ids")
def _compute_employee_id(self):
for partner in self:
if len(partner.user_ids) == 1 and partner.user_ids[0].employee_ids:
partner.employee_id = partner.user_ids[0].employee_ids[0]
else:
partner.employee_id = False
@api.depends("agent_type", "employee_id")
def _compute_employee(self):
"""Set the Boolean field according to the ResPartner-HrEmployee
relation created here
"""
if hasattr(super(), "_compute_employee"):
return super()._compute_employee()
for record in self:
if record.employee_id and record.agent_type == "salesman":
record.employee = True
else:
record.employee = False
@api.constrains("agent_type")
def _check_employee(self):
if self.agent_type == "salesman" and not self.employee_id:
raise exceptions.ValidationError(
_(
"There must one (and only one) employee linked to this "
"partner. To do this, go to 'Employees' and create an "
"Employee with a 'Related User' under 'HR Settings'."
)
)
| 36.480769 | 1,897 |
292 |
py
|
PYTHON
|
15.0
|
# Copyright 2020 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import models
class CommissionSettlement(models.Model):
_inherit = "commission.settlement"
def mark_as_invoiced(self):
self.write({"state": "invoiced"})
| 26.545455 | 292 |
736 |
py
|
PYTHON
|
15.0
|
import setuptools
with open('VERSION.txt', 'r') as f:
version = f.read().strip()
setuptools.setup(
name="odoo-addons-oca-commission",
description="Meta package for oca-commission Odoo addons",
version=version,
install_requires=[
'odoo-addon-account_commission>=15.0dev,<15.1dev',
'odoo-addon-commission>=15.0dev,<15.1dev',
'odoo-addon-commission_formula>=15.0dev,<15.1dev',
'odoo-addon-hr_commission>=15.0dev,<15.1dev',
'odoo-addon-sale_commission>=15.0dev,<15.1dev',
'odoo-addon-sale_commission_salesman>=15.0dev,<15.1dev',
],
classifiers=[
'Programming Language :: Python',
'Framework :: Odoo',
'Framework :: Odoo :: 15.0',
]
)
| 32 | 736 |
100 |
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667 | 100 |
100 |
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667 | 100 |
100 |
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667 | 100 |
100 |
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667 | 100 |
100 |
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667 | 100 |
100 |
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667 | 100 |
893 |
py
|
PYTHON
|
15.0
|
# Copyright 2020 Tecnativa - Manuel Calero
# Copyright 2022 Quartile
# Copyright 2014-2022 Tecnativa - Pedro M. Baeza
{
"name": "Account commissions",
"version": "15.0.2.2.0",
"author": "Tecnativa, Odoo Community Association (OCA)",
"category": "Sales Management",
"license": "AGPL-3",
"depends": [
"account",
"commission",
],
"website": "https://github.com/OCA/commission",
"maintainers": ["pedrobaeza"],
"data": [
"security/account_commission_security.xml",
"security/ir.model.access.csv",
"data/menuitem_data.xml",
"views/account_move_views.xml",
"views/commission_settlement_views.xml",
"views/commission_views.xml",
"views/report_settlement_templates.xml",
"report/commission_analysis_view.xml",
"wizards/wizard_invoice.xml",
],
"installable": True,
}
| 31.892857 | 893 |
18,163 |
py
|
PYTHON
|
15.0
|
# Copyright 2020 Tecnativa - Manuel Calero
# Copyright 2022 Quartile
# Copyright 2016-2022 Tecnativa - Pedro M. Baeza
# License AGPL-3 - See https://www.gnu.org/licenses/agpl-3.0.html
from dateutil.relativedelta import relativedelta
from odoo import fields
from odoo.exceptions import UserError, ValidationError
from odoo.tests import Form, tagged
from odoo.addons.commission.tests.test_commission import TestCommissionBase
@tagged("post_install", "-at_install")
class TestAccountCommission(TestCommissionBase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.journal = cls.env["account.journal"].search(
[("type", "=", "purchase"), ("company_id", "=", cls.company.id)], limit=1
)
cls.commission_net_paid.write({"invoice_state": "paid"})
cls.commission_net_invoice = cls.commission_model.create(
{
"name": "10% fixed commission (Net amount) - Invoice Based",
"fix_qty": 10.0,
"amount_base_type": "net_amount",
}
)
cls.commission_section_paid.write({"invoice_state": "paid"})
cls.product = cls.env["product.product"].create(
{
"name": "Test product for commissions",
"list_price": 5,
}
)
cls.default_line_account = cls.env.ref("account.data_account_type_receivable")
cls.agent_biweekly = cls.res_partner_model.create(
{
"name": "Test Agent - Bi-weekly",
"agent": True,
"settlement": "biweekly",
"lang": "en_US",
"commission_id": cls.commission_net_invoice.id,
}
)
cls.income_account = cls.env["account.account"].search(
[
("company_id", "=", cls.company.id),
("user_type_id.name", "=", "Income"),
],
limit=1,
)
def _create_invoice(self, agent, commission, date=None):
invoice_form = Form(
self.env["account.move"].with_context(default_move_type="out_invoice")
)
invoice_form.partner_id = self.partner
with invoice_form.invoice_line_ids.new() as line_form:
line_form.product_id = self.product
if date:
invoice_form.invoice_date = date
invoice_form.date = date
invoice = invoice_form.save()
invoice.invoice_line_ids.agent_ids = [
(0, 0, {"agent_id": agent.id, "commission_id": commission.id})
]
return invoice
def _settle_agent_invoice(self, agent=None, period=None, date=None):
vals = self._get_make_settle_vals(agent, period, date)
vals["settlement_type"] = "sale_invoice"
wizard = self.make_settle_model.create(vals)
wizard.action_settle()
def _process_invoice_and_settle(self, agent, commission, period, order=None):
if not order:
invoice = self._create_invoice(agent, commission)
else:
invoice = order.invoice_ids
invoice.invoice_line_ids.agent_ids._compute_amount()
invoice.action_post()
self._settle_agent_invoice(agent, period)
return invoice
def _check_settlements(self, agent, commission, settlements=None):
if not settlements:
settlements = self._create_settlement(agent, commission)
settlements.make_invoices(self.journal, self.commission_product)
for settlement in settlements:
self.assertEqual(settlement.state, "invoiced")
with self.assertRaises(UserError):
settlements.action_cancel()
with self.assertRaises(UserError):
settlements.unlink()
return settlements
def _check_invoice_thru_settle(
self, agent, commission, period, initial_count, order=None
):
invoice = self._process_invoice_and_settle(agent, commission, period, order)
settlements = self.settle_model.search([("state", "=", "settled")])
self.assertEqual(len(settlements), initial_count)
journal = self.env["account.journal"].search(
[("type", "=", "cash"), ("company_id", "=", invoice.company_id.id)],
limit=1,
)
register_payments = (
self.env["account.payment.register"]
.with_context(active_ids=invoice.id, active_model="account.move")
.create({"journal_id": journal.id})
)
register_payments.action_create_payments()
self.assertEqual(invoice.partner_agent_ids.ids, agent.ids)
self.assertEqual(
self.env["account.move"]
.search([("partner_agent_ids", "=", agent.name)])
.ids,
invoice.ids,
)
self.assertIn(invoice.payment_state, ["in_payment", "paid"])
self._settle_agent_invoice(agent, period)
settlements = self.settle_model.search([("state", "=", "settled")])
self.assertTrue(settlements)
inv_line = invoice.invoice_line_ids[0]
self.assertTrue(inv_line.any_settled)
with self.assertRaises(ValidationError):
inv_line.agent_ids.amount = 5
return self._check_settlements(agent, commission, settlements)
def test_commission_gross_amount(self):
settlements = self._check_settlements(
self.env.ref("commission.res_partner_pritesh_sale_agent"),
self.commission_section_paid,
)
# Check report print - It shouldn't fail
self.env.ref("commission.action_report_settlement")._render_qweb_html(
settlements[0].ids
)
def test_account_commission_gross_amount_payment(self):
self._check_invoice_thru_settle(
self.env.ref("commission.res_partner_pritesh_sale_agent"),
self.commission_section_paid,
1,
0,
)
def test_account_commission_gross_amount_payment_annual(self):
self._check_invoice_thru_settle(
self.agent_annual, self.commission_section_paid, 12, 0
)
def test_account_commission_gross_amount_payment_semi(self):
self.product.list_price = 15100 # for testing specific commission section
self._check_invoice_thru_settle(
self.agent_semi, self.commission_section_invoice, 6, 1
)
def test_account_commission_gross_amount_invoice(self):
self._process_invoice_and_settle(
self.agent_quaterly,
self.env.ref("commission.demo_commission"),
1,
)
settlements = self.settle_model.search([("state", "=", "invoiced")])
settlements.make_invoices(self.journal, self.commission_product)
for settlement in settlements:
self.assertNotEqual(
len(settlement.invoice_id),
0,
"Settlements need to be in Invoiced State.",
)
def test_commission_status(self):
# Make sure user is in English
self.env.user.lang = "en_US"
invoice = self._create_invoice(
self.env.ref("commission.res_partner_pritesh_sale_agent"),
self.commission_section_invoice,
)
self.assertIn("1", invoice.invoice_line_ids[0].commission_status)
self.assertNotIn("agents", invoice.invoice_line_ids[0].commission_status)
invoice.mapped("invoice_line_ids.agent_ids").unlink()
self.assertIn("No", invoice.invoice_line_ids[0].commission_status)
invoice.invoice_line_ids[0].agent_ids = [
(
0,
0,
{
"agent_id": self.env.ref(
"commission.res_partner_pritesh_sale_agent"
).id,
"commission_id": self.env.ref("commission.demo_commission").id,
},
),
(
0,
0,
{
"agent_id": self.env.ref(
"commission.res_partner_eiffel_sale_agent"
).id,
"commission_id": self.env.ref("commission.demo_commission").id,
},
),
]
self.assertIn("2", invoice.invoice_line_ids[0].commission_status)
self.assertIn("agents", invoice.invoice_line_ids[0].commission_status)
invoice.action_post()
# Free
invoice.invoice_line_ids.commission_free = True
self.assertIn("free", invoice.invoice_line_ids.commission_status)
self.assertAlmostEqual(invoice.invoice_line_ids.agent_ids.amount, 0)
# test show agents buton
action = invoice.invoice_line_ids.button_edit_agents()
self.assertEqual(action["res_id"], invoice.invoice_line_ids.id)
def test_supplier_invoice(self):
"""No agents should be populated on supplier invoices."""
self.partner.agent_ids = self.agent_semi
move_form = Form(
self.env["account.move"].with_context(default_move_type="in_invoice")
)
move_form.partner_id = self.partner
move_form.ref = "sale_comission_TEST"
with move_form.invoice_line_ids.new() as line_form:
line_form.product_id = self.product
line_form.quantity = 1
line_form.currency_id = self.company.currency_id
invoice = move_form.save()
self.assertFalse(invoice.invoice_line_ids.agent_ids)
def test_commission_propagation(self):
"""Test propagation of agents from partner to invoice."""
self.partner.agent_ids = [(4, self.agent_monthly.id)]
move_form = Form(
self.env["account.move"].with_context(default_move_type="out_invoice")
)
move_form.partner_id = self.partner
with move_form.invoice_line_ids.new() as line_form:
line_form.currency_id = self.company.currency_id
line_form.product_id = self.product
line_form.quantity = 1
invoice = move_form.save()
agent = invoice.invoice_line_ids.agent_ids
self._check_propagation(agent, self.commission_net_invoice, self.agent_monthly)
# Check agent change
agent.agent_id = self.agent_quaterly
self.assertTrue(agent.commission_id, self.commission_section_invoice)
# Check recomputation
agent.unlink()
invoice.recompute_lines_agents()
agent = invoice.invoice_line_ids.agent_ids
self._check_propagation(agent, self.commission_net_invoice, self.agent_monthly)
def test_negative_settlements(self):
self.product.write({"list_price": 1000})
agent = self.agent_monthly
commission = self.commission_net_invoice
invoice = self._process_invoice_and_settle(agent, commission, 1)
settlement = self.settle_model.search([("agent_id", "=", agent.id)])
self.assertEqual(1, len(settlement))
self.assertEqual(settlement.state, "settled")
commission_invoice = settlement.make_invoices(
product=self.commission_product, journal=self.journal
)
self.assertEqual(settlement.state, "invoiced")
self.assertEqual(commission_invoice.move_type, "in_invoice")
refund = invoice._reverse_moves(
default_values_list=[{"invoice_date": invoice.invoice_date}],
)
self.assertEqual(
invoice.invoice_line_ids.agent_ids.agent_id,
refund.invoice_line_ids.agent_ids.agent_id,
)
refund.invoice_line_ids.agent_ids._compute_amount()
refund.action_post()
self._settle_agent_invoice(agent, 1)
settlements = self.settle_model.search([("agent_id", "=", agent.id)])
self.assertEqual(2, len(settlements))
second_settlement = settlements.filtered(lambda r: r.total < 0)
self.assertEqual(second_settlement.state, "settled")
# Use invoice wizard for testing also this part
wizard = self.env["commission.make.invoice"].create(
{"product_id": self.commission_product.id}
)
action = wizard.button_create()
commission_refund = self.env["account.move"].browse(action["domain"][0][2])
self.assertEqual(second_settlement.state, "invoiced")
self.assertEqual(commission_refund.move_type, "in_refund")
# Undo invoices + make invoice again to get a unified invoice
commission_invoices = commission_invoice + commission_refund
commission_invoices.button_cancel()
self.assertEqual(settlement.state, "except_invoice")
self.assertEqual(second_settlement.state, "except_invoice")
commission_invoices.unlink()
settlements.unlink()
self._settle_agent_invoice(False, 1) # agent=False for testing default
settlement = self.settle_model.search([("agent_id", "=", agent.id)])
# Check make invoice wizard
action = settlement.action_invoice()
self.assertEqual(action["context"]["settlement_ids"], settlement.ids)
# Use invoice wizard for testing also this part
wizard = self.env["commission.make.invoice"].create(
{
"product_id": self.commission_product.id,
"journal_id": self.journal.id,
"settlement_ids": [(4, settlement.id)],
}
)
action = wizard.button_create()
invoice = self.env["account.move"].browse(action["domain"][0][2])
self.assertEqual(invoice.move_type, "in_invoice")
self.assertAlmostEqual(invoice.amount_total, 0)
def test_negative_settlements_join_invoice(self):
self.product.write({"list_price": 1000})
agent = self.agent_monthly
commission = self.commission_net_invoice
invoice = self._process_invoice_and_settle(agent, commission, 1)
settlement = self.settle_model.search([("agent_id", "=", agent.id)])
self.assertEqual(1, len(settlement))
self.assertEqual(settlement.state, "settled")
refund = invoice._reverse_moves(
default_values_list=[
{
"invoice_date": invoice.invoice_date + relativedelta(months=-1),
"date": invoice.date + relativedelta(months=-1),
}
],
)
self.assertEqual(
invoice.invoice_line_ids.agent_ids.agent_id,
refund.invoice_line_ids.agent_ids.agent_id,
)
refund.action_post()
self._settle_agent_invoice(agent, 1)
settlements = self.settle_model.search([("agent_id", "=", agent.id)])
self.assertEqual(2, len(settlements))
second_settlement = settlements.filtered(lambda r: r.total < 0)
self.assertEqual(second_settlement.state, "settled")
# Use invoice wizard for testing also this part
wizard = self.env["commission.make.invoice"].create(
{"product_id": self.commission_product.id, "grouped": True}
)
action = wizard.button_create()
commission_invoice = self.env["account.move"].browse(action["domain"][0][2])
self.assertEqual(1, len(commission_invoice))
self.assertEqual(commission_invoice.move_type, "in_invoice")
self.assertAlmostEqual(commission_invoice.amount_total, 0, places=2)
def _create_multi_settlements(self):
agent = self.agent_monthly
commission = self.commission_section_invoice
today = fields.Date.today()
last_month = today + relativedelta(months=-1)
invoice_1 = self._create_invoice(agent, commission, today)
invoice_1.action_post()
invoice_2 = self._create_invoice(agent, commission, last_month)
invoice_2.action_post()
self._settle_agent_invoice(agent, 1)
settlements = self.settle_model.search(
[
("agent_id", "=", agent.id),
("state", "=", "settled"),
]
)
self.assertEqual(2, len(settlements))
return settlements
def test_commission_single_invoice(self):
settlements = self._create_multi_settlements()
settlements.make_invoices(self.journal, self.commission_product, grouped=True)
invoices = settlements.mapped("invoice_id")
self.assertEqual(1, len(invoices))
def test_commission_multiple_invoice(self):
settlements = self._create_multi_settlements()
settlements.make_invoices(self.journal, self.commission_product)
invoices = settlements.mapped("invoice_id")
self.assertEqual(2, len(invoices))
def test_biweekly(self):
agent = self.agent_biweekly
commission = self.commission_net_invoice
invoice = self._create_invoice(agent, commission)
invoice.invoice_date = "2022-01-01"
invoice.date = "2022-01-01"
invoice.action_post()
invoice2 = self._create_invoice(agent, commission, date="2022-01-16")
invoice2.invoice_date = "2022-01-16"
invoice2.date = "2022-01-16"
invoice2.action_post()
invoice3 = self._create_invoice(agent, commission, date="2022-01-31")
invoice3.invoice_date = "2022-01-31"
invoice3.date = "2022-01-31"
invoice3.action_post()
self._settle_agent_invoice(agent=self.agent_biweekly, date="2022-02-01")
settlements = self.settle_model.search(
[("agent_id", "=", self.agent_biweekly.id)]
)
self.assertEqual(len(settlements), 2)
def test_account_commission_single_settlement_ids(self):
settlement = self._check_invoice_thru_settle(
self.env.ref("commission.res_partner_pritesh_sale_agent"),
self.commission_section_paid,
1,
0,
)
invoice_id = settlement.invoice_id
self.assertEqual(1, invoice_id.settlement_count)
def test_account_commission_multiple_settlement_ids(self):
settlements = self._create_multi_settlements()
settlements.make_invoices(self.journal, self.commission_product, grouped=True)
invoices = settlements.mapped("invoice_id")
self.assertEqual(2, invoices.settlement_count)
| 43.142518 | 18,163 |
326 |
py
|
PYTHON
|
15.0
|
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields, models
class Commission(models.Model):
_inherit = "commission"
invoice_state = fields.Selection(
[("open", "Invoice Based"), ("paid", "Payment Based")],
string="Invoice Status",
default="open",
)
| 25.076923 | 326 |
9,295 |
py
|
PYTHON
|
15.0
|
# Copyright 2020 Tecnativa - Manuel Calero
# Copyright 2014-2022 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from lxml import etree
from odoo import _, api, exceptions, fields, models
class AccountMove(models.Model):
_inherit = "account.move"
commission_total = fields.Float(
string="Commissions",
compute="_compute_commission_total",
store=True,
)
partner_agent_ids = fields.Many2many(
string="Agents",
comodel_name="res.partner",
compute="_compute_agents",
search="_search_agents",
)
settlement_count = fields.Integer(compute="_compute_settlement")
settlement_ids = fields.One2many(
"commission.settlement",
string="Settlements",
compute="_compute_settlement",
)
def action_view_settlement(self):
xmlid = "commission.action_commission_settlement"
action = self.env["ir.actions.actions"]._for_xml_id(xmlid)
action["context"] = {}
settlements = self.mapped("settlement_ids")
if not settlements or len(settlements) > 1:
action["domain"] = [("id", "in", settlements.ids)]
elif len(settlements) == 1:
res = self.env.ref("commission.view_settlement_form", False)
action["views"] = [(res and res.id or False, "form")]
action["res_id"] = settlements.id
return action
def _compute_settlement(self):
for invoice in self:
settlements = invoice.invoice_line_ids.settlement_id
invoice.settlement_ids = settlements
invoice.settlement_count = len(settlements)
@api.depends("partner_agent_ids", "invoice_line_ids.agent_ids.agent_id")
def _compute_agents(self):
for move in self:
move.partner_agent_ids = [
(6, 0, move.mapped("invoice_line_ids.agent_ids.agent_id").ids)
]
@api.model
def _search_agents(self, operator, value):
ail_agents = self.env["account.invoice.line.agent"].search(
[("agent_id", operator, value)]
)
return [("id", "in", ail_agents.mapped("object_id.move_id").ids)]
@api.depends("line_ids.agent_ids.amount")
def _compute_commission_total(self):
for record in self:
record.commission_total = 0.0
for line in record.line_ids:
record.commission_total += sum(x.amount for x in line.agent_ids)
def action_post(self):
"""Put settlements associated to the invoices in invoiced state."""
self.mapped("line_ids.settlement_id").write({"state": "invoiced"})
return super().action_post()
def button_cancel(self):
"""Check settled lines and put settlements associated to the invoices in
exception.
"""
if any(self.mapped("invoice_line_ids.any_settled")):
raise exceptions.ValidationError(
_("You can't cancel an invoice with settled lines"),
)
self.mapped("line_ids.settlement_id").write({"state": "except_invoice"})
return super().button_cancel()
def recompute_lines_agents(self):
self.mapped("invoice_line_ids").recompute_agents()
@api.model
def fields_view_get(
self, view_id=None, view_type="form", toolbar=False, submenu=False
):
"""Inject in this method the needed context for not removing other
possible context values.
"""
res = super(AccountMove, self).fields_view_get(
view_id=view_id,
view_type=view_type,
toolbar=toolbar,
submenu=submenu,
)
if view_type == "form":
invoice_xml = etree.XML(res["arch"])
invoice_line_fields = invoice_xml.xpath("//field[@name='invoice_line_ids']")
if invoice_line_fields:
invoice_line_field = invoice_line_fields[0]
context = invoice_line_field.attrib.get("context", "{}").replace(
"{",
"{'partner_id': partner_id, ",
1,
)
invoice_line_field.attrib["context"] = context
res["arch"] = etree.tostring(invoice_xml)
return res
class AccountMoveLine(models.Model):
_inherit = [
"account.move.line",
"commission.mixin",
]
_name = "account.move.line"
agent_ids = fields.One2many(comodel_name="account.invoice.line.agent")
any_settled = fields.Boolean(compute="_compute_any_settled")
settlement_id = fields.Many2one(
comodel_name="commission.settlement",
help="Settlement that generates this invoice line",
copy=False,
)
@api.depends("agent_ids", "agent_ids.settled")
def _compute_any_settled(self):
for record in self:
record.any_settled = any(record.mapped("agent_ids.settled"))
@api.depends("move_id.partner_id")
def _compute_agent_ids(self):
for res in self:
settlement_lines = self.env["commission.settlement.line"].search(
[("invoice_line_id", "=", res.id)]
)
for line in settlement_lines:
line.date = False
line.agent_id = False
line.settled_amount = 0.00
line.currency_id = False
line.commission_id = False
self.agent_ids = False # for resetting previous agents
for record in self.filtered(
lambda x: x.move_id.partner_id and x.move_id.move_type[:3] == "out"
):
if not record.commission_free and record.product_id:
record.agent_ids = record._prepare_agents_vals_partner(
record.move_id.partner_id, settlement_type="sale_invoice"
)
def _copy_data_extend_business_fields(self, values):
"""We don't want to loose the settlement from the line when reversing the line
if it was a refund. We need to include it, but as we don't want change it
everytime, we will add the data when a context key is passed.
"""
res = super()._copy_data_extend_business_fields(values)
if self.settlement_id and self.env.context.get("include_settlement", False):
values["settlement_id"] = self.settlement_id.id
return res
class AccountInvoiceLineAgent(models.Model):
_inherit = "commission.line.mixin"
_name = "account.invoice.line.agent"
_description = "Agent detail of commission line in invoice lines"
object_id = fields.Many2one(comodel_name="account.move.line")
invoice_id = fields.Many2one(
string="Invoice",
comodel_name="account.move",
related="object_id.move_id",
store=True,
)
invoice_date = fields.Date(
string="Invoice date",
related="invoice_id.invoice_date",
store=True,
readonly=True,
)
settlement_line_ids = fields.One2many(
comodel_name="commission.settlement.line",
inverse_name="invoice_agent_line_id",
)
settled = fields.Boolean(compute="_compute_settled", store=True)
company_id = fields.Many2one(
comodel_name="res.company",
compute="_compute_company",
store=True,
)
currency_id = fields.Many2one(
related="object_id.currency_id",
readonly=True,
)
@api.depends(
"object_id.price_subtotal",
"object_id.product_id.commission_free",
"commission_id",
)
def _compute_amount(self):
for line in self:
inv_line = line.object_id
line.amount = line._get_commission_amount(
line.commission_id,
inv_line.price_subtotal,
inv_line.product_id,
inv_line.quantity,
)
# Refunds commissions are negative
if line.invoice_id.move_type and "refund" in line.invoice_id.move_type:
line.amount = -line.amount
@api.depends(
"settlement_line_ids",
"settlement_line_ids.settlement_id.state",
"invoice_id",
"invoice_id.state",
)
def _compute_settled(self):
# Count lines of not open or paid invoices as settled for not
# being included in settlements
for line in self:
line.settled = any(
x.settlement_id.state != "cancel" for x in line.settlement_line_ids
)
@api.depends("object_id", "object_id.company_id")
def _compute_company(self):
for line in self:
line.company_id = line.object_id.company_id
@api.constrains("agent_id", "amount")
def _check_settle_integrity(self):
for record in self:
if any(record.mapped("settled")):
raise exceptions.ValidationError(
_("You can't modify a settled line"),
)
def _skip_settlement(self):
"""This function should return False if the commission can be paid.
:return: bool
"""
self.ensure_one()
return (
self.commission_id.invoice_state == "paid"
and self.invoice_id.payment_state not in ["in_payment", "paid"]
) or self.invoice_id.state != "posted"
| 36.027132 | 9,295 |
6,952 |
py
|
PYTHON
|
15.0
|
# Copyright 2020 Tecnativa - Manuel Calero
# Copyright 2022 Quartile
# Copyright 2014-2022 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import _, api, fields, models
from odoo.exceptions import UserError
from odoo.tests import Form
from odoo.tools import groupby
class CommissionSettlement(models.Model):
_inherit = "commission.settlement"
settlement_type = fields.Selection(
selection_add=[("sale_invoice", "Sales Invoices")],
ondelete={"sale_invoice": "set default"},
)
state = fields.Selection(
selection_add=[
("invoiced", "Invoiced"),
("except_invoice", "Invoice exception"),
],
ondelete={"invoiced": "set default", "except_invoice": "set default"},
)
invoice_line_ids = fields.One2many(
comodel_name="account.move.line",
inverse_name="settlement_id",
string="Generated invoice lines",
readonly=True,
)
invoice_id = fields.Many2one(
string="Generated Invoice",
store=True,
comodel_name="account.move",
compute="_compute_invoice_id",
)
def _compute_can_edit(self):
"""Make settlements coming from invoice lines to not be editable."""
sale_invoices = self.filtered(lambda x: x.settlement_type == "sale_invoice")
sale_invoices.update({"can_edit": False})
return super(CommissionSettlement, self - sale_invoices)._compute_can_edit()
@api.depends("invoice_line_ids")
def _compute_invoice_id(self):
for record in self:
record.invoice_id = record.invoice_line_ids.filtered(
lambda x: x.parent_state != "cancel"
)[:1].move_id
def action_cancel(self):
"""Check if any settlement has been invoiced."""
if any(x.state != "settled" for x in self):
raise UserError(_("Cannot cancel an invoiced settlement."))
return super().action_cancel()
def action_draft(self):
self.write({"state": "settled"})
def unlink(self):
"""Allow to delete only cancelled settlements."""
if any(x.state == "invoiced" for x in self):
raise UserError(_("You can't delete invoiced settlements."))
return super().unlink()
def action_invoice(self):
return {
"type": "ir.actions.act_window",
"name": _("Make invoice"),
"res_model": "commission.make.invoice",
"view_type": "form",
"target": "new",
"view_mode": "form",
"context": {"settlement_ids": self.ids},
}
def _get_invoice_partner(self):
return self[0].agent_id
def _prepare_invoice(self, journal, product, date=False):
move_form = Form(
self.env["account.move"].with_context(default_move_type="in_invoice")
)
if date:
move_form.invoice_date = date
partner = self._get_invoice_partner()
move_form.partner_id = partner
move_form.journal_id = journal
for settlement in self:
with move_form.invoice_line_ids.new() as line_form:
line_form.product_id = product
line_form.quantity = -1 if settlement.total < 0 else 1
line_form.price_unit = abs(settlement.total)
# Put period string
partner = self.agent_id
lang = self.env["res.lang"].search(
[
(
"code",
"=",
partner.lang or self.env.context.get("lang", "en_US"),
)
]
)
date_from = fields.Date.from_string(settlement.date_from)
date_to = fields.Date.from_string(settlement.date_to)
line_form.name += "\n" + _(
"Period: from %(date_from)s to %(date_to)s",
date_from=date_from.strftime(lang.date_format),
date_to=date_to.strftime(lang.date_format),
)
line_form.currency_id = (
settlement.currency_id
) # todo or compute agent currency_id?\
line_form.settlement_id = settlement
vals = move_form._values_to_save(all_fields=True)
return vals
def _get_invoice_grouping_keys(self):
return ["company_id", "agent_id"]
def make_invoices(self, journal, product, date=False, grouped=False):
invoice_vals_list = []
settlement_obj = self.env[self._name]
if grouped:
invoice_grouping_keys = self._get_invoice_grouping_keys()
settlements = groupby(
self.sorted(
key=lambda x: [
x._fields[grouping_key].convert_to_write(x[grouping_key], x)
for grouping_key in invoice_grouping_keys
],
),
key=lambda x: tuple(
x._fields[grouping_key].convert_to_write(x[grouping_key], x)
for grouping_key in invoice_grouping_keys
),
)
grouped_settlements = [
settlement_obj.union(*list(sett))
for _grouping_keys, sett in settlements
]
else:
grouped_settlements = self
for settlement in grouped_settlements:
invoice_vals = settlement._prepare_invoice(journal, product, date)
invoice_vals_list.append(invoice_vals)
invoices = self.env["account.move"].create(invoice_vals_list)
invoices.sudo().filtered(lambda m: m.amount_total < 0).with_context(
include_settlement=True
).action_switch_invoice_into_refund_credit_note()
self.write({"state": "invoiced"})
return invoices
class SettlementLine(models.Model):
_inherit = "commission.settlement.line"
invoice_agent_line_id = fields.Many2one(comodel_name="account.invoice.line.agent")
invoice_line_id = fields.Many2one(
comodel_name="account.move.line",
store=True,
related="invoice_agent_line_id.object_id",
string="Source invoice line",
)
@api.depends("invoice_agent_line_id")
def _compute_date(self):
for record in self.filtered("invoice_agent_line_id"):
record.date = record.invoice_agent_line_id.invoice_date
@api.depends("invoice_agent_line_id")
def _compute_commission_id(self):
for record in self.filtered("invoice_agent_line_id"):
record.commission_id = record.invoice_agent_line_id.commission_id
@api.depends("invoice_agent_line_id")
def _compute_settled_amount(self):
for record in self.filtered("invoice_agent_line_id"):
record.settled_amount = record.invoice_agent_line_id.amount
| 38.40884 | 6,952 |
3,915 |
py
|
PYTHON
|
15.0
|
# Copyright 2014-2018 Tecnativa - Pedro M. Baeza
# Copyright 2020 Tecnativa - Manuel Calero
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from psycopg2.extensions import AsIs
from odoo import api, fields, models, tools
class InvoiceCommissionAnalysisReport(models.Model):
_name = "invoice.commission.analysis.report"
_description = "Invoice Commission Analysis Report"
_auto = False
_rec_name = "commission_id"
@api.model
def _get_selection_invoice_state(self):
return self.env["account.move"].fields_get(allfields=["state"])["state"][
"selection"
]
invoice_state = fields.Selection(
selection="_get_selection_invoice_state", string="Invoice Status", readonly=True
)
date_invoice = fields.Date("Invoice Date", readonly=True)
company_id = fields.Many2one("res.company", "Company", readonly=True)
partner_id = fields.Many2one("res.partner", "Partner", readonly=True)
agent_id = fields.Many2one("res.partner", "Agent", readonly=True)
categ_id = fields.Many2one("product.category", "Category of Product", readonly=True)
product_id = fields.Many2one("product.product", "Product", readonly=True)
uom_id = fields.Many2one("uom.uom", "Unit of Measure", readonly=True)
quantity = fields.Float("# of Qty", readonly=True)
price_unit = fields.Float("Unit Price", readonly=True)
price_subtotal = fields.Float("Subtotal", readonly=True)
balance = fields.Float(
readonly=True,
)
percentage = fields.Integer("Percentage of commission", readonly=True)
amount = fields.Float(readonly=True)
invoice_line_id = fields.Many2one("account.move.line", readonly=True)
settled = fields.Boolean(readonly=True)
commission_id = fields.Many2one("commission", "Commission", readonly=True)
def _select(self):
select_str = """
SELECT MIN(aila.id) AS id,
ai.partner_id AS partner_id,
ai.state AS invoice_state,
ai.date AS date_invoice,
ail.company_id AS company_id,
rp.id AS agent_id,
pt.categ_id AS categ_id,
ail.product_id AS product_id,
pt.uom_id AS uom_id,
SUM(ail.quantity) AS quantity,
AVG(ail.price_unit) AS price_unit,
SUM(ail.price_subtotal) AS price_subtotal,
SUM(ail.balance) AS balance,
AVG(c.fix_qty) AS percentage,
SUM(aila.amount) AS amount,
ail.id AS invoice_line_id,
aila.settled AS settled,
aila.commission_id AS commission_id
"""
return select_str
def _from(self):
from_str = """
account_invoice_line_agent aila
LEFT JOIN account_move_line ail ON ail.id = aila.object_id
INNER JOIN account_move ai ON ai.id = ail.move_id
LEFT JOIN commission c ON c.id = aila.commission_id
LEFT JOIN product_product pp ON pp.id = ail.product_id
INNER JOIN product_template pt ON pp.product_tmpl_id = pt.id
LEFT JOIN res_partner rp ON aila.agent_id = rp.id
"""
return from_str
def _group_by(self):
group_by_str = """
GROUP BY ai.partner_id,
ai.state,
ai.date,
ail.company_id,
rp.id,
pt.categ_id,
ail.product_id,
pt.uom_id,
ail.id,
aila.settled,
aila.commission_id
"""
return group_by_str
@api.model
def init(self):
tools.drop_view_if_exists(self._cr, self._table)
self._cr.execute(
"CREATE or REPLACE VIEW %s AS ( %s FROM ( %s ) %s )",
(
AsIs(self._table),
AsIs(self._select()),
AsIs(self._from()),
AsIs(self._group_by()),
),
)
| 36.933962 | 3,915 |
1,543 |
py
|
PYTHON
|
15.0
|
# Copyright 2014-2022 Tecnativa - Pedro M. Baeza
# Copyright 2022 Quartile
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields, models
class CommissionMakeSettle(models.TransientModel):
_inherit = "commission.make.settle"
settlement_type = fields.Selection(
selection_add=[("sale_invoice", "Sales Invoices")],
ondelete={"sale_invoice": "cascade"},
)
def _get_agent_lines(self, agent, date_to_agent):
"""Filter sales invoice agent lines for this type of settlement."""
if self.settlement_type != "sale_invoice":
return super()._get_agent_lines(agent, date_to_agent)
return self.env["account.invoice.line.agent"].search(
[
("invoice_date", "<", date_to_agent),
("agent_id", "=", agent.id),
("settled", "=", False),
],
order="invoice_date",
)
def _prepare_settlement_line_vals(self, settlement, line):
"""Prepare extra settlement values when the source is a sales invoice agent
line.
"""
res = super()._prepare_settlement_line_vals(settlement, line)
if self.settlement_type == "sale_invoice":
res.update(
{
"invoice_agent_line_id": line.id,
"date": line.invoice_date,
"commission_id": line.commission_id.id,
"settled_amount": line.amount,
}
)
return res
| 35.068182 | 1,543 |
3,259 |
py
|
PYTHON
|
15.0
|
from odoo import _, exceptions, fields, models
class CommissionMakeInvoice(models.TransientModel):
_name = "commission.make.invoice"
_description = "Wizard for making an invoice from a settlement"
def _default_journal_id(self):
return self.env["account.journal"].search(
[("type", "=", "purchase"), ("company_id", "=", self.env.company.id)],
limit=1,
)
def _default_settlement_ids(self):
context = self.env.context
if context.get("active_model") == "commission.settlement":
settlements = self.env[context["active_model"]].browse(
context.get("active_ids")
)
settlements = settlements.filtered_domain(
[
("state", "=", "settled"),
("agent_type", "=", "agent"),
("company_id", "=", self.env.company.id),
]
)
if not settlements:
raise exceptions.UserError(_("No valid settlements to invoice."))
return settlements.ids
return self.env.context.get("settlement_ids", [])
def _default_from_settlement(self):
return bool(self._default_settlement_ids())
journal_id = fields.Many2one(
comodel_name="account.journal",
required=True,
domain="[('type', '=', 'purchase')]",
default=lambda self: self._default_journal_id(),
)
company_id = fields.Many2one(
comodel_name="res.company", related="journal_id.company_id", readonly=True
)
product_id = fields.Many2one(
string="Product for invoicing", comodel_name="product.product", required=True
)
settlement_ids = fields.Many2many(
comodel_name="commission.settlement",
relation="commission_make_invoice_settlement_rel",
column1="wizard_id",
column2="settlement_id",
domain="[('state', '=', 'settled'),('agent_type', '=', 'agent'),"
"('company_id', '=', company_id)]",
default=lambda self: self._default_settlement_ids(),
)
from_settlement = fields.Boolean(
default=lambda self: self._default_from_settlement()
)
date = fields.Date(default=fields.Date.context_today)
grouped = fields.Boolean(string="Group invoices")
def button_create(self):
self.ensure_one()
if self.settlement_ids:
settlements = self.settlement_ids
else:
settlements = self.env["commission.settlement"].search(
[
("state", "=", "settled"),
("agent_type", "=", "agent"),
("company_id", "=", self.journal_id.company_id.id),
]
)
invoices = settlements.make_invoices(
self.journal_id,
self.product_id,
date=self.date,
grouped=self.grouped,
)
# go to results
if len(settlements):
return {
"name": _("Created Invoices"),
"type": "ir.actions.act_window",
"views": [[False, "list"], [False, "form"]],
"res_model": "account.move",
"domain": [["id", "in", invoices.ids]],
}
| 37.034091 | 3,259 |
773 |
py
|
PYTHON
|
15.0
|
# Copyright 2016 Nicola Malcontenti - Agile Business Group
# Copyright 2016 Davide Corio - Abstract
# Copyright 2021 Tecnativa - Pedro M. Baeza
# License AGPL-3 - See https://www.gnu.org/licenses/agpl-3.0.html
{
"name": "Commission Formula",
"version": "15.0.1.0.0",
"category": "Commission",
"license": "AGPL-3",
"summary": "Commissions computed by formulas",
"author": "Abstract,Odoo Community Association (OCA)",
"website": "https://github.com/OCA/commission",
"depends": ["commission"],
"data": ["views/commission_view.xml"],
"demo": ["demo/commission_demo.xml"],
"assets": {
"web.assets_backend": [
"commission_formula/static/src/css/commission_formula.css",
],
},
"installable": True,
}
| 35.136364 | 773 |
572 |
py
|
PYTHON
|
15.0
|
# © 2016 Nicola Malcontenti - Agile Business Group
# © 2016 Davide Corio - Abstract
# License AGPL-3 - See https://www.gnu.org/licenses/agpl-3.0.html
from odoo import fields, models
class Commission(models.Model):
_inherit = "commission"
commission_type = fields.Selection(
selection_add=[("formula", "Formula")], ondelete={"formula": "set default"}
)
formula = fields.Text(
default="if line._name == 'sale.order.line':\n"
" result = 0\n"
"if line._name == 'account.move.line':\n"
" result = 0\n",
)
| 30 | 570 |
1,176 |
py
|
PYTHON
|
15.0
|
# © 2016 Nicola Malcontenti - Agile Business Group
# © 2016 Davide Corio - Abstract
# Copyright 2018 Tecnativa - Pedro M. Baeza
# License AGPL-3 - See https://www.gnu.org/licenses/agpl-3.0.html
from odoo import api, models
from odoo.tools.safe_eval import safe_eval
class CommissionLineMixin(models.AbstractModel):
_inherit = "commission.line.mixin"
@api.model
def _get_formula_input_dict(self):
return {
"line": self.object_id,
"self": self,
}
def _get_commission_amount(self, commission, subtotal, product, quantity):
"""Get the commission amount for the data given. To be called by
compute methods of children models.
"""
self.ensure_one()
if (
not product.commission_free
and commission
and commission.commission_type == "formula"
):
formula = commission.formula
results = self._get_formula_input_dict()
safe_eval(formula, results, mode="exec", nocopy=True)
return float(results["result"])
return super()._get_commission_amount(commission, subtotal, product, quantity)
| 34.529412 | 1,174 |
586 |
py
|
PYTHON
|
15.0
|
# Copyright 2020 Tecnativa - Manuel Calero
# Copyright 2022 Quartile
# Copyright 2014-2022 Tecnativa - Pedro M. Baeza
{
"name": "Sales commissions",
"version": "15.0.2.1.0",
"author": "Tecnativa, Odoo Community Association (OCA)",
"category": "Sales Management",
"license": "AGPL-3",
"depends": [
"sale",
"account_commission",
],
"website": "https://github.com/OCA/commission",
"maintainers": ["pedrobaeza"],
"data": [
"security/ir.model.access.csv",
"views/sale_order_view.xml",
],
"installable": True,
}
| 27.904762 | 586 |
5,762 |
py
|
PYTHON
|
15.0
|
# Copyright 2020 Tecnativa - Manuel Calero
# Copyright 2022 Quartile
# Copyright 2016-2022 Tecnativa - Pedro M. Baeza
# License AGPL-3 - See https://www.gnu.org/licenses/agpl-3.0.html
from odoo.tests import Form, tagged
from odoo.addons.account_commission.tests.test_account_commission import (
TestAccountCommission,
)
@tagged("post_install", "-at_install")
class TestSaleCommission(TestAccountCommission):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.sale_order_model = cls.env["sale.order"]
cls.advance_inv_model = cls.env["sale.advance.payment.inv"]
cls.product.write({"invoice_policy": "order"})
def _create_sale_order(self, agent, commission):
order_form = Form(self.sale_order_model)
order_form.partner_id = self.partner
with order_form.order_line.new() as line_form:
line_form.product_id = self.product
order = order_form.save()
order.order_line.agent_ids = [
(0, 0, {"agent_id": agent.id, "commission_id": commission.id})
]
return order
def _invoice_sale_order(self, sale_order, date=None):
old_invoices = sale_order.invoice_ids
wizard = self.advance_inv_model.create({"advance_payment_method": "delivered"})
wizard.with_context(
active_model="sale.order",
active_ids=[sale_order.id],
active_id=sale_order.id,
).create_invoices()
invoice = sale_order.invoice_ids - old_invoices
if date:
invoice.invoice_date = date
invoice.date = date
return
def _create_order_and_invoice(self, agent, commission):
sale_order = self._create_sale_order(agent, commission)
sale_order.action_confirm()
self._invoice_sale_order(sale_order)
invoices = sale_order.invoice_ids
invoices.invoice_line_ids.agent_ids._compute_amount()
return sale_order
def _check_full(self, agent, commission, period, initial_count):
sale_order = self._create_order_and_invoice(agent, commission)
settlements = self._check_invoice_thru_settle(
agent, commission, period, initial_count, sale_order
)
return settlements
def test_sale_commission_gross_amount_payment(self):
self._check_full(
self.env.ref("commission.res_partner_pritesh_sale_agent"),
self.commission_section_paid,
1,
0,
)
def test_sale_commission_status(self):
# Make sure user is in English
self.env.user.lang = "en_US"
sale_order = self._create_sale_order(
self.env.ref("commission.res_partner_pritesh_sale_agent"),
self.commission_section_invoice,
)
self.assertIn("1", sale_order.order_line[0].commission_status)
self.assertNotIn("agents", sale_order.order_line[0].commission_status)
sale_order.mapped("order_line.agent_ids").unlink()
self.assertIn("No", sale_order.order_line[0].commission_status)
sale_order.order_line[0].agent_ids = [
(
0,
0,
{
"agent_id": self.env.ref(
"commission.res_partner_pritesh_sale_agent"
).id,
"commission_id": self.env.ref("commission.demo_commission").id,
},
),
(
0,
0,
{
"agent_id": self.env.ref(
"commission.res_partner_eiffel_sale_agent"
).id,
"commission_id": self.env.ref("commission.demo_commission").id,
},
),
]
self.assertIn("2", sale_order.order_line[0].commission_status)
self.assertIn("agents", sale_order.order_line[0].commission_status)
# Free
sale_order.order_line.commission_free = True
self.assertIn("free", sale_order.order_line.commission_status)
self.assertAlmostEqual(sale_order.order_line.agent_ids.amount, 0)
# test show agents buton
action = sale_order.order_line.button_edit_agents()
self.assertEqual(action["res_id"], sale_order.order_line.id)
def test_sale_commission_propagation(self):
self.partner.agent_ids = [(4, self.agent_monthly.id)]
sale_order_form = Form(self.env["sale.order"])
sale_order_form.partner_id = self.partner
with sale_order_form.order_line.new() as line_form:
line_form.product_id = self.product
line_form.product_uom_qty = 1
sale_order = sale_order_form.save()
agent = sale_order.order_line.agent_ids
self._check_propagation(agent, self.commission_net_invoice, self.agent_monthly)
# Check agent change
agent.agent_id = self.agent_quaterly
self.assertTrue(agent.commission_id, self.commission_section_invoice)
# Check recomputation
agent.unlink()
sale_order.recompute_lines_agents()
agent = sale_order.order_line.agent_ids
self._check_propagation(agent, self.commission_net_invoice, self.agent_monthly)
def test_sale_commission_invoice_line_agent(self):
sale_order = self._create_sale_order(
self.agent_monthly,
self.commission_section_invoice,
)
sale_order.action_confirm()
self._invoice_sale_order(sale_order)
inv_line = sale_order.mapped("invoice_ids.invoice_line_ids")[0]
self.assertTrue(
inv_line.agent_ids[0].commission_id, self.commission_section_invoice
)
self.assertTrue(inv_line.agent_ids[0].agent_id, self.agent_monthly)
| 40.293706 | 5,762 |
3,004 |
py
|
PYTHON
|
15.0
|
# Copyright 2014-2022 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
class SaleOrder(models.Model):
_inherit = "sale.order"
@api.depends("order_line.agent_ids.amount")
def _compute_commission_total(self):
for record in self:
record.commission_total = sum(record.mapped("order_line.agent_ids.amount"))
commission_total = fields.Float(
string="Commissions",
compute="_compute_commission_total",
store=True,
)
partner_agent_ids = fields.Many2many(
string="Agents",
comodel_name="res.partner",
compute="_compute_agents",
search="_search_agents",
)
@api.depends("partner_agent_ids", "order_line.agent_ids.agent_id")
def _compute_agents(self):
for so in self:
so.partner_agent_ids = [
(6, 0, so.mapped("order_line.agent_ids.agent_id").ids)
]
@api.model
def _search_agents(self, operator, value):
sol_agents = self.env["sale.order.line.agent"].search(
[("agent_id", operator, value)]
)
return [("id", "in", sol_agents.mapped("object_id.order_id").ids)]
def recompute_lines_agents(self):
self.mapped("order_line").recompute_agents()
class SaleOrderLine(models.Model):
_inherit = [
"sale.order.line",
"commission.mixin",
]
_name = "sale.order.line"
agent_ids = fields.One2many(comodel_name="sale.order.line.agent")
@api.depends("order_id.partner_id")
def _compute_agent_ids(self):
self.agent_ids = False # for resetting previous agents
for record in self.filtered(lambda x: x.order_id.partner_id):
if not record.commission_free:
record.agent_ids = record._prepare_agents_vals_partner(
record.order_id.partner_id, settlement_type="sale_invoice"
)
def _prepare_invoice_line(self, **optional_values):
vals = super()._prepare_invoice_line(**optional_values)
vals["agent_ids"] = [
(0, 0, {"agent_id": x.agent_id.id, "commission_id": x.commission_id.id})
for x in self.agent_ids
]
return vals
class SaleOrderLineAgent(models.Model):
_inherit = "commission.line.mixin"
_name = "sale.order.line.agent"
_description = "Agent detail of commission line in order lines"
object_id = fields.Many2one(comodel_name="sale.order.line")
@api.depends(
"commission_id",
"object_id.price_subtotal",
"object_id.product_id",
"object_id.product_uom_qty",
)
def _compute_amount(self):
for line in self:
order_line = line.object_id
line.amount = line._get_commission_amount(
line.commission_id,
order_line.price_subtotal,
order_line.product_id,
order_line.product_uom_qty,
)
| 31.957447 | 3,004 |
462 |
py
|
PYTHON
|
15.0
|
# Copyright 2020 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Sales commissions from salesman",
"version": "15.0.1.0.0",
"author": "Tecnativa, " "Odoo Community Association (OCA)",
"category": "Sales",
"website": "https://github.com/OCA/commission",
"license": "AGPL-3",
"depends": ["sale_commission"],
"data": ["views/res_partner_views.xml"],
"installable": True,
}
| 33 | 462 |
3,435 |
py
|
PYTHON
|
15.0
|
# Copyright 2020 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import exceptions
from odoo.tests import Form, TransactionCase
class TestSaleCommissionSalesman(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.product = cls.env["product.product"].create(
{"name": "Test Product 1", "list_price": 100}
)
SaleCommission = cls.env["commission"]
cls.commission_1 = SaleCommission.create(
{"name": "1% commission", "fix_qty": 1.0}
)
Partner = cls.env["res.partner"]
cls.salesman = cls.env["res.users"].create(
{"name": "Test agent", "login": "sale_comission_salesman_test"}
)
cls.agent = cls.salesman.partner_id
cls.agent.write(
{
"agent": True,
"salesman_as_agent": True,
"commission_id": cls.commission_1.id,
}
)
cls.other_agent = Partner.create(
{
"name": "Test other agent",
"agent": True,
"commission_id": cls.commission_1.id,
}
)
cls.partner = Partner.create({"name": "Partner test"})
cls.sale_order = cls.env["sale.order"].create(
{"partner_id": cls.partner.id, "user_id": cls.salesman.id}
)
cls.invoice = cls.env["account.move"].create(
{
"partner_id": cls.partner.id,
"invoice_user_id": cls.salesman.id,
"move_type": "out_invoice",
}
)
def test_check_salesman_commission(self):
with self.assertRaises(exceptions.ValidationError):
self.agent.commission_id = False
def test_sale_commission_salesman(self):
line = self.env["sale.order.line"].create(
{"order_id": self.sale_order.id, "product_id": self.product.id}
)
self.assertTrue(line.agent_ids)
self.assertTrue(line.agent_ids.agent_id, self.agent)
self.assertTrue(line.agent_ids.commission_id, self.commission_1)
def test_sale_commission_salesman_no_population(self):
self.partner.agent_ids = [(4, self.other_agent.id)]
line = self.env["sale.order.line"].create(
{"order_id": self.sale_order.id, "product_id": self.product.id}
)
self.assertTrue(len(line.agent_ids), 1)
self.assertTrue(line.agent_ids.agent_id, self.other_agent)
def test_invoice_commission_salesman(self):
invoice_form = Form(self.invoice)
with invoice_form.invoice_line_ids.new() as line_form:
line_form.product_id = self.product
invoice_form.save()
line = self.invoice.invoice_line_ids
self.assertTrue(line.agent_ids)
self.assertTrue(line.agent_ids.agent_id, self.agent)
self.assertTrue(line.agent_ids.commission_id, self.commission_1)
def test_invoice_commission_salesman_no_population(self):
self.partner.agent_ids = [(4, self.other_agent.id)]
invoice_form = Form(self.invoice)
with invoice_form.invoice_line_ids.new() as line_form:
line_form.product_id = self.product
invoice_form.save()
line = self.invoice.invoice_line_ids
self.assertTrue(line.agent_ids)
self.assertTrue(line.agent_ids.agent_id, self.other_agent)
| 39.034091 | 3,435 |
823 |
py
|
PYTHON
|
15.0
|
# Copyright 2020 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import models
class AccountMoveLine(models.Model):
_inherit = "account.move.line"
def _compute_agent_ids(self):
"""Add salesman agent if configured so and no other commission
already populated.
"""
result = super()._compute_agent_ids()
for record in self.filtered(
lambda x: x.move_id.partner_id
and x.move_id.move_type[:3] == "out"
and x.product_id
and not x.agent_ids
):
partner = self.move_id.invoice_user_id.partner_id
if partner.agent and partner.salesman_as_agent:
record.agent_ids = [(0, 0, self._prepare_agent_vals(partner))]
return result
| 34.291667 | 823 |
709 |
py
|
PYTHON
|
15.0
|
# Copyright 2020 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import models
class SaleOrdeLine(models.Model):
_inherit = "sale.order.line"
def _compute_agent_ids(self):
"""Add salesman agent if configured so and no other commission
already populated.
"""
result = super()._compute_agent_ids()
for record in self.filtered(lambda x: x.order_id.partner_id):
partner = record.order_id.user_id.partner_id
if not record.agent_ids and partner.agent and partner.salesman_as_agent:
record.agent_ids = [(0, 0, record._prepare_agent_vals(partner))]
return result
| 37.315789 | 709 |
849 |
py
|
PYTHON
|
15.0
|
# Copyright 2020 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import _, api, exceptions, fields, models
class ResPartner(models.Model):
_inherit = "res.partner"
salesman_as_agent = fields.Boolean(
string="Convert salesman into agent",
help="If the user linked to this partner is put as salesman and no "
"other commission rule is triggered, this agent will be "
"added as the commission agent",
)
@api.constrains("salesman_as_agent", "commission_id")
def _check_salesman_as_agent(self):
for record in self:
if record.salesman_as_agent and not record.commission_id:
raise exceptions.ValidationError(
_("You can't have a salesman auto-agent without commission.")
)
| 36.913043 | 849 |
640 |
py
|
PYTHON
|
15.0
|
# Copyright 2015 Therp BV (<http://therp.nl>).
# Copyright 2019 Tecnativa - Pedro M. Baeza
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
"name": "Reconcile payment orders",
"version": "15.0.1.0.0",
"author": "Therp BV, Tecnativa, Odoo Community Association (OCA)",
"license": "AGPL-3",
"website": "https://github.com/OCA/account-reconcile",
"category": "Invoicing Management",
"summary": "Automatically propose all lines generated from payment orders",
"depends": ["account_payment_order", "account_reconciliation_widget"],
"installable": True,
"maintainers": ["pedrobaeza"],
}
| 40 | 640 |
4,171 |
py
|
PYTHON
|
15.0
|
# Copyright 2019 Tecnativa - Pedro M. Baeza
# Copyright 2021 Tecnativa - João Marques
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
import odoo.tests
from odoo.addons.account_payment_order.tests.test_payment_order_inbound import (
TestPaymentOrderInboundBase,
)
@odoo.tests.tagged("post_install", "-at_install")
class TestAccountReconcilePaymentOrder(TestPaymentOrderInboundBase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.widget_obj = cls.env["account.reconciliation.widget"]
cls.bank_journal = cls.env["account.journal"].create(
{"name": "Test bank journal", "type": "bank"}
)
# Create second invoice for being sure it handles the payment order
cls.invoice2 = cls._create_customer_invoice(cls)
cls.partner2 = cls.env["res.partner"].create({"name": "Test partner 2"})
# Set correct partner in invoice
cls.invoice2.partner_id = cls.partner2.id
for line in cls.invoice2.line_ids:
line.partner_id = cls.partner2.id
cls.invoice2.payment_mode_id = cls.inbound_mode
cls.invoice2.action_post()
# Add to payment order using the wizard
cls.env["account.invoice.payment.line.multi"].with_context(
active_model="account.move", active_ids=cls.invoice2.ids
).create({}).run()
# Prepare statement
cls.statement = cls.env["account.bank.statement"].create(
{
"name": "Test statement",
"date": "2019-01-01",
"journal_id": cls.bank_journal.id,
"line_ids": [
(
0,
0,
{
"date": "2019-01-01",
"name": "Test line",
"amount": 200, # 100 * 2
"payment_ref": "payment",
},
),
],
}
)
def test_reconcile_payment_order_bank(self):
self.assertEqual(len(self.inbound_order.payment_line_ids), 2)
# Prepare payment order
self.inbound_order.draft2open()
self.inbound_order.open2generated()
self.inbound_order.generated2uploaded()
# Check widget result
res = self.widget_obj.get_bank_statement_line_data(self.statement.line_ids.ids)
self.assertEqual(len(res["lines"][0]["reconciliation_proposition"]), 2)
def test_reconcile_payment_order_transfer_account(self):
self.assertEqual(len(self.inbound_order.payment_line_ids), 2)
self.inbound_mode.write(
{
"default_journal_ids": [(4, self.bank_journal.id)],
}
)
self.assertEqual(len(self.inbound_order.payment_line_ids), 2)
# Prepare payment order
self.inbound_order.draft2open()
self.inbound_order.open2generated()
self.inbound_order.generated2uploaded()
# Check widget result
res = self.widget_obj.get_bank_statement_line_data(self.statement.line_ids.ids)
proposition = res["lines"][0]["reconciliation_proposition"]
self.assertEqual(len(proposition), 2)
# Reconcile that entries and check again
st_line_vals = res["lines"][0]["st_line"]
self.widget_obj.process_move_lines(
data=[
{
"type": "",
"mv_line_ids": [proposition[0]["id"], proposition[1]["id"]],
"new_mv_line_dicts": [
{
"name": st_line_vals["name"],
"credit": st_line_vals["amount"],
"debit": 0,
"account_id": st_line_vals["account_id"][0],
"journal_id": st_line_vals["journal_id"],
}
],
}
],
)
res2 = self.widget_obj.get_bank_statement_line_data(
self.statement.line_ids.ids,
)
self.assertNotEqual(res, res2)
| 40.485437 | 4,170 |
2,862 |
py
|
PYTHON
|
15.0
|
# Copyright 2019 Tecnativa - Pedro M. Baeza
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from odoo import api, models
class AccountReconciliationWidget(models.AbstractModel):
_inherit = "account.reconciliation.widget"
@api.model
def _get_possible_payment_orders_for_statement_line(self, st_line):
"""Find orders that might be candidates for matching a statement
line.
"""
return self.env["account.payment.order"].search(
[
("total_company_currency", "=", st_line.amount),
("state", "in", ["done", "uploaded"]),
]
)
@api.model
def _get_reconcile_lines_from_order(self, st_line, order, excluded_ids=None):
"""Return lines to reconcile our statement line with."""
aml_obj = self.env["account.move.line"]
lines = aml_obj
for payment in order.payment_ids:
lines |= payment.move_id.line_ids.filtered(
lambda x: x.account_id != payment.destination_account_id
and x.partner_id == payment.partner_id
)
return (lines - aml_obj.browse(excluded_ids)).filtered(
lambda x: not x.reconciled
)
def _prepare_proposition_from_orders(self, st_line, orders, excluded_ids=None):
"""Fill with the expected format the reconciliation proposition
for the given statement line and possible payment orders.
"""
target_currency = (
st_line.currency_id
or st_line.journal_id.currency_id
or st_line.journal_id.company_id.currency_id
)
for order in orders:
elegible_lines = self._get_reconcile_lines_from_order(
st_line,
order,
excluded_ids=excluded_ids,
)
if elegible_lines:
return self._prepare_move_lines(
elegible_lines,
target_currency=target_currency,
target_date=st_line.date,
)
return []
def get_bank_statement_line_data(self, st_line_ids, excluded_ids=None):
res = super().get_bank_statement_line_data(
st_line_ids,
excluded_ids=excluded_ids,
)
st_line_obj = self.env["account.bank.statement.line"]
for line_vals in res.get("lines", []):
st_line = st_line_obj.browse(line_vals["st_line"]["id"])
orders = self._get_possible_payment_orders_for_statement_line(st_line)
proposition_vals = self._prepare_proposition_from_orders(
st_line,
orders,
excluded_ids=excluded_ids,
)
if proposition_vals:
line_vals["reconciliation_proposition"] = proposition_vals
return res
| 38.16 | 2,862 |
1,243 |
py
|
PYTHON
|
15.0
|
# Copyright 2020 Ozono Multimedia - Iván Antón
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "account_reconciliation_widget",
"version": "15.0.1.2.9",
"category": "Accounting",
"license": "AGPL-3",
"summary": "Account reconciliation widget",
"author": "Odoo, Ozono Multimedia, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/account-reconcile",
"depends": ["account"],
"development_status": "Production/Stable",
"data": [
"security/ir.model.access.csv",
"wizards/res_config_settings_views.xml",
"views/account_view.xml",
"views/account_bank_statement_view.xml",
"views/account_journal_dashboard_view.xml",
],
"assets": {
"web.assets_backend": [
"account_reconciliation_widget/static/src/scss/account_reconciliation.scss",
"account_reconciliation_widget/static/src/js/reconciliation/**/*",
],
"web.qunit_suite_tests": [
"account_reconciliation_widget/static/tests/**/*",
],
"web.assets_qweb": [
"account_reconciliation_widget/static/src/xml/account_reconciliation.xml",
],
},
"installable": True,
}
| 36.5 | 1,241 |
8,171 |
py
|
PYTHON
|
15.0
|
import logging
import time
import requests
import odoo.tests
from odoo.tools.misc import NON_BREAKING_SPACE
from odoo.addons.account.tests.common import TestAccountReconciliationCommon
_logger = logging.getLogger(__name__)
@odoo.tests.tagged("post_install", "-at_install")
class TestUi(odoo.tests.HttpCase):
def test_01_admin_bank_statement_reconciliation(self):
bank_stmt_name = "BNK/%s/0001" % time.strftime("%Y")
bank_stmt_line = (
self.env["account.bank.statement"]
.search([("name", "=", bank_stmt_name)])
.mapped("line_ids")
)
if not bank_stmt_line:
_logger.info(
"Tour bank_statement_reconciliation skipped: bank statement %s "
"not found." % bank_stmt_name
)
return
admin = self.env.ref("base.user_admin")
# Tour can't be run if the setup if not the generic one.
generic_coa = self.env.ref(
"l10n_generic_coa.configurable_chart_template", raise_if_not_found=False
)
if (
not admin.company_id.chart_template_id
or admin.company_id.chart_template_id != generic_coa
):
_logger.info(
"Tour bank_statement_reconciliation skipped: generic coa not found."
)
return
# To be able to test reconciliation, admin user must have access to
# accounting features, so we give him the right group for that
admin.write({"groups_id": [(4, self.env.ref("account.group_account_user").id)]})
payload = {
"action": "bank_statement_reconciliation_view",
"statement_line_ids[]": bank_stmt_line.ids,
}
prep = requests.models.PreparedRequest()
prep.prepare_url(url="http://localhost/web#", params=payload)
self.start_tour(
prep.url.replace("http://localhost", "").replace("?", "#"),
"bank_statement_reconciliation",
login="admin",
)
@odoo.tests.tagged("post_install", "-at_install")
class TestReconciliationWidget(TestAccountReconciliationCommon):
@classmethod
def setUpClass(cls, chart_template_ref=None):
super().setUpClass(chart_template_ref=chart_template_ref)
cls.acc_bank_stmt_model = cls.env["account.bank.statement"]
cls.acc_bank_stmt_line_model = cls.env["account.bank.statement.line"]
def test_statement_suggestion_other_currency(self):
# company currency is EUR
# payment in USD
invoice = self.create_invoice(
invoice_amount=50, currency_id=self.currency_usd_id
)
# journal currency in USD
bank_stmt = self.acc_bank_stmt_model.create(
{
"journal_id": self.bank_journal_usd.id,
"date": time.strftime("%Y-07-15"),
"name": "payment %s" % invoice.name,
}
)
bank_stmt_line = self.acc_bank_stmt_line_model.create(
{
"payment_ref": "payment",
"statement_id": bank_stmt.id,
"partner_id": self.partner_agrolait_id,
"amount": 50,
"date": time.strftime("%Y-07-15"),
}
)
result = self.env["account.reconciliation.widget"].get_bank_statement_line_data(
bank_stmt_line.ids
)
self.assertEqual(
result["lines"][0]["reconciliation_proposition"][0]["amount_str"],
f"${NON_BREAKING_SPACE}50.00",
)
def test_filter_partner1(self):
inv1 = self.create_invoice(currency_id=self.currency_euro_id)
inv2 = self.create_invoice(currency_id=self.currency_euro_id)
partner = inv1.partner_id
receivable1 = inv1.line_ids.filtered(
lambda l: l.account_id.internal_type == "receivable"
)
receivable2 = inv2.line_ids.filtered(
lambda l: l.account_id.internal_type == "receivable"
)
bank_stmt = self.acc_bank_stmt_model.create(
{
"company_id": self.env.ref("base.main_company").id,
"journal_id": self.bank_journal_euro.id,
"date": time.strftime("%Y-07-15"),
"name": "test",
}
)
bank_stmt_line = self.acc_bank_stmt_line_model.create(
{
"name": "testLine",
"statement_id": bank_stmt.id,
"amount": 100,
"date": time.strftime("%Y-07-15"),
"payment_ref": "test",
}
)
# This is like input a partner in the widget
mv_lines_rec = self.env[
"account.reconciliation.widget"
].get_move_lines_for_bank_statement_line(
bank_stmt_line.id,
partner_id=partner.id,
excluded_ids=[],
search_str=False,
mode="rp",
)
mv_lines_ids = [line["id"] for line in mv_lines_rec]
self.assertIn(receivable1.id, mv_lines_ids)
self.assertIn(receivable2.id, mv_lines_ids)
# With a partner set, type the invoice reference in the filter
mv_lines_rec = self.env[
"account.reconciliation.widget"
].get_move_lines_for_bank_statement_line(
bank_stmt_line.id,
partner_id=partner.id,
excluded_ids=[],
search_str=inv1.payment_reference,
mode="rp",
)
mv_lines_ids = [line["id"] for line in mv_lines_rec]
self.assertIn(receivable1.id, mv_lines_ids)
self.assertNotIn(receivable2.id, mv_lines_ids)
# Without a partner set, type "deco" in the filter
mv_lines_rec = self.env[
"account.reconciliation.widget"
].get_move_lines_for_bank_statement_line(
bank_stmt_line.id,
partner_id=False,
excluded_ids=[],
search_str="deco",
mode="rp",
)
mv_lines_ids = [line["id"] for line in mv_lines_rec]
self.assertIn(receivable1.id, mv_lines_ids)
self.assertIn(receivable2.id, mv_lines_ids)
# With a partner set, type "deco" in the filter and click on the first
# receivable
mv_lines_rec = self.env[
"account.reconciliation.widget"
].get_move_lines_for_bank_statement_line(
bank_stmt_line.id,
partner_id=partner.id,
excluded_ids=[receivable1.id],
search_str="deco",
mode="rp",
)
mv_lines_ids = [line["id"] for line in mv_lines_rec]
self.assertNotIn(receivable1.id, mv_lines_ids)
self.assertIn(receivable2.id, mv_lines_ids)
def test_partner_name_with_parent(self):
parent_partner = self.env["res.partner"].create(
{
"name": "test",
}
)
child_partner = self.env["res.partner"].create(
{
"name": "test",
"parent_id": parent_partner.id,
"type": "delivery",
}
)
self.create_invoice_partner(
currency_id=self.currency_euro_id, partner_id=child_partner.id
)
bank_stmt = self.acc_bank_stmt_model.create(
{
"company_id": self.env.ref("base.main_company").id,
"journal_id": self.bank_journal_euro.id,
"date": time.strftime("%Y-07-15"),
"name": "test",
}
)
bank_stmt_line = self.acc_bank_stmt_line_model.create(
{
"name": "testLine",
"statement_id": bank_stmt.id,
"amount": 100,
"date": time.strftime("%Y-07-15"),
"payment_ref": "test",
"partner_name": "test",
}
)
bkstmt_data = self.env[
"account.reconciliation.widget"
].get_bank_statement_line_data(bank_stmt_line.ids)
self.assertEqual(len(bkstmt_data["lines"]), 1)
self.assertEqual(bkstmt_data["lines"][0]["partner_id"], parent_partner.id)
| 33.904564 | 8,171 |
5,499 |
py
|
PYTHON
|
15.0
|
from odoo import _, fields, models
from odoo.exceptions import UserError
class AccountMoveLine(models.Model):
_inherit = "account.move.line"
def _create_writeoff(self, writeoff_vals):
"""Create a writeoff move per journal for the account.move.lines in
self. If debit/credit is not specified in vals, the writeoff amount
will be computed as the sum of amount_residual of the given recordset.
:param writeoff_vals: list of dicts containing values suitable for
account_move_line.create(). The data in vals will be processed to
create both writeoff account.move.line and their enclosing
account.move.
"""
def compute_writeoff_counterpart_vals(values):
line_values = values.copy()
line_values["debit"], line_values["credit"] = (
line_values["credit"],
line_values["debit"],
)
if "amount_currency" in values:
line_values["amount_currency"] = -line_values["amount_currency"]
return line_values
# Group writeoff_vals by journals
writeoff_dict = {}
for val in writeoff_vals:
journal_id = val.get("journal_id", False)
if not writeoff_dict.get(journal_id, False):
writeoff_dict[journal_id] = [val]
else:
writeoff_dict[journal_id].append(val)
partner_id = (
self.env["res.partner"]._find_accounting_partner(self[0].partner_id).id
)
company_currency = self[0].account_id.company_id.currency_id
writeoff_currency = self[0].account_id.currency_id or company_currency
line_to_reconcile = self.env["account.move.line"]
# Iterate and create one writeoff by journal
writeoff_moves = self.env["account.move"]
for journal_id, lines in writeoff_dict.items():
total = 0
total_currency = 0
writeoff_lines = []
date = fields.Date.today()
for vals in lines:
# Check and complete vals
if "account_id" not in vals or "journal_id" not in vals:
raise UserError(
_(
"It is mandatory to specify an account and a "
"journal to create a write-off."
)
)
if ("debit" in vals) ^ ("credit" in vals):
raise UserError(_("Either pass both debit and credit or none."))
if "date" not in vals:
vals["date"] = self._context.get("date_p") or fields.Date.today()
vals["date"] = fields.Date.to_date(vals["date"])
if vals["date"] and vals["date"] < date:
date = vals["date"]
if "name" not in vals:
vals["name"] = self._context.get("comment") or _("Write-Off")
if "analytic_account_id" not in vals:
vals["analytic_account_id"] = self.env.context.get(
"analytic_id", False
)
# compute the writeoff amount if not given
if "credit" not in vals and "debit" not in vals:
amount = sum(r.amount_residual for r in self)
vals["credit"] = amount > 0 and amount or 0.0
vals["debit"] = amount < 0 and abs(amount) or 0.0
vals["partner_id"] = partner_id
total += vals["debit"] - vals["credit"]
if (
"amount_currency" not in vals
and writeoff_currency != company_currency
):
vals["currency_id"] = writeoff_currency.id
sign = 1 if vals["debit"] > 0 else -1
vals["amount_currency"] = sign * abs(
sum(r.amount_residual_currency for r in self)
)
total_currency += vals["amount_currency"]
writeoff_lines.append(compute_writeoff_counterpart_vals(vals))
# Create balance line
writeoff_lines.append(
{
"name": _("Write-Off"),
"debit": total > 0 and total or 0.0,
"credit": total < 0 and -total or 0.0,
"amount_currency": total_currency,
"currency_id": total_currency and writeoff_currency.id or False,
"journal_id": journal_id,
"account_id": self[0].account_id.id,
"partner_id": partner_id,
}
)
# Create the move
writeoff_move = self.env["account.move"].create(
{
"journal_id": journal_id,
"date": date,
"state": "draft",
"line_ids": [(0, 0, line) for line in writeoff_lines],
}
)
writeoff_moves += writeoff_move
line_to_reconcile += writeoff_move.line_ids.filtered(
lambda r: r.account_id == self[0].account_id
).sorted(key="id")[-1:]
# post all the writeoff moves at once
if writeoff_moves:
writeoff_moves.action_post()
# Return the writeoff move.line which is to be reconciled
return line_to_reconcile
| 43.299213 | 5,499 |
47,665 |
py
|
PYTHON
|
15.0
|
import copy
import logging
from psycopg2 import sql
from odoo import _, api, models
from odoo.exceptions import UserError
from odoo.osv import expression
from odoo.tools.misc import format_date, formatLang, parse_date
_logger = logging.getLogger(__name__)
class AccountReconciliation(models.AbstractModel):
_name = "account.reconciliation.widget"
_description = "Account Reconciliation widget"
####################################################
# Public
####################################################
@api.model
def process_bank_statement_line(self, st_line_ids, data):
"""Handles data sent from the bank statement reconciliation widget
(and can otherwise serve as an old-API bridge)
:param st_line_ids
:param list of dicts data: must contains the keys
'counterpart_aml_dicts', 'payment_aml_ids' and 'new_aml_dicts',
whose value is the same as described in process_reconciliation
except that ids are used instead of recordsets.
:returns dict: used as a hook to add additional keys.
"""
st_lines = self.env["account.bank.statement.line"].browse(st_line_ids)
AccountMoveLine = self.env["account.move.line"]
ctx = dict(self._context, force_price_include=False)
processed_moves = self.env["account.move"]
for st_line, datum in zip(st_lines, copy.deepcopy(data)):
payment_aml_rec = AccountMoveLine.browse(datum.get("payment_aml_ids", []))
for aml_dict in datum.get("counterpart_aml_dicts", []):
aml_dict["move_line"] = AccountMoveLine.browse(
aml_dict["counterpart_aml_id"]
)
del aml_dict["counterpart_aml_id"]
if datum.get("partner_id") is not None:
st_line.write({"partner_id": datum["partner_id"]})
ctx["default_to_check"] = datum.get("to_check")
moves = st_line.with_context(**ctx).process_reconciliation(
datum.get("counterpart_aml_dicts", []),
payment_aml_rec,
datum.get("new_aml_dicts", []),
)
processed_moves = processed_moves | moves
return {
"moves": processed_moves.ids,
"statement_line_ids": processed_moves.mapped(
"line_ids.statement_line_id"
).ids,
}
@api.model
def get_move_lines_for_bank_statement_line(
self,
st_line_id,
partner_id=None,
excluded_ids=None,
search_str=False,
offset=0,
limit=None,
mode=None,
):
"""Returns move lines for the bank statement reconciliation widget,
formatted as a list of dicts
:param st_line_id: ids of the statement lines
:param partner_id: optional partner id to select only the moves
line corresponding to the partner
:param excluded_ids: optional move lines ids excluded from the
result
:param search_str: optional search (can be the amout, display_name,
partner name, move line name)
:param offset: useless but kept in stable to preserve api
:param limit: number of the result to search
:param mode: 'rp' for receivable/payable or 'other'
"""
st_line = self.env["account.bank.statement.line"].browse(st_line_id)
# Blue lines = payment on bank account not assigned to a statement yet
aml_accounts = [
st_line.journal_id.default_account_id.id,
]
if partner_id is None:
partner_id = st_line.partner_id.id
domain = self._domain_move_lines_for_reconciliation(
st_line,
aml_accounts,
partner_id,
excluded_ids=excluded_ids,
search_str=search_str,
mode=mode,
)
from_clause, where_clause, where_clause_params = (
self.env["account.move.line"]._where_calc(domain).get_sql()
)
query_str = sql.SQL(
"""
SELECT "account_move_line".id, COUNT(*) OVER() FROM {from_clause}
{where_str}
ORDER BY ("account_move_line".debit -
"account_move_line".credit) = {amount} DESC,
"account_move_line".date_maturity ASC,
"account_move_line".id ASC
{limit_str}
""".format(
from_clause=from_clause,
where_str=where_clause and (" WHERE %s" % where_clause) or "",
amount=st_line.amount,
limit_str=limit and " LIMIT %s" or "",
)
)
params = where_clause_params + (limit and [limit] or [])
self.env["account.move"].flush()
self.env["account.move.line"].flush()
self.env["account.bank.statement"].flush()
self._cr.execute(query_str, params)
res = self._cr.fetchall()
try:
# All records will have the same count value, just get the 1st one
recs_count = res[0][1]
except IndexError:
recs_count = 0
aml_recs = self.env["account.move.line"].browse([i[0] for i in res])
target_currency = (
st_line.currency_id
or st_line.journal_id.currency_id
or st_line.journal_id.company_id.currency_id
)
return self._prepare_move_lines(
aml_recs,
target_currency=target_currency,
target_date=st_line.date,
recs_count=recs_count,
)
@api.model
def _get_bank_statement_line_partners(self, st_lines):
params = []
# Add the res.partner.ban's IR rules. In case partners are not shared
# between companies, identical bank accounts may exist in a company we
# don't have access to.
ir_rules_query = self.env["res.partner.bank"]._where_calc([])
self.env["res.partner.bank"]._apply_ir_rules(ir_rules_query, "read")
from_clause, where_clause, where_clause_params = ir_rules_query.get_sql()
if where_clause:
where_bank = ("AND %s" % where_clause).replace("res_partner_bank", "bank")
params += where_clause_params
else:
where_bank = ""
# Add the res.partner's IR rules. In case partners are not shared
# between companies, identical partners may exist in a company we don't
# have access to.
ir_rules_query = self.env["res.partner"]._where_calc([])
self.env["res.partner"]._apply_ir_rules(ir_rules_query, "read")
from_clause, where_clause, where_clause_params = ir_rules_query.get_sql()
if where_clause:
where_partner = ("AND %s" % where_clause).replace("res_partner", "p3")
params += where_clause_params
else:
where_partner = ""
query = """
SELECT
st_line.id AS id,
COALESCE(p1.id,p2.id,p3.id) AS partner_id
FROM account_bank_statement_line st_line
"""
query += "INNER JOIN account_move m ON m.id = st_line.move_id \n"
query += (
"LEFT JOIN res_partner_bank bank ON bank.id = m.partner_bank_id OR "
"bank.sanitized_acc_number "
"ILIKE regexp_replace(st_line.account_number, '\\W+', '', 'g') %s\n"
% (where_bank)
)
query += "LEFT JOIN res_partner p1 ON st_line.partner_id=p1.id \n"
query += "LEFT JOIN res_partner p2 ON bank.partner_id=p2.id \n"
# By definition the commercial partner_id doesn't have a parent_id set
query += (
"LEFT JOIN res_partner p3 ON p3.name ILIKE st_line.partner_name %s "
"AND p3.parent_id is NULL \n" % (where_partner)
)
query += "WHERE st_line.id IN %s"
params += [tuple(st_lines.ids)]
self._cr.execute(query, params)
result = {}
for res in self._cr.dictfetchall():
result[res["id"]] = res["partner_id"]
return result
@api.model
def get_bank_statement_line_data(self, st_line_ids, excluded_ids=None):
"""Returns the data required to display a reconciliation widget, for
each statement line in self
:param st_line_id: ids of the statement lines
:param excluded_ids: optional move lines ids excluded from the
result
"""
results = {
"lines": [],
"value_min": 0,
"value_max": 0,
"reconciled_aml_ids": [],
}
if not st_line_ids:
return results
excluded_ids = excluded_ids or []
# Make a search to preserve the table's order.
bank_statement_lines = self.env["account.bank.statement.line"].search(
[("id", "in", st_line_ids)]
)
results["value_max"] = len(bank_statement_lines)
reconcile_model = self.env["account.reconcile.model"].search(
[("rule_type", "!=", "writeoff_button")]
)
# Search for missing partners when opening the reconciliation widget.
if bank_statement_lines:
partner_map = self._get_bank_statement_line_partners(bank_statement_lines)
matching_amls = reconcile_model._apply_rules(
bank_statement_lines, excluded_ids=excluded_ids, partner_map=partner_map
)
# Iterate on st_lines to keep the same order in the results list.
bank_statements_left = self.env["account.bank.statement"]
for line in bank_statement_lines:
if matching_amls[line.id].get("status") == "reconciled":
reconciled_move_lines = matching_amls[line.id].get("reconciled_lines")
results["value_min"] += 1
results["reconciled_aml_ids"] += (
reconciled_move_lines and reconciled_move_lines.ids or []
)
else:
aml_ids = matching_amls[line.id]["aml_ids"]
bank_statements_left += line.statement_id
target_currency = (
line.currency_id
or line.journal_id.currency_id
or line.journal_id.company_id.currency_id
)
amls = aml_ids and self.env["account.move.line"].browse(aml_ids)
line_vals = {
"st_line": self._get_statement_line(line),
"reconciliation_proposition": aml_ids
and self._prepare_move_lines(
amls, target_currency=target_currency, target_date=line.date
)
or [],
"model_id": matching_amls[line.id].get("model")
and matching_amls[line.id]["model"].id,
"write_off": matching_amls[line.id].get("status") == "write_off",
}
if not line.partner_id:
partner = False
if matching_amls[line.id].get("partner"):
partner = matching_amls[line.id]["partner"]
elif partner_map.get(line.id):
partner = self.env["res.partner"].browse(partner_map[line.id])
if partner:
line_vals.update(
{
"partner_id": partner.id,
"partner_name": partner.name,
}
)
results["lines"].append(line_vals)
return results
@api.model
def get_bank_statement_data(self, bank_statement_line_ids, srch_domain=None):
"""Get statement lines of the specified statements or all unreconciled
statement lines and try to automatically reconcile them / find them
a partner.
Return ids of statement lines left to reconcile and other data for
the reconciliation widget.
:param bank_statement_line_ids: ids of the bank statement lines
"""
if not bank_statement_line_ids:
return {}
bank_statements = (
self.env["account.bank.statement.line"]
.browse(bank_statement_line_ids)
.mapped("statement_id")
)
query = """
SELECT line.id
FROM account_bank_statement_line line
LEFT JOIN res_partner p on p.id = line.partner_id
INNER JOIN account_bank_statement st ON line.statement_id = st.id
AND st.state = 'posted'
WHERE line.is_reconciled = FALSE
AND line.amount != 0.0
AND line.id IN %(ids)s
GROUP BY line.id
"""
self.env.cr.execute(query, {"ids": tuple(bank_statement_line_ids)})
domain = [["id", "in", [line.get("id") for line in self.env.cr.dictfetchall()]]]
if srch_domain is not None:
domain += srch_domain
bank_statement_lines = self.env["account.bank.statement.line"].search(domain)
results = self.get_bank_statement_line_data(bank_statement_lines.ids)
bank_statement_lines_left = self.env["account.bank.statement.line"].browse(
[line["st_line"]["id"] for line in results["lines"]]
)
bank_statements_left = bank_statement_lines_left.mapped("statement_id")
results.update(
{
"statement_id": len(bank_statements_left) == 1
and bank_statements_left.id
or False,
"statement_name": len(bank_statements_left) == 1
and bank_statements_left.name
or False,
"journal_id": bank_statements
and bank_statements[0].journal_id.id
or False,
"notifications": [],
}
)
if len(results["lines"]) < len(bank_statement_lines):
results["notifications"].append(
{
"type": "info",
"template": "reconciliation.notification.reconciled",
"reconciled_aml_ids": results["reconciled_aml_ids"],
"nb_reconciled_lines": results["value_min"],
"details": {
"name": _("Journal Items"),
"model": "account.move.line",
"ids": results["reconciled_aml_ids"],
},
}
)
return results
@api.model
def get_move_lines_for_manual_reconciliation(
self,
account_id,
partner_id=False,
excluded_ids=None,
search_str=False,
offset=0,
limit=None,
target_currency_id=False,
):
"""Returns unreconciled move lines for an account or a partner+account,
formatted for the manual reconciliation widget"""
Account_move_line = self.env["account.move.line"]
Account = self.env["account.account"]
Currency = self.env["res.currency"]
domain = self._domain_move_lines_for_manual_reconciliation(
account_id, partner_id, excluded_ids, search_str
)
recs_count = Account_move_line.search_count(domain)
lines = Account_move_line.search(
domain, limit=limit, order="date_maturity desc, id desc"
)
if target_currency_id:
target_currency = Currency.browse(target_currency_id)
else:
account = Account.browse(account_id)
target_currency = account.currency_id or account.company_id.currency_id
return self._prepare_move_lines(
lines, target_currency=target_currency, recs_count=recs_count
)
@api.model
def get_all_data_for_manual_reconciliation(self, partner_ids, account_ids):
"""Returns the data required for the invoices & payments matching of
partners/accounts.
If an argument is None, fetch all related reconciliations. Use [] to
fetch nothing.
"""
MoveLine = self.env["account.move.line"]
aml_ids = (
self._context.get("active_ids")
and self._context.get("active_model") == "account.move.line"
and tuple(self._context.get("active_ids"))
)
if aml_ids:
aml = MoveLine.browse(aml_ids)
account = aml[0].account_id
currency = account.currency_id or account.company_id.currency_id
return {
"accounts": [
{
"reconciliation_proposition": self._prepare_move_lines(
aml, target_currency=currency
),
"company_id": account.company_id.id,
"currency_id": currency.id,
"mode": "accounts",
"account_id": account.id,
"account_name": account.name,
"account_code": account.code,
}
],
"customers": [],
"suppliers": [],
}
# If we have specified partner_ids, don't return the list of
# reconciliation for specific accounts as it will show entries that are
# not reconciled with other partner. Asking for a specific partner on a
# specific account is never done.
accounts_data = []
if not partner_ids or not any(partner_ids):
accounts_data = self.get_data_for_manual_reconciliation(
"account", account_ids
)
return {
"customers": self.get_data_for_manual_reconciliation(
"partner", partner_ids, "receivable"
),
"suppliers": self.get_data_for_manual_reconciliation(
"partner", partner_ids, "payable"
),
"accounts": accounts_data,
}
@api.model
def get_data_for_manual_reconciliation(
self, res_type, res_ids=None, account_type=None
):
"""Returns the data required for the invoices & payments matching of
partners/accounts (list of dicts).
If no res_ids is passed, returns data for all partners/accounts that can
be reconciled.
:param res_type: either 'partner' or 'account'
:param res_ids: ids of the partners/accounts to reconcile, use None to
fetch data indiscriminately of the id, use [] to prevent from
fetching any data at all.
:param account_type: if a partner is both customer and vendor, you can
use 'payable' to reconcile the vendor-related journal entries and
'receivable' for the customer-related entries.
"""
Account = self.env["account.account"]
Partner = self.env["res.partner"]
if res_ids is not None and len(res_ids) == 0:
# Note : this short-circuiting is better for performances, but also
# required since postgresql doesn't implement empty list (so 'AND id
# in ()' is useless)
return []
res_ids = res_ids and tuple(res_ids)
assert res_type in ("partner", "account")
assert account_type in ("payable", "receivable", None)
is_partner = res_type == "partner"
res_alias = is_partner and "p" or "a"
aml_ids = (
self._context.get("active_ids")
and self._context.get("active_model") == "account.move.line"
and tuple(self._context.get("active_ids"))
)
all_entries = self._context.get("all_entries", False)
all_entries_query = """
AND EXISTS (
SELECT NULL
FROM account_move_line l
JOIN account_move move ON l.move_id = move.id
JOIN account_journal journal ON l.journal_id = journal.id
WHERE l.account_id = a.id
{inner_where}
AND l.amount_residual != 0
AND move.state = 'posted'
)
""".format(
inner_where=is_partner and "AND l.partner_id = p.id" or " "
)
only_dual_entries_query = """
AND EXISTS (
SELECT NULL
FROM account_move_line l
JOIN account_move move ON l.move_id = move.id
JOIN account_journal journal ON l.journal_id = journal.id
WHERE l.account_id = a.id
{inner_where}
AND l.amount_residual > 0
AND move.state = 'posted'
)
AND EXISTS (
SELECT NULL
FROM account_move_line l
JOIN account_move move ON l.move_id = move.id
JOIN account_journal journal ON l.journal_id = journal.id
WHERE l.account_id = a.id
{inner_where}
AND l.amount_residual < 0
AND move.state = 'posted'
)
""".format(
inner_where=is_partner and "AND l.partner_id = p.id" or " "
)
query = sql.SQL(
"""
SELECT {select} account_id, account_name, account_code, max_date
FROM (
SELECT {inner_select}
a.id AS account_id,
a.name AS account_name,
a.code AS account_code,
MAX(l.write_date) AS max_date
FROM
account_move_line l
RIGHT JOIN account_account a ON (a.id = l.account_id)
RIGHT JOIN account_account_type at
ON (at.id = a.user_type_id)
{inner_from}
WHERE
a.reconcile IS TRUE
AND l.full_reconcile_id is NULL
{where1}
{where2}
{where3}
AND l.company_id = {company_id}
{where4}
{where5}
GROUP BY {group_by1} a.id, a.name, a.code {group_by2}
{order_by}
) as s
{outer_where}
""".format(
select=is_partner
and "partner_id, partner_name, to_char(last_time_entries_checked, "
"'YYYY-MM-DD') AS last_time_entries_checked,"
or " ",
inner_select=is_partner
and "p.id AS partner_id, p.name AS partner_name, "
"p.last_time_entries_checked AS last_time_entries_checked,"
or " ",
inner_from=is_partner
and "RIGHT JOIN res_partner p ON (l.partner_id = p.id)"
or " ",
where1=is_partner
and " "
or "AND ((at.type <> 'payable' AND at.type <> 'receivable') "
"OR l.partner_id IS NULL)",
where2=account_type and "AND at.type = %(account_type)s" or "",
where3=res_ids and "AND " + res_alias + ".id in %(res_ids)s" or "",
company_id=self.env.company.id,
where4=aml_ids and "AND l.id IN %(aml_ids)s" or " ",
where5=all_entries and all_entries_query or only_dual_entries_query,
group_by1=is_partner and "l.partner_id, p.id," or " ",
group_by2=is_partner and ", p.last_time_entries_checked" or " ",
order_by=is_partner
and "ORDER BY p.last_time_entries_checked"
or "ORDER BY a.code",
outer_where=is_partner
and "WHERE (last_time_entries_checked IS NULL "
"OR max_date > last_time_entries_checked)"
or " ",
)
)
self.env["account.move.line"].flush()
self.env["account.account"].flush()
self.env.cr.execute(query, locals())
# Apply ir_rules by filtering out
rows = self.env.cr.dictfetchall()
ids = [x["account_id"] for x in rows]
allowed_ids = set(Account.browse(ids).ids)
rows = [row for row in rows if row["account_id"] in allowed_ids]
if is_partner:
ids = [x["partner_id"] for x in rows]
allowed_ids = set(Partner.browse(ids).ids)
rows = [row for row in rows if row["partner_id"] in allowed_ids]
# Keep mode for future use in JS
if res_type == "account":
mode = "accounts"
else:
mode = "customers" if account_type == "receivable" else "suppliers"
# Fetch other data
for row in rows:
account = Account.browse(row["account_id"])
currency = account.currency_id or account.company_id.currency_id
row["currency_id"] = currency.id
partner_id = is_partner and row["partner_id"] or None
rec_prop = (
aml_ids
and self.env["account.move.line"].browse(aml_ids)
or self._get_move_line_reconciliation_proposition(
account.id, partner_id
)
)
row["reconciliation_proposition"] = self._prepare_move_lines(
rec_prop, target_currency=currency
)
row["mode"] = mode
row["company_id"] = account.company_id.id
# Return the partners with a reconciliation proposition first, since
# they are most likely to be reconciled.
return [r for r in rows if r["reconciliation_proposition"]] + [
r for r in rows if not r["reconciliation_proposition"]
]
@api.model
def process_move_lines(self, data):
"""Used to validate a batch of reconciliations in a single call
:param data: list of dicts containing:
- 'type': either 'partner' or 'account'
- 'id': id of the affected res.partner or account.account
- 'mv_line_ids': ids of existing account.move.line to reconcile
- 'new_mv_line_dicts': list of dicts containing values suitable for
account_move_line.create()
"""
Partner = self.env["res.partner"]
for datum in data:
if (
len(datum["mv_line_ids"]) >= 1
or len(datum["mv_line_ids"]) + len(datum["new_mv_line_dicts"]) >= 2
):
self._process_move_lines(
datum["mv_line_ids"], datum["new_mv_line_dicts"]
)
if datum["type"] == "partner":
partners = Partner.browse(datum["id"])
partners.mark_as_reconciled()
####################################################
# Private
####################################################
def _str_domain_for_mv_line(self, search_str):
return [
"|",
("account_id.code", "ilike", search_str),
"|",
("move_id.name", "ilike", search_str),
"|",
("move_id.ref", "ilike", search_str),
"|",
("date_maturity", "like", parse_date(self.env, search_str)),
"&",
("name", "!=", "/"),
("name", "ilike", search_str),
]
@api.model
def _domain_move_lines(self, search_str):
"""Returns the domain from the search_str search
:param search_str: search string
"""
if not search_str:
return []
str_domain = self._str_domain_for_mv_line(search_str)
if search_str[0] in ["-", "+"]:
try:
amounts_str = search_str.split("|")
for amount_str in amounts_str:
amount = (
amount_str[0] == "-"
and float(amount_str)
or float(amount_str[1:])
)
amount_domain = [
"|",
("amount_residual", "=", amount),
"|",
("amount_residual_currency", "=", amount),
"|",
(
amount_str[0] == "-" and "credit" or "debit",
"=",
float(amount_str[1:]),
),
("amount_currency", "=", amount),
]
str_domain = expression.OR([str_domain, amount_domain])
except Exception:
_logger.warning(Exception)
else:
try:
amount = float(search_str)
amount_domain = [
"|",
("amount_residual", "=", amount),
"|",
("amount_residual_currency", "=", amount),
"|",
("amount_residual", "=", -amount),
"|",
("amount_residual_currency", "=", -amount),
"&",
("account_id.internal_type", "=", "liquidity"),
"|",
"|",
"|",
("debit", "=", amount),
("credit", "=", amount),
("amount_currency", "=", amount),
("amount_currency", "=", -amount),
]
str_domain = expression.OR([str_domain, amount_domain])
except Exception:
_logger.warning(Exception)
return str_domain
@api.model
def _domain_move_lines_for_reconciliation(
self,
st_line,
aml_accounts,
partner_id,
excluded_ids=None,
search_str=False,
mode="rp",
):
"""Return the domain for account.move.line records which can be used for
bank statement reconciliation.
:param aml_accounts:
:param partner_id:
:param excluded_ids:
:param search_str:
:param mode: 'rp' for receivable/payable or 'other'
"""
AccountMoveLine = self.env["account.move.line"]
# Always exclude the journal items that have been marked as
# 'to be checked' in a former bank statement reconciliation
to_check_excluded = AccountMoveLine.search(
AccountMoveLine._get_suspense_moves_domain()
).ids
if excluded_ids is None:
excluded_ids = []
excluded_ids.extend(to_check_excluded)
domain_reconciliation = [
"&",
"&",
("statement_line_id", "=", False),
("account_id", "in", aml_accounts),
("balance", "!=", 0.0),
]
if st_line.company_id.account_bank_reconciliation_start:
domain_reconciliation = expression.AND(
[
domain_reconciliation,
[
(
"date",
">=",
st_line.company_id.account_bank_reconciliation_start,
)
],
]
)
# default domain matching
domain_matching = [
"&",
"&",
"&",
"&",
("id", "not in", st_line.move_id.line_ids.ids),
("reconciled", "=", False),
("account_id.reconcile", "=", True),
("balance", "!=", 0.0),
("parent_state", "=", "posted"),
]
domain = expression.OR([domain_reconciliation, domain_matching])
if partner_id:
domain = expression.AND([domain, [("partner_id", "=", partner_id)]])
if mode == "rp":
domain = expression.AND(
[
domain,
[
(
"account_id.internal_type",
"in",
["receivable", "payable", "liquidity"],
)
],
]
)
else:
domain = expression.AND(
[
domain,
[
(
"account_id.internal_type",
"not in",
["receivable", "payable", "liquidity"],
)
],
]
)
# Domain factorized for all reconciliation use cases
if search_str:
str_domain = self._domain_move_lines(search_str=search_str)
str_domain = expression.OR(
[str_domain, [("partner_id.name", "ilike", search_str)]]
)
domain = expression.AND([domain, str_domain])
if excluded_ids:
domain = expression.AND([[("id", "not in", excluded_ids)], domain])
# filter on account.move.line having the same company as the statement
# line
domain = expression.AND([domain, [("company_id", "=", st_line.company_id.id)]])
return domain
@api.model
def _domain_move_lines_for_manual_reconciliation(
self, account_id, partner_id=False, excluded_ids=None, search_str=False
):
"""Create domain criteria that are relevant to manual reconciliation."""
domain = [
"&",
"&",
("reconciled", "=", False),
("account_id", "=", account_id),
("move_id.state", "=", "posted"),
]
domain = expression.AND([domain, [("balance", "!=", 0.0)]])
if partner_id:
domain = expression.AND([domain, [("partner_id", "=", partner_id)]])
if excluded_ids:
domain = expression.AND([[("id", "not in", excluded_ids)], domain])
if search_str:
str_domain = self._domain_move_lines(search_str=search_str)
domain = expression.AND([domain, str_domain])
# filter on account.move.line having the same company as the given account
account = self.env["account.account"].browse(account_id)
domain = expression.AND([domain, [("company_id", "=", account.company_id.id)]])
return domain
@api.model
def _prepare_move_lines(
self, move_lines, target_currency=False, target_date=False, recs_count=0
):
"""Returns move lines formatted for the manual/bank reconciliation
widget
:param move_line_ids:
:param target_currency: currency (browse) you want the move line
debit/credit converted into
:param target_date: date to use for the monetary conversion
"""
ret = []
for line in move_lines:
company_currency = line.company_id.currency_id
line_currency = (
(line.currency_id and line.amount_currency)
and line.currency_id
or company_currency
)
ret_line = {
"id": line.id,
"name": line.name
and line.name != "/"
and line.move_id.name != line.name
and line.move_id.name + ": " + line.name
or line.move_id.name,
"ref": line.move_id.ref or "",
# For reconciliation between statement transactions and already
# registered payments (eg. checks)
# NB : we don't use the 'reconciled' field because the line
# we're selecting is not the one that gets reconciled
"account_id": [line.account_id.id, line.account_id.display_name],
"already_paid": line.account_id.internal_type == "liquidity",
"account_code": line.account_id.code,
"account_name": line.account_id.name,
"account_type": line.account_id.internal_type,
"date_maturity": format_date(self.env, line.date_maturity),
"date": format_date(self.env, line.date),
"journal_id": [line.journal_id.id, line.journal_id.display_name],
"partner_id": line.partner_id.id,
"partner_name": line.partner_id.name,
"currency_id": line_currency.id,
}
debit = line.debit
credit = line.credit
amount = line.amount_residual
amount_currency = line.amount_residual_currency
# For already reconciled lines, don't use amount_residual(_currency)
if line.account_id.internal_type == "liquidity":
amount = debit - credit
amount_currency = line.amount_currency
target_currency = target_currency or company_currency
# Use case:
# Let's assume that company currency is in USD and that we have the
# 3 following move lines
# Debit Credit Amount currency Currency
# 1) 25 0 0 NULL
# 2) 17 0 25 EUR
# 3) 33 0 25 YEN
#
# If we ask to see the information in the reconciliation widget in
# company currency, we want to see The following information
# 1) 25 USD (no currency information)
# 2) 17 USD [25 EUR] (show 25 euro in currency information,
# in the little bill)
# 3) 33 USD [25 YEN] (show 25 yen in currency information)
#
# If we ask to see the information in another currency than the
# company let's say EUR
# 1) 35 EUR [25 USD]
# 2) 25 EUR (no currency information)
# 3) 50 EUR [25 YEN]
# In that case, we have to convert the debit-credit to the currency
# we want and we show next to it the value of the amount_currency or
# the debit-credit if no amount currency
if target_currency == company_currency:
if line_currency == target_currency:
amount = amount
amount_currency = ""
total_amount = debit - credit
total_amount_currency = ""
else:
amount = amount
amount_currency = amount_currency
total_amount = debit - credit
total_amount_currency = line.amount_currency
if target_currency != company_currency:
if line_currency == target_currency:
amount = amount_currency
amount_currency = ""
total_amount = line.amount_currency
total_amount_currency = ""
else:
amount_currency = line.currency_id and amount_currency or amount
company = line.account_id.company_id
date = target_date or line.date
amount = company_currency._convert(
amount, target_currency, company, date
)
total_amount = company_currency._convert(
(line.debit - line.credit), target_currency, company, date
)
total_amount_currency = (
line.currency_id
and line.amount_currency
or (line.debit - line.credit)
)
ret_line["recs_count"] = recs_count
ret_line["debit"] = amount > 0 and amount or 0
ret_line["credit"] = amount < 0 and -amount or 0
ret_line["amount_currency"] = amount_currency
ret_line["amount_str"] = formatLang(
self.env, abs(amount), currency_obj=target_currency
)
ret_line["total_amount_str"] = formatLang(
self.env, abs(total_amount), currency_obj=target_currency
)
ret_line["amount_currency_str"] = (
amount_currency
and formatLang(
self.env, abs(amount_currency), currency_obj=line_currency
)
or ""
)
ret_line["total_amount_currency_str"] = (
total_amount_currency
and formatLang(
self.env, abs(total_amount_currency), currency_obj=line_currency
)
or ""
)
ret.append(ret_line)
return ret
@api.model
def _get_statement_line(self, st_line):
"""Returns the data required by the bank statement reconciliation
widget to display a statement line"""
statement_currency = (
st_line.journal_id.currency_id or st_line.journal_id.company_id.currency_id
)
st_line_currency = (
st_line.foreign_currency_id or st_line.currency_id or statement_currency
)
if st_line.amount_currency and (st_line_currency != statement_currency):
amount = st_line.amount
amount_currency = st_line.amount_currency
amount_currency_str = formatLang(
self.env, abs(amount_currency), currency_obj=st_line_currency
)
else:
amount = st_line.amount
amount_currency = amount
amount_currency_str = ""
amount_str = formatLang(
self.env,
abs(amount),
currency_obj=st_line.currency_id or statement_currency,
)
data = {
"id": st_line.id,
"ref": st_line.ref,
"narration": st_line.narration or "",
"name": st_line.name,
"payment_ref": st_line.payment_ref,
"date": format_date(self.env, st_line.date),
"amount": amount,
"amount_str": amount_str, # Amount in the statement line currency
"currency_id": (st_line.currency_id or statement_currency).id,
"partner_id": st_line.partner_id.id,
"journal_id": st_line.journal_id.id,
"statement_id": st_line.statement_id.id,
"account_id": [
st_line.journal_id.default_account_id.id,
st_line.journal_id.default_account_id.display_name,
],
"account_code": st_line.journal_id.default_account_id.code,
"account_name": st_line.journal_id.default_account_id.name,
"partner_name": st_line.partner_id.name,
"communication_partner_name": st_line.partner_name,
# Amount in the statement currency
"amount_currency_str": amount_currency_str,
# Amount in the statement currency
"amount_currency": amount_currency,
"has_no_partner": not st_line.partner_id.id,
"company_id": st_line.company_id.id,
}
if st_line.partner_id:
data["open_balance_account_id"] = (
amount > 0
and st_line.partner_id.property_account_receivable_id.id
or st_line.partner_id.property_account_payable_id.id
)
return data
@api.model
def _get_move_line_reconciliation_proposition(self, account_id, partner_id=None):
"""Returns two lines whose amount are opposite"""
Account_move_line = self.env["account.move.line"]
ir_rules_query = Account_move_line._where_calc([])
Account_move_line._apply_ir_rules(ir_rules_query, "read")
from_clause, where_clause, where_clause_params = ir_rules_query.get_sql()
where_str = where_clause and (" WHERE %s" % where_clause) or ""
# Get pairs
query = sql.SQL(
"""
SELECT a.id, b.id
FROM account_move_line a, account_move_line b,
account_move move_a, account_move move_b,
account_journal journal_a, account_journal journal_b
WHERE a.id != b.id
AND move_a.id = a.move_id
AND move_a.state = 'posted'
AND move_a.journal_id = journal_a.id
AND move_b.id = b.move_id
AND move_b.journal_id = journal_b.id
AND move_b.state = 'posted'
AND a.amount_residual = -b.amount_residual
AND a.balance != 0.0
AND b.balance != 0.0
AND NOT a.reconciled
AND a.account_id = %s
AND (%s IS NULL AND b.account_id = %s)
AND (%s IS NULL AND NOT b.reconciled OR b.id = %s)
AND (%s is NULL OR (a.partner_id = %s AND b.partner_id = %s))
AND a.id IN (SELECT "account_move_line".id FROM {0})
AND b.id IN (SELECT "account_move_line".id FROM {0})
ORDER BY a.date desc
LIMIT 1
""".format(
from_clause + where_str
)
)
move_line_id = self.env.context.get("move_line_id") or None
params = (
[
account_id,
move_line_id,
account_id,
move_line_id,
move_line_id,
partner_id,
partner_id,
partner_id,
]
+ where_clause_params
+ where_clause_params
)
self.env.cr.execute(query, params)
pairs = self.env.cr.fetchall()
if pairs:
return Account_move_line.browse(pairs[0])
return Account_move_line
@api.model
def _process_move_lines(self, move_line_ids, new_mv_line_dicts):
"""Create new move lines from new_mv_line_dicts (if not empty) then call
reconcile_partial on self and new move lines
:param new_mv_line_dicts: list of dicts containing values suitable for
account_move_line.create()
"""
if len(move_line_ids) < 1 or len(move_line_ids) + len(new_mv_line_dicts) < 2:
raise UserError(_("A reconciliation must involve at least 2 move lines."))
AccountMoveLine = self.env["account.move.line"].with_context(
skip_account_move_synchronization=True
)
account_move_line = AccountMoveLine.browse(move_line_ids)
writeoff_lines = AccountMoveLine
# Create writeoff move lines
if len(new_mv_line_dicts) > 0:
company_currency = account_move_line[0].account_id.company_id.currency_id
same_currency = False
currencies = list(
{aml.currency_id or company_currency for aml in account_move_line}
)
if len(currencies) == 1 and currencies[0] != company_currency:
same_currency = True
# We don't have to convert debit/credit to currency as all values in
# the reconciliation widget are displayed in company currency
# If all the lines are in the same currency, create writeoff entry
# with same currency also
for mv_line_dict in new_mv_line_dicts:
if not same_currency:
mv_line_dict["amount_currency"] = False
writeoff_lines += account_move_line._create_writeoff([mv_line_dict])
(account_move_line + writeoff_lines).reconcile()
else:
account_move_line.reconcile()
| 40.394068 | 47,665 |
1,151 |
py
|
PYTHON
|
15.0
|
from odoo import models
class AccountJournal(models.Model):
_inherit = "account.journal"
def action_open_reconcile(self):
# Open reconciliation view for bank statements belonging to this journal
bank_stmt = (
self.env["account.bank.statement"]
.search([("journal_id", "in", self.ids)])
.mapped("line_ids")
)
return {
"type": "ir.actions.client",
"tag": "bank_statement_reconciliation_view",
"context": {
"statement_line_ids": bank_stmt.ids,
"company_ids": self.mapped("company_id").ids,
},
}
def action_open_reconcile_to_check(self):
self.ensure_one()
ids = self.to_check_ids().ids
action_context = {
"show_mode_selector": False,
"company_ids": self.mapped("company_id").ids,
"suspense_moves_mode": True,
"statement_line_ids": ids,
}
return {
"type": "ir.actions.client",
"tag": "bank_statement_reconciliation_view",
"context": action_context,
}
| 31.108108 | 1,151 |
504 |
py
|
PYTHON
|
15.0
|
from odoo import fields, models
class ResCompany(models.Model):
_inherit = "res.company"
account_bank_reconciliation_start = fields.Date(
string="Bank Reconciliation Threshold",
help="The bank reconciliation widget won't ask to reconcile payments "
"older than this date.\n"
"This is useful if you install accounting after having used invoicing "
"for some time and don't want to reconcile all the past payments with "
"bank statements.",
)
| 36 | 504 |
15,603 |
py
|
PYTHON
|
15.0
|
from odoo import _, fields, models
from odoo.exceptions import UserError
class AccountBankStatement(models.Model):
_inherit = "account.bank.statement"
accounting_date = fields.Date(
string="Financial Date",
help="If set, the accounting entries created during the bank statement "
"reconciliation process will be created at this date.\n"
"This is useful if the accounting period in which the entries should "
"normally be booked is already closed.",
states={"open": [("readonly", False)]},
readonly=True,
)
def action_bank_reconcile_bank_statements(self):
self.ensure_one()
bank_stmt_lines = self.mapped("line_ids")
return {
"type": "ir.actions.client",
"tag": "bank_statement_reconciliation_view",
"context": {
"statement_line_ids": bank_stmt_lines.ids,
"company_ids": self.mapped("company_id").ids,
},
}
class AccountBankStatementLine(models.Model):
_inherit = "account.bank.statement.line"
move_name = fields.Char(
string="Journal Entry Name",
readonly=True,
default=False,
copy=False,
help="Technical field holding the number given to the journal entry,"
"automatically set when the statement line is reconciled then stored"
"to set the same number again if the line is cancelled,"
"set to draft and re-processed again.",
)
def process_reconciliation(
self, counterpart_aml_dicts=None, payment_aml_rec=None, new_aml_dicts=None
):
"""Match statement lines with existing payments (eg. checks) and/or
payables/receivables (eg. invoices and credit notes) and/or new move
lines (eg. write-offs).
If any new journal item needs to be created (via new_aml_dicts or
counterpart_aml_dicts), a new journal entry will be created and will
contain those items, as well as a journal item for the bank statement
line.
Finally, mark the statement line as reconciled by putting the matched
moves ids in the column journal_entry_ids.
:param self: browse collection of records that are supposed to have no
accounting entries already linked.
:param (list of dicts) counterpart_aml_dicts: move lines to create to
reconcile with existing payables/receivables.
The expected keys are :
- 'name'
- 'debit'
- 'credit'
- 'move_line'
# The move line to reconcile (partially if specified
# debit/credit is lower than move line's credit/debit)
:param (list of recordsets) payment_aml_rec: recordset move lines
representing existing payments (which are already fully reconciled)
:param (list of dicts) new_aml_dicts: move lines to create. The expected
keys are :
- 'name'
- 'debit'
- 'credit'
- 'account_id'
- (optional) 'tax_ids'
- (optional) Other account.move.line fields like analytic_account_id
or analytics_id
- (optional) 'reconcile_model_id'
:returns: The journal entries with which the transaction was matched.
If there was at least an entry in counterpart_aml_dicts or
new_aml_dicts, this list contains the move created by the
reconciliation, containing entries for the statement.line (1), the
counterpart move lines (0..*) and the new move lines (0..*).
"""
payable_account_type = self.env.ref("account.data_account_type_payable")
receivable_account_type = self.env.ref("account.data_account_type_receivable")
suspense_moves_mode = self._context.get("suspense_moves_mode")
counterpart_aml_dicts = counterpart_aml_dicts or []
payment_aml_rec = payment_aml_rec or self.env["account.move.line"]
new_aml_dicts = new_aml_dicts or []
aml_obj = self.env["account.move.line"]
counterpart_moves = self.env["account.move"]
# Check and prepare received data
if any(rec.statement_id for rec in payment_aml_rec):
raise UserError(_("A selected move line was already reconciled."))
for aml_dict in counterpart_aml_dicts:
if aml_dict["move_line"].reconciled and not suspense_moves_mode:
raise UserError(_("A selected move line was already reconciled."))
if isinstance(aml_dict["move_line"], int):
aml_dict["move_line"] = aml_obj.browse(aml_dict["move_line"])
account_types = self.env["account.account.type"]
for aml_dict in counterpart_aml_dicts + new_aml_dicts:
if aml_dict.get("tax_ids") and isinstance(aml_dict["tax_ids"][0], int):
# Transform the value in the format required for One2many and
# Many2many fields
aml_dict["tax_ids"] = [(4, id, None) for id in aml_dict["tax_ids"]]
user_type_id = (
self.env["account.account"]
.browse(aml_dict.get("account_id"))
.user_type_id
)
if (
user_type_id in [payable_account_type, receivable_account_type]
and user_type_id not in account_types
):
account_types |= user_type_id
# Fully reconciled moves are just linked to the bank statement (blue lines),
# but the generated move on statement post should be removed and link the
# payment one for not having double entry
# TODO: To mix already done payments with new ones. Not sure if possible.
old_move = self.move_id.with_context(force_delete=True)
for aml_rec in payment_aml_rec:
aml_rec.with_context(check_move_validity=False).write(
{"statement_line_id": self.id}
)
# This overwrites the value on each loop, so only one will be linked, but
# there's no better solution in this case
self.move_id = aml_rec.move_id.id
counterpart_moves |= aml_rec.move_id
if payment_aml_rec:
old_move.button_draft()
old_move.unlink()
# Create move line(s). Either matching an existing journal entry
# (eg. invoice), in which case we reconcile the existing and the
# new move lines together, or being a write-off.
if counterpart_aml_dicts or new_aml_dicts:
counterpart_moves = self._create_counterpart_and_new_aml(
counterpart_moves, counterpart_aml_dicts, new_aml_dicts
)
elif self.move_name:
raise UserError(
_(
"Operation not allowed. Since your statement line already "
"received a number (%s), you cannot reconcile it entirely "
"with existing journal entries otherwise it would make a "
"gap in the numbering. You should book an entry and make a "
"regular revert of it in case you want to cancel it."
)
% (self.move_name)
)
# create the res.partner.bank if needed
if self.account_number and self.partner_id and not self.partner_bank_id:
# Search bank account without partner to handle the case the res.partner.bank
# already exists but is set on a different partner.
self.partner_bank_id = self._find_or_create_bank_account()
counterpart_moves._check_balanced()
return counterpart_moves
def _create_counterpart_and_new_aml(
self, counterpart_moves, counterpart_aml_dicts, new_aml_dicts
):
aml_obj = self.env["account.move.line"]
# Delete previous move_lines
self.move_id.line_ids.with_context(force_delete=True).unlink()
# Create liquidity line
liquidity_aml_dict = self._prepare_liquidity_move_line_vals()
aml_obj.with_context(check_move_validity=False).create(liquidity_aml_dict)
self.sequence = self.statement_id.line_ids.ids.index(self.id) + 1
self.move_id.ref = self._get_move_ref(self.statement_id.name)
counterpart_moves = counterpart_moves | self.move_id
# Complete dicts to create both counterpart move lines and write-offs
to_create = counterpart_aml_dicts + new_aml_dicts
date = self.date or fields.Date.today()
for aml_dict in to_create:
aml_dict["move_id"] = self.move_id.id
aml_dict["partner_id"] = self.partner_id.id
aml_dict["statement_line_id"] = self.id
self._prepare_move_line_for_currency(aml_dict, date)
# Create write-offs
wo_aml = self.env["account.move.line"]
for aml_dict in new_aml_dicts:
wo_aml |= aml_obj.with_context(check_move_validity=False).create(aml_dict)
analytic_wo_aml = wo_aml.filtered(
lambda l: l.analytic_account_id or l.analytic_tag_ids
)
# Create counterpart move lines and reconcile them
aml_to_reconcile = []
for aml_dict in counterpart_aml_dicts:
if not aml_dict["move_line"].statement_line_id:
aml_dict["move_line"].write({"statement_line_id": self.id})
if aml_dict["move_line"].partner_id.id:
aml_dict["partner_id"] = aml_dict["move_line"].partner_id.id
aml_dict["account_id"] = aml_dict["move_line"].account_id.id
counterpart_move_line = aml_dict.pop("move_line")
new_aml = aml_obj.with_context(check_move_validity=False).create(aml_dict)
aml_to_reconcile.append((new_aml, counterpart_move_line))
# Post to allow reconcile
if self.move_id.state == "draft":
self.move_id.with_context(
skip_account_move_synchronization=True
).action_post()
elif analytic_wo_aml:
# if already posted the analytic entry has to be created
analytic_wo_aml.create_analytic_lines()
# Reconcile new lines with counterpart
for new_aml, counterpart_move_line in aml_to_reconcile:
(new_aml | counterpart_move_line).reconcile()
self._check_invoice_state(counterpart_move_line.move_id)
# Needs to be called manually as lines were created 1 by 1
if self.move_id.state == "draft":
self.move_id.with_context(
skip_account_move_synchronization=True
).action_post()
# record the move name on the statement line to be able to retrieve
# it in case of unreconciliation
self.write({"move_name": self.move_id.name})
return counterpart_moves
def _get_move_ref(self, move_ref):
ref = move_ref or ""
if self.ref:
ref = move_ref + " - " + self.ref if move_ref else self.ref
return ref
def _prepare_move_line_for_currency(self, aml_dict, date):
self.ensure_one()
company_currency = self.journal_id.company_id.currency_id
statement_currency = self.journal_id.currency_id or company_currency
st_line_currency = self.currency_id or statement_currency
st_line_currency_rate = (
self.currency_id and (self.amount_currency / self.amount) or False
)
company = self.company_id
if st_line_currency.id != company_currency.id:
aml_dict["amount_currency"] = aml_dict["debit"] - aml_dict["credit"]
aml_dict["currency_id"] = st_line_currency.id
if (
self.currency_id
and statement_currency.id == company_currency.id
and st_line_currency_rate
):
# Statement is in company currency but the transaction is in foreign currency
aml_dict["debit"] = company_currency.round(
aml_dict["debit"] / st_line_currency_rate
)
aml_dict["credit"] = company_currency.round(
aml_dict["credit"] / st_line_currency_rate
)
elif self.currency_id and st_line_currency_rate:
# Statement is in foreign currency and the transaction is in another one
aml_dict["debit"] = statement_currency._convert(
aml_dict["debit"] / st_line_currency_rate,
company_currency,
company,
date,
)
aml_dict["credit"] = statement_currency._convert(
aml_dict["credit"] / st_line_currency_rate,
company_currency,
company,
date,
)
else:
# Statement is in foreign currency and no extra currency is given
# for the transaction
aml_dict["debit"] = st_line_currency._convert(
aml_dict["debit"], company_currency, company, date
)
aml_dict["credit"] = st_line_currency._convert(
aml_dict["credit"], company_currency, company, date
)
elif statement_currency.id != company_currency.id:
# Statement is in foreign currency but the transaction is in company currency
prorata_factor = (
aml_dict["debit"] - aml_dict["credit"]
) / self.amount_currency
aml_dict["amount_currency"] = prorata_factor * self.amount
aml_dict["currency_id"] = statement_currency.id
def _check_invoice_state(self, invoice):
if invoice.is_invoice(include_receipts=True):
invoice._compute_amount()
def button_undo_reconciliation(self):
"""Handle the case when the reconciliation was done against a direct payment
with the bank account as counterpart. This may be the case for payments made
in previous versions of Odoo.
"""
handled = self.env[self._name]
for record in self:
if record.move_id.payment_id:
# The reconciliation was done against a blue line (existing move)
# We remove the link on the current existing move, preserving it,
# and recreate a new move as if the statement line was new
record.move_id.line_ids.statement_line_id = False
statement = record.statement_id
journal = statement.journal_id
line_vals_list = record._prepare_move_line_default_vals()
new_move = self.env["account.move"].create(
{
"move_type": "entry",
"statement_line_id": record.id,
"ref": statement.name,
"date": record.date,
"journal_id": journal.id,
"partner_id": record.partner_id.id,
"currency_id": (
journal.currency_id or journal.company_id.currency_id
).id,
"line_ids": [(0, 0, line_vals) for line_vals in line_vals_list],
}
)
new_move.action_post()
record.move_id = new_move.id
handled += record
return super(
AccountBankStatementLine, self - handled
).button_undo_reconciliation()
| 44.965418 | 15,603 |
376 |
py
|
PYTHON
|
15.0
|
# Copyright 2022 Akretion France - Alexis de Lattre
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ResConfigSettings(models.TransientModel):
_inherit = "res.config.settings"
account_bank_reconciliation_start = fields.Date(
related="company_id.account_bank_reconciliation_start", readonly=False
)
| 31.333333 | 376 |
395 |
py
|
PYTHON
|
15.0
|
# Copyright 2022 Tecnativa - Ernesto Tejeda
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Account Move Reconcile Forbid Cancel",
"version": "15.0.1.0.0",
"category": "Finance",
"website": "https://github.com/OCA/account-reconcile",
"author": "Tecnativa, Odoo Community Association (OCA)",
"license": "AGPL-3",
"depends": ["account"],
}
| 32.916667 | 395 |
4,698 |
py
|
PYTHON
|
15.0
|
# Copyright 2022 Tecnativa - Ernesto Tejeda
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields
from odoo.exceptions import ValidationError
from odoo.tests.common import Form, TransactionCase
class TestAccountMoveReconcileForbidCancel(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.env["account.journal"].create(
{"name": "Bank Journal", "code": "BANK", "type": "bank"}
)
receivable_account = cls.env["account.account"].create(
{
"name": "Receivable Account",
"code": "REC",
"user_type_id": cls.env.ref("account.data_account_type_receivable").id,
"reconcile": True,
}
)
payable_account = cls.env["account.account"].create(
{
"name": "Payable Account",
"code": "PAY",
"user_type_id": cls.env.ref("account.data_account_type_payable").id,
"reconcile": True,
}
)
income_account = cls.env["account.account"].create(
{
"name": "Income Account",
"code": "INC",
"user_type_id": cls.env.ref(
"account.data_account_type_other_income"
).id,
"reconcile": False,
}
)
expense_account = cls.env["account.account"].create(
{
"name": "Expense Account",
"code": "EXP",
"user_type_id": cls.env.ref("account.data_account_type_expenses").id,
"reconcile": False,
}
)
cls.partner = cls.env["res.partner"].create(
{
"name": "Partner test",
"property_account_receivable_id": receivable_account.id,
"property_account_payable_id": payable_account.id,
}
)
cls.product = cls.env["product.product"].create(
{
"name": "Product Test",
"property_account_income_id": income_account.id,
"property_account_expense_id": expense_account.id,
}
)
# Create a purchase invoice
cls.purchase_invoice = cls._create_invoice(cls, "in_invoice")
cls.purchase_invoice.action_post()
# Create payment from invoice
cls._create_payment_from_invoice(cls, cls.purchase_invoice)
# Create a sale invoice
cls.sale_invoice = cls._create_invoice(cls, "out_invoice")
cls.sale_invoice.action_post()
# Create payment from invoice
cls._create_payment_from_invoice(cls, cls.sale_invoice)
def _create_invoice(self, move_type):
move_form = Form(
self.env["account.move"].with_context(default_move_type=move_type)
)
move_form.invoice_date = fields.Date.today()
move_form.partner_id = self.partner
with move_form.invoice_line_ids.new() as line_form:
line_form.product_id = self.product
line_form.price_unit = 100.0
return move_form.save()
def _create_payment_from_invoice(self, invoice):
res = invoice.action_register_payment()
payment_register_form = Form(
self.env[res["res_model"]].with_context(**res["context"])
)
payment = payment_register_form.save()
payment.action_create_payments()
def test_reset_invoice_to_draft(self):
with self.assertRaises(ValidationError):
self.purchase_invoice.with_context(
test_reconcile_forbid_cancel=True
).button_draft()
with self.assertRaises(ValidationError):
self.sale_invoice.with_context(
test_reconcile_forbid_cancel=True
).button_draft()
def test_cancel_invoice(self):
with self.assertRaises(ValidationError):
self.purchase_invoice.with_context(
test_reconcile_forbid_cancel=True
).button_cancel()
with self.assertRaises(ValidationError):
self.sale_invoice.with_context(
test_reconcile_forbid_cancel=True
).button_cancel()
def test_extra_invoice_process_to_draft(self):
invoice = self._create_invoice("out_invoice")
invoice.action_post()
invoice.button_draft()
self.assertEqual(invoice.state, "draft")
def test_extra_invoice_process_cancel(self):
invoice = self._create_invoice("out_invoice")
invoice.action_post()
invoice.button_cancel()
self.assertEqual(invoice.state, "cancel")
| 37.887097 | 4,698 |
1,462 |
py
|
PYTHON
|
15.0
|
# Copyright 2022 Tecnativa - Ernesto Tejeda
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import _, models, tools
from odoo.exceptions import ValidationError
class AccountMove(models.Model):
_inherit = "account.move"
def _get_receivable_payable_lines(self):
return self.line_ids.filtered(
lambda l: l.account_internal_type in ["receivable", "payable"],
)
def button_draft(self):
if not self.env.context.get("skip_reconcile_forbid_cancel") and (
not tools.config["test_enable"]
or self.env.context.get("test_reconcile_forbid_cancel")
):
rec_pay_lines = self._get_receivable_payable_lines()
if rec_pay_lines.matched_debit_ids or rec_pay_lines.matched_credit_ids:
raise ValidationError(
_("You cannot reset to draft reconciled entries.")
)
return super().button_draft()
def button_cancel(self):
if not self.env.context.get("skip_reconcile_forbid_cancel") and (
not tools.config["test_enable"]
or self.env.context.get("test_reconcile_forbid_cancel")
):
rec_pay_lines = self._get_receivable_payable_lines()
if rec_pay_lines.matched_debit_ids or rec_pay_lines.matched_credit_ids:
raise ValidationError(_("You cannot cancel reconciled entries."))
return super().button_cancel()
| 40.611111 | 1,462 |
479 |
py
|
PYTHON
|
15.0
|
# Copyright 2017-20 ForgeFlow S.L. (http://www.forgeflow.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
{
"name": "Account Partner Reconcile",
"version": "15.0.1.0.0",
"category": "Accounting",
"author": "ForgeFlow, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/account-reconcile",
"license": "AGPL-3",
"depends": ["account"],
"data": ["views/res_partner_view.xml"],
"installable": True,
}
| 34.214286 | 479 |
1,205 |
py
|
PYTHON
|
15.0
|
# Copyright 2017-20 ForgeFlow S.L. (http://www.forgeflow.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo.tests.common import TransactionCase
class TestAccountPartnerReconcile(TransactionCase):
"""Tests for Account Partner Reconcile."""
def setUp(self):
super(TestAccountPartnerReconcile, self).setUp()
self.partner1 = self.env.ref("base.res_partner_1")
def test_account_partner_reconcile(self):
res = self.partner1.action_open_reconcile()
# assertDictContainsSubset is deprecated in Python <3.2
expect = {"type": "ir.actions.client", "tag": "manual_reconciliation_view"}
self.assertDictEqual(
expect,
{k: v for k, v in res.items() if k in expect},
"There was an error and the manual_reconciliation_view "
"couldn't be opened.",
)
expect = {"partner_ids": self.partner1.ids, "show_mode_selector": True}
self.assertDictEqual(
expect,
{k: v for k, v in res["context"].items() if k in expect},
"There was an error and the manual_reconciliation_view "
"couldn't be opened.",
)
| 36.515152 | 1,205 |
894 |
py
|
PYTHON
|
15.0
|
# Copyright 2017-20 ForgeFlow S.L. (http://www.forgeflow.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import models
class ResPartner(models.Model):
_inherit = "res.partner"
def action_open_reconcile(self):
# Open reconciliation view for customers and suppliers
reconcile_mode = self.env.context.get("reconcile_mode", False)
accounts = self.property_account_payable_id
if reconcile_mode == "customers":
accounts = self.property_account_receivable_id
action_context = {
"show_mode_selector": True,
"partner_ids": [self.id],
"mode": reconcile_mode,
"account_ids": accounts.ids,
}
return {
"type": "ir.actions.client",
"tag": "manual_reconciliation_view",
"context": action_context,
}
| 33.111111 | 894 |
793 |
py
|
PYTHON
|
15.0
|
# Copyright 2022 ForgeFlow S.L.
# @author Jordi Ballester <[email protected]>
# Copyright 2022 Akretion (http://www.akretion.com)
# @author Alexis de Lattre <[email protected]>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
{
"name": "Account Bank Statement Reopen Skip Undo Reconciliation",
"summary": "When reopening a bank statement it will respect the "
"reconciled entries.",
"version": "15.0.1.0.0",
"author": "ForgeFlow, Akretion, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/account-reconcile",
"category": "Finance",
"depends": ["account"],
"data": ["views/account_bank_statement_views.xml"],
"license": "AGPL-3",
"installable": True,
"auto_install": False,
}
| 39.65 | 793 |
3,245 |
py
|
PYTHON
|
15.0
|
# Copyright 2022 ForgeFlow S.L.
# @author Jordi Ballester <[email protected]>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import fields
from odoo.tests import tagged
from odoo.addons.account.tests.test_account_bank_statement import (
TestAccountBankStatementCommon,
)
@tagged("post_install", "-at_install")
class TestAccountBankStatementLine(TestAccountBankStatementCommon):
def test_button_undo_reconciliation(self):
statement = self.env["account.bank.statement"].create(
{
"name": "test_statement",
"date": "2019-01-01",
"journal_id": self.bank_journal_2.id,
"line_ids": [
(
0,
0,
{
"date": "2019-01-01",
"payment_ref": "line_1",
"partner_id": self.partner_a.id,
"amount": 1000,
},
),
(
0,
0,
{
"date": "2019-01-01",
"payment_ref": "line_2",
"partner_id": self.partner_a.id,
"amount": 2000,
},
),
],
}
)
statement_line = statement.line_ids[0]
test_invoice = self.env["account.move"].create(
[
{
"move_type": "out_invoice",
"invoice_date": fields.Date.from_string("2016-01-01"),
"date": fields.Date.from_string("2016-01-01"),
"partner_id": self.partner_a.id,
"invoice_line_ids": [
(
0,
None,
{
"name": "counterpart line, same amount",
"account_id": self.company_data[
"default_account_revenue"
].id,
"quantity": 1,
"price_unit": 1000,
},
),
],
}
]
)
test_invoice.action_post()
statement.button_post()
counterpart_lines = test_invoice.mapped("line_ids").filtered(
lambda line: line.account_internal_type in ("receivable", "payable")
)
statement_line.reconcile([{"id": counterpart_lines[0].id}])
self.assertEqual(counterpart_lines.reconciled, True)
statement.button_reopen()
self.assertEqual(counterpart_lines.reconciled, True)
self.assertEqual(statement_line.move_id.state, "posted")
second_statement_line = statement.line_ids[0]
self.assertEqual(second_statement_line.move_id.state, "draft")
statement_line.button_undo_reconciliation()
self.assertEqual(statement_line.move_id.state, "draft")
| 39.096386 | 3,245 |
436 |
py
|
PYTHON
|
15.0
|
# Copyright 2022 ForgeFlow S.L.
# @author Jordi Ballester <[email protected]>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import models
class AccountMove(models.Model):
_inherit = "account.move"
def button_draft(self):
moves_to_draft = self.filtered(lambda m: not m.statement_line_id.is_reconciled)
return super(AccountMove, moves_to_draft).button_draft()
| 33.538462 | 436 |
451 |
py
|
PYTHON
|
15.0
|
# Copyright 2022 ForgeFlow S.L.
# @author Jordi Ballester <[email protected]>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import models
class AccountMoveLine(models.Model):
_inherit = "account.move.line"
def remove_move_reconcile(self):
if self._context.get("skip_undo_reconciliation"):
return True
return super(AccountMoveLine, self).remove_move_reconcile()
| 32.214286 | 451 |
699 |
py
|
PYTHON
|
15.0
|
# Copyright 2022 Akretion (http://www.akretion.com)
# @author Alexis de Lattre <[email protected]>
# Copyright 2022 ForgeFlow S.L.
# @author Jordi Ballester <[email protected]>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import models
class AccountBankStatementLine(models.Model):
_inherit = "account.bank.statement.line"
def button_undo_reconciliation(self):
if self._context.get("skip_undo_reconciliation"):
return
res = super(AccountBankStatementLine, self).button_undo_reconciliation()
if self.statement_id.state == "open":
self.move_id.button_draft()
return res
| 34.95 | 699 |
542 |
py
|
PYTHON
|
15.0
|
# Copyright 2022 Akretion (http://www.akretion.com)
# @author Alexis de Lattre <[email protected]>
# Copyright 2022 ForgeFlow S.L.
# @author Jordi Ballester <[email protected]>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import models
class AccountBankStatement(models.Model):
_inherit = "account.bank.statement"
def button_reopen(self):
self = self.with_context(skip_undo_reconciliation=True)
return super(AccountBankStatement, self).button_reopen()
| 36.133333 | 542 |
100 |
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667 | 100 |
928 |
py
|
PYTHON
|
15.0
|
import setuptools
with open('VERSION.txt', 'r') as f:
version = f.read().strip()
setuptools.setup(
name="odoo-addons-oca-account-reconcile",
description="Meta package for oca-account-reconcile Odoo addons",
version=version,
install_requires=[
'odoo-addon-account_bank_statement_reopen_skip_undo_reconciliation>=15.0dev,<15.1dev',
'odoo-addon-account_mass_reconcile>=15.0dev,<15.1dev',
'odoo-addon-account_move_reconcile_forbid_cancel>=15.0dev,<15.1dev',
'odoo-addon-account_partner_reconcile>=15.0dev,<15.1dev',
'odoo-addon-account_reconcile_payment_order>=15.0dev,<15.1dev',
'odoo-addon-account_reconciliation_widget>=15.0dev,<15.1dev',
'odoo-addon-account_reconciliation_widget_due_date>=15.0dev,<15.1dev',
],
classifiers=[
'Programming Language :: Python',
'Framework :: Odoo',
'Framework :: Odoo :: 15.0',
]
)
| 38.666667 | 928 |
100 |
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667 | 100 |
100 |
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667 | 100 |
100 |
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667 | 100 |
100 |
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667 | 100 |
100 |
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667 | 100 |
100 |
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667 | 100 |
629 |
py
|
PYTHON
|
15.0
|
# Copyright 2012-2016 Camptocamp SA
# Copyright 2010 Sébastien Beau
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Account Mass Reconcile",
"version": "15.0.1.0.0",
"depends": ["account"],
"author": "Akretion,Camptocamp,Odoo Community Association (OCA)",
"website": "https://github.com/OCA/account-reconcile",
"category": "Finance",
"data": [
"security/ir_rule.xml",
"security/ir.model.access.csv",
"views/mass_reconcile.xml",
"views/mass_reconcile_history_view.xml",
"views/res_config_view.xml",
],
"license": "AGPL-3",
}
| 31.4 | 628 |
2,560 |
py
|
PYTHON
|
15.0
|
# © 2014-2016 Camptocamp SA (Damien Crier)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import odoo.tests
from odoo import exceptions, fields
from odoo.addons.account.tests.common import TestAccountReconciliationCommon
@odoo.tests.tagged("post_install", "-at_install")
class TestReconcile(TestAccountReconciliationCommon):
@classmethod
def setUpClass(cls):
super(TestReconcile, cls).setUpClass()
cls.rec_history_obj = cls.env["mass.reconcile.history"]
cls.mass_rec_obj = cls.env["account.mass.reconcile"]
cls.mass_rec_method_obj = cls.env["account.mass.reconcile.method"]
cls.sale_journal = cls.company_data["default_journal_sale"]
cls.mass_rec = cls.mass_rec_obj.create(
{"name": "Sale Account", "account": cls.sale_journal.default_account_id.id}
)
cls.mass_rec_method = cls.mass_rec_method_obj.create(
{
"name": "mass.reconcile.simple.name",
"sequence": "10",
"task_id": cls.mass_rec.id,
}
)
cls.mass_rec_no_history = cls.mass_rec_obj.create(
{"name": "AER3", "account": cls.sale_journal.default_account_id.id}
)
cls.rec_history = cls.rec_history_obj.create(
{"mass_reconcile_id": cls.mass_rec.id, "date": fields.Datetime.now()}
)
def test_last_history(self):
mass_rec_last_hist = self.mass_rec.last_history
self.assertEqual(self.rec_history, mass_rec_last_hist)
def test_last_history_empty(self):
mass_rec_last_hist = self.mass_rec_no_history.last_history.id
self.assertEqual(False, mass_rec_last_hist)
def test_last_history_full_no_history(self):
with self.assertRaises(exceptions.Warning):
self.mass_rec_no_history.last_history_reconcile()
def test_open_unreconcile(self):
res = self.mass_rec.open_unreconcile()
self.assertEqual([("id", "in", [])], res.get("domain", []))
def test_prepare_run_transient(self):
res = self.mass_rec._prepare_run_transient(self.mass_rec_method)
self.assertEqual(
self.sale_journal.default_account_id.id, res.get("account_id", 0)
)
def test_open_full_empty(self):
res = self.rec_history._open_move_lines()
self.assertEqual([("id", "in", [])], res.get("domain", []))
def test_open_full_empty_from_method(self):
res = self.rec_history.open_reconcile()
self.assertEqual([("id", "in", [])], res.get("domain", []))
| 39.369231 | 2,559 |
1,236 |
py
|
PYTHON
|
15.0
|
# © 2014-2016 Camptocamp SA (Damien Crier)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo.tests import common
class TestOnChange(common.TransactionCase):
@classmethod
def setUpClass(cls):
super(TestOnChange, cls).setUpClass()
acc_setting = cls.env["res.config.settings"]
cls.acc_setting_obj = acc_setting.create({})
cls.company_obj = cls.env["res.company"]
# analytic defaults account creation
cls.main_company = cls.env.ref("base.main_company")
cls.sec_company = cls.company_obj.create(
{"name": "Second company", "reconciliation_commit_every": 80}
)
def test_retrieve_analytic_account(self):
sec_company_commit = self.sec_company.reconciliation_commit_every
main_company_commit = self.main_company.reconciliation_commit_every
self.acc_setting_obj.company_id = self.sec_company
self.assertEqual(
sec_company_commit, self.acc_setting_obj.reconciliation_commit_every, False
)
self.acc_setting_obj.company_id = self.main_company
self.assertEqual(
main_company_commit, self.acc_setting_obj.reconciliation_commit_every, False
)
| 36.323529 | 1,235 |
9,380 |
py
|
PYTHON
|
15.0
|
# © 2014-2016 Camptocamp SA (Damien Crier)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from datetime import timedelta
import odoo.tests
from odoo import fields
from odoo.addons.account.tests.common import TestAccountReconciliationCommon
@odoo.tests.tagged("post_install", "-at_install")
class TestScenarioReconcile(TestAccountReconciliationCommon):
@classmethod
def setUpClass(cls):
super(TestScenarioReconcile, cls).setUpClass()
cls.rec_history_obj = cls.env["mass.reconcile.history"]
cls.mass_rec_obj = cls.env["account.mass.reconcile"]
cls.invoice_obj = cls.env["account.move"]
cls.bk_stmt_obj = cls.env["account.bank.statement"]
cls.bk_stmt_line_obj = cls.env["account.bank.statement.line"]
cls.acc_move_line_obj = cls.env["account.move.line"]
cls.mass_rec_method_obj = cls.env["account.mass.reconcile.method"]
cls.acs_model = cls.env["res.config.settings"]
cls.company = cls.company_data["company"]
cls.bank_journal = cls.company_data["default_journal_bank"]
cls.sale_journal = cls.company_data["default_journal_sale"]
acs_ids = cls.acs_model.search([("company_id", "=", cls.company.id)])
values = {"group_multi_currency": True}
if acs_ids:
acs_ids.write(values)
else:
default_vals = cls.acs_model.default_get([])
default_vals.update(values)
acs_ids = cls.acs_model.create(default_vals)
def test_scenario_reconcile(self):
invoice = self.create_invoice()
self.assertEqual("posted", invoice.state)
receivalble_account_id = invoice.partner_id.property_account_receivable_id.id
# create payment
payment = self.env["account.payment"].create(
{
"partner_type": "customer",
"payment_type": "inbound",
"partner_id": invoice.partner_id.id,
"destination_account_id": receivalble_account_id,
"amount": 50.0,
"journal_id": self.bank_journal.id,
}
)
payment.action_post()
# create the mass reconcile record
mass_rec = self.mass_rec_obj.create(
{
"name": "mass_reconcile_1",
"account": invoice.partner_id.property_account_receivable_id.id,
"reconcile_method": [(0, 0, {"name": "mass.reconcile.simple.partner"})],
}
)
# call the automatic reconciliation method
mass_rec.run_reconcile()
self.assertEqual("paid", invoice.payment_state)
def test_scenario_reconcile_currency(self):
currency_rate = (
self.env["res.currency.rate"]
.sudo()
.search(
[
("currency_id", "=", self.ref("base.USD")),
("company_id", "=", self.ref("base.main_company")),
]
)
.filtered(lambda r: r.name == fields.Date.today())
)
if not currency_rate:
# create currency rate
self.env["res.currency.rate"].create(
{
"name": fields.Date.today(),
"currency_id": self.ref("base.USD"),
"rate": 1.5,
}
)
else:
currency_rate = fields.first(currency_rate)
currency_rate.rate = 1.5
# create invoice
invoice = self._create_invoice(
currency_id=self.ref("base.USD"),
date_invoice=fields.Date.today(),
auto_validate=True,
)
self.assertEqual("posted", invoice.state)
self.env["res.currency.rate"].create(
{
"name": fields.Date.today() - timedelta(days=3),
"currency_id": self.ref("base.USD"),
"rate": 2,
}
)
receivable_account_id = invoice.partner_id.property_account_receivable_id.id
# create payment
payment = self.env["account.payment"].create(
{
"partner_type": "customer",
"payment_type": "inbound",
"partner_id": invoice.partner_id.id,
"destination_account_id": receivable_account_id,
"amount": 50.0,
"currency_id": self.ref("base.USD"),
"journal_id": self.bank_journal.id,
"date": fields.Date.today() - timedelta(days=2),
}
)
payment.action_post()
# create the mass reconcile record
mass_rec = self.mass_rec_obj.create(
{
"name": "mass_reconcile_1",
"account": invoice.partner_id.property_account_receivable_id.id,
"reconcile_method": [(0, 0, {"name": "mass.reconcile.simple.partner"})],
}
)
# call the automatic reconciliation method
mass_rec.run_reconcile()
self.assertEqual("paid", invoice.payment_state)
def test_scenario_reconcile_partial(self):
invoice1 = self.create_invoice()
invoice1.ref = "test ref"
# create payment
receivable_account_id = invoice1.partner_id.property_account_receivable_id.id
payment = self.env["account.payment"].create(
{
"partner_type": "customer",
"payment_type": "inbound",
"partner_id": invoice1.partner_id.id,
"destination_account_id": receivable_account_id,
"amount": 500.0,
"journal_id": self.bank_journal.id,
"ref": "test ref",
}
)
payment.action_post()
line_payment = payment.line_ids.filtered(
lambda l: l.account_id.id == receivable_account_id
)
self.assertEqual(line_payment.reconciled, False)
invoice1_line = invoice1.line_ids.filtered(
lambda l: l.account_id.id == receivable_account_id
)
self.assertEqual(invoice1_line.reconciled, False)
# Create the mass reconcile record
reconcile_method_vals = {
"name": "mass.reconcile.advanced.ref",
"write_off": 0.1,
}
mass_rec = self.mass_rec_obj.create(
{
"name": "mass_reconcile_1",
"account": receivable_account_id,
"reconcile_method": [(0, 0, reconcile_method_vals)],
}
)
mass_rec.run_reconcile()
self.assertEqual(line_payment.amount_residual, -450.0)
self.assertEqual(invoice1_line.reconciled, True)
invoice2 = self._create_invoice(invoice_amount=500, auto_validate=True)
invoice2.ref = "test ref"
invoice2_line = invoice2.line_ids.filtered(
lambda l: l.account_id.id == receivable_account_id
)
mass_rec.run_reconcile()
self.assertEqual(line_payment.reconciled, True)
self.assertEqual(invoice2_line.reconciled, False)
self.assertEqual(invoice2_line.amount_residual, 50.0)
def test_reconcile_with_writeoff(self):
invoice = self.create_invoice()
receivable_account_id = invoice.partner_id.property_account_receivable_id.id
# create payment
payment = self.env["account.payment"].create(
{
"partner_type": "customer",
"payment_type": "inbound",
"partner_id": invoice.partner_id.id,
"destination_account_id": receivable_account_id,
"amount": 50.1,
"journal_id": self.bank_journal.id,
}
)
payment.action_post()
# create the mass reconcile record
mass_rec = self.mass_rec_obj.create(
{
"name": "mass_reconcile_1",
"account": invoice.partner_id.property_account_receivable_id.id,
"reconcile_method": [
(
0,
0,
{
"name": "mass.reconcile.simple.partner",
"account_lost_id": self.company_data[
"default_account_expense"
].id,
"account_profit_id": self.company_data[
"default_account_revenue"
].id,
"journal_id": self.company_data["default_journal_misc"].id,
"write_off": 0.05,
},
)
],
}
)
# call the automatic reconciliation method
mass_rec.run_reconcile()
self.assertEqual("not_paid", invoice.payment_state)
mass_rec.reconcile_method.write_off = 0.11
mass_rec.run_reconcile()
self.assertEqual("paid", invoice.payment_state)
full_reconcile = invoice.line_ids.mapped("full_reconcile_id")
writeoff_line = full_reconcile.reconciled_line_ids.filtered(
lambda l: l.debit == 0.1
)
self.assertEqual(len(writeoff_line), 1)
self.assertEqual(
writeoff_line.move_id.journal_id.id,
self.company_data["default_journal_misc"].id,
)
| 38.281633 | 9,379 |
12,680 |
py
|
PYTHON
|
15.0
|
# Copyright 2012-2016 Camptocamp SA
# Copyright 2010 Sébastien Beau
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import logging
from itertools import product
from odoo import api, models, registry
from odoo.tools.translate import _
_logger = logging.getLogger(__name__)
class MassReconcileAdvanced(models.AbstractModel):
_name = "mass.reconcile.advanced"
_inherit = "mass.reconcile.base"
_description = "Mass Reconcile Advanced"
def _query_debit(self):
"""Select all move (debit>0) as candidate."""
select = self._select_query()
sql_from = self._from_query()
where, params = self._where_query()
where += " AND account_move_line.debit > 0 "
where2, params2 = self._get_filter()
query = " ".join((select, sql_from, where, where2))
self.env.cr.execute(query, params + params2)
return self.env.cr.dictfetchall()
def _query_credit(self):
"""Select all move (credit>0) as candidate."""
select = self._select_query()
sql_from = self._from_query()
where, params = self._where_query()
where += " AND account_move_line.credit > 0 "
where2, params2 = self._get_filter()
query = " ".join((select, sql_from, where, where2))
self.env.cr.execute(query, params + params2)
return self.env.cr.dictfetchall()
@staticmethod
def _matchers(move_line):
"""
Return the values used as matchers to find the opposite lines
All the matcher keys in the dict must have their equivalent in
the `_opposite_matchers`.
The values of each matcher key will be searched in the
one returned by the `_opposite_matchers`
Must be inherited to implement the matchers for one method
As instance, it can return:
return ('ref', move_line['rec'])
or
return (('partner_id', move_line['partner_id']),
('ref', "prefix_%s" % move_line['rec']))
All the matchers have to be found in the opposite lines
to consider them as "opposite"
The matchers will be evaluated in the same order as declared
vs the the opposite matchers, so you can gain performance by
declaring first the partners with the less computation.
All matchers should match with their opposite to be considered
as "matching".
So with the previous example, partner_id and ref have to be
equals on the opposite line matchers.
:return: tuple of tuples (key, value) where the keys are
the matchers keys
(They must be the same that `_opposite_matchers` returns,
and their values to match in the opposite lines.
A matching key can have multiples values.)
"""
raise NotImplementedError
@staticmethod
def _opposite_matchers(move_line):
"""
Return the values of the opposite line used as matchers
so the line is matched
Must be inherited to implement the matchers for one method
It can be inherited to apply some formatting of fields
(strip(), lower() and so on)
This method is the counterpart of the `_matchers()` method.
Each matcher has to yield its value respecting the order
of the `_matchers()`.
When a matcher does not correspond, the next matchers won't
be evaluated so the ones which need the less computation
have to be executed first.
If the `_matchers()` returns:
(('partner_id', move_line['partner_id']),
('ref', move_line['ref']))
Here, you should yield :
yield ('partner_id', move_line['partner_id'])
yield ('ref', move_line['ref'])
Note that a matcher can contain multiple values, as instance,
if for a move line, you want to search from its `ref` in the
`ref` or `name` fields of the opposite move lines, you have to
yield ('partner_id', move_line['partner_id'])
yield ('ref', (move_line['ref'], move_line['name'])
An OR is used between the values for the same key.
An AND is used between the different keys.
:param dict move_line: values of the move_line
:yield: matchers as tuple ('matcher key', value(s))
"""
raise NotImplementedError
@staticmethod
def _compare_values(key, value, opposite_value):
"""Can be inherited to modify the equality condition
specifically according to the matcher key (maybe using
a like operator instead of equality on 'ref' as instance)
"""
# consider that empty vals are not valid matchers
# it can still be inherited for some special cases
# where it would be allowed
if not (value and opposite_value):
return False
if value == opposite_value:
return True
return False
@classmethod
def _compare_matcher_values(cls, key, values, opposite_values):
"""Compare every `values` from a matcher vs an opposite matcher
and return True if it matches
"""
for value, ovalue in product(values, opposite_values):
# we do not need to compare all values, if one matches
# we are done
if cls._compare_values(key, value, ovalue):
return True
return False
@staticmethod
def _compare_matchers(matcher, opposite_matcher):
"""
Prepare and check the matchers to compare
"""
mkey, mvalue = matcher
omkey, omvalue = opposite_matcher
assert mkey == omkey, _(
"A matcher %(mkey)s is compared with a matcher %(omkey)s, the _matchers and "
"_opposite_matchers are probably wrong"
) % {"mkey": mkey, "omkey": omkey}
if not isinstance(mvalue, (list, tuple)):
mvalue = (mvalue,)
if not isinstance(omvalue, (list, tuple)):
omvalue = (omvalue,)
return MassReconcileAdvanced._compare_matcher_values(mkey, mvalue, omvalue)
def _compare_opposite(self, move_line, opposite_move_line, matchers):
"""Iterate over the matchers of the move lines vs opposite move lines
and if they all match, return True.
If all the matchers match for a move line and an opposite move line,
they are candidate for a reconciliation.
"""
opp_matchers = self._opposite_matchers(opposite_move_line)
for matcher in matchers:
try:
opp_matcher = next(opp_matchers)
except StopIteration as e:
# if you fall here, you probably missed to put a `yield`
# in `_opposite_matchers()`
raise ValueError("Missing _opposite_matcher: %s" % matcher[0]) from e
if not self._compare_matchers(matcher, opp_matcher):
# if any of the matcher fails, the opposite line
# is not a valid counterpart
# directly returns so the next yield of _opposite_matchers
# are not evaluated
return False
return True
def _search_opposites(self, move_line, opposite_move_lines):
"""Search the opposite move lines for a move line
:param dict move_line: the move line for which we search opposites
:param list opposite_move_lines: list of dict of move lines values,
the move lines we want to search for
:return: list of matching lines
"""
matchers = self._matchers(move_line)
return [
op
for op in opposite_move_lines
if self._compare_opposite(move_line, op, matchers)
]
def _action_rec(self):
self.flush()
credit_lines = self._query_credit()
debit_lines = self._query_debit()
result = self._rec_auto_lines_advanced(credit_lines, debit_lines)
return result
def _skip_line(self, move_line):
"""
When True is returned on some conditions, the credit move line
will be skipped for reconciliation. Can be inherited to
skip on some conditions. ie: ref or partner_id is empty.
"""
return False
def _rec_group(self, reconcile_groups, lines_by_id):
reconciled_ids = []
for group_count, reconcile_group_ids in enumerate(reconcile_groups, start=1):
_logger.debug(
"Reconciling group %d/%d with ids %s",
group_count,
len(reconcile_groups),
reconcile_group_ids,
)
group_lines = [lines_by_id[lid] for lid in reconcile_group_ids]
reconciled, full = self._reconcile_lines(group_lines, allow_partial=True)
if reconciled and full:
reconciled_ids += reconcile_group_ids
return reconciled_ids
def _rec_group_by_chunk(self, reconcile_groups, lines_by_id, chunk_size):
"""Commit after each chunk
:param list reconcile_groups: all groups to reconcile, will be split
by chunk
:param dict lines_by_id: dict of move lines values,
the move lines we want to search for
:return: list of reconciled lines
"""
reconciled_ids = []
_logger.info("Reconciling by chunk of %d", chunk_size)
# Copy and commit current transient model before creating a new cursor
# This is required to avoid CacheMiss when using data from `self`
# which is created during current transaction.
with registry(self.env.cr.dbname).cursor() as new_cr:
new_env = api.Environment(new_cr, self.env.uid, self.env.context)
self_env = self.with_env(new_env)
rec = self_env.create(self.copy_data())
for i in range(0, len(reconcile_groups), chunk_size):
chunk = reconcile_groups[i : i + chunk_size]
_logger.debug("Reconcile group chunk %s", chunk)
try:
with registry(self.env.cr.dbname).cursor() as new_cr:
new_env = api.Environment(new_cr, self.env.uid, self.env.context)
# Re-use the committed transient we just committed
self_env = self.with_env(new_env).browse(rec.id)
reconciled_ids += self_env._rec_group(chunk, lines_by_id)
except Exception as e:
msg = "Reconciliation failed for group chunk %s with error:\n%s"
_logger.exception(msg, chunk, e)
return reconciled_ids
def _rec_auto_lines_advanced(self, credit_lines, debit_lines):
"""Advanced reconciliation main loop"""
# pylint: disable=invalid-commit
reconciled_ids = []
for rec in self:
commit_every = rec.account_id.company_id.reconciliation_commit_every
reconcile_groups = []
_logger.info("%d credit lines to reconcile", len(credit_lines))
for idx, credit_line in enumerate(credit_lines, start=1):
if idx % 50 == 0:
_logger.info(
"... %d/%d credit lines inspected ...", idx, len(credit_lines)
)
if self._skip_line(credit_line):
continue
opposite_lines = self._search_opposites(credit_line, debit_lines)
if not opposite_lines:
continue
opposite_ids = [opp["id"] for opp in opposite_lines]
line_ids = opposite_ids + [credit_line["id"]]
for group in reconcile_groups:
if any([lid in group for lid in opposite_ids]):
_logger.debug(
"New lines %s matched with an existing " "group %s",
line_ids,
group,
)
group.update(line_ids)
break
else:
_logger.debug("New group of lines matched %s", line_ids)
reconcile_groups.append(set(line_ids))
lines_by_id = {line["id"]: line for line in credit_lines + debit_lines}
_logger.info("Found %d groups to reconcile", len(reconcile_groups))
if commit_every:
reconciled_ids = self._rec_group_by_chunk(
reconcile_groups, lines_by_id, commit_every
)
else:
reconciled_ids = self._rec_group(reconcile_groups, lines_by_id)
_logger.info("Reconciliation is over")
return reconciled_ids
| 40.507987 | 12,679 |
7,766 |
py
|
PYTHON
|
15.0
|
# Copyright 2012-2016 Camptocamp SA
# Copyright 2010 Sébastien Beau
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import models
class MassReconcileAdvancedRef(models.TransientModel):
_name = "mass.reconcile.advanced.ref"
_inherit = "mass.reconcile.advanced"
_description = "Mass Reconcile Advanced Ref"
@staticmethod
def _skip_line(move_line):
"""
When True is returned on some conditions, the credit move line
will be skipped for reconciliation. Can be inherited to
skip on some conditions. ie: ref or partner_id is empty.
"""
return not (move_line.get("ref") and move_line.get("partner_id"))
@staticmethod
def _matchers(move_line):
"""
Return the values used as matchers to find the opposite lines
All the matcher keys in the dict must have their equivalent in
the `_opposite_matchers`.
The values of each matcher key will be searched in the
one returned by the `_opposite_matchers`
Must be inherited to implement the matchers for one method
For instance, it can return:
return ('ref', move_line['rec'])
or
return (('partner_id', move_line['partner_id']),
('ref', "prefix_%s" % move_line['rec']))
All the matchers have to be found in the opposite lines
to consider them as "opposite"
The matchers will be evaluated in the same order as declared
vs the opposite matchers, so you can gain performance by
declaring first the partners with the less computation.
All matchers should match with their opposite to be considered
as "matching".
So with the previous example, partner_id and ref have to be
equals on the opposite line matchers.
:return: tuple of tuples (key, value) where the keys are
the matchers keys
(They must be the same that `_opposite_matchers` returns,
and their values to match in the opposite lines.
A matching key can have multiples values.)
"""
return (
("partner_id", move_line["partner_id"]),
("ref", (move_line["ref"] or "").lower().strip()),
)
@staticmethod
def _opposite_matchers(move_line):
"""
Return the values of the opposite line used as matchers
so the line is matched
Must be inherited to implement the matchers for one method
It can be inherited to apply some formatting of fields
(strip(), lower() and so on)
This method is the counterpart of the `_matchers()` method.
Each matcher has to yield its value respecting the order
of the `_matchers()`.
When a matcher does not correspond, the next matchers won't
be evaluated so the ones which need the less computation
have to be executed first.
If the `_matchers()` returns:
(('partner_id', move_line['partner_id']),
('ref', move_line['ref']))
Here, you should yield :
yield ('partner_id', move_line['partner_id'])
yield ('ref', move_line['ref'])
Note that a matcher can contain multiple values, as instance,
if for a move line, you want to search from its `ref` in the
`ref` or `name` fields of the opposite move lines, you have to
yield ('partner_id', move_line['partner_id'])
yield ('ref', (move_line['ref'], move_line['name'])
An OR is used between the values for the same key.
An AND is used between the different keys.
:param dict move_line: values of the move_line
:yield: matchers as tuple ('matcher key', value(s))
"""
yield ("partner_id", move_line["partner_id"])
yield (
"ref",
(
(move_line["ref"] or "").lower().strip(),
(move_line["name"] or "").lower().strip(),
),
)
class MassReconcileAdvancedName(models.TransientModel):
_name = "mass.reconcile.advanced.name"
_inherit = "mass.reconcile.advanced"
_description = "Mass Reconcile Advanced Name"
@staticmethod
def _skip_line(move_line):
"""
When True is returned on some conditions, the credit move line
will be skipped for reconciliation. Can be inherited to
skip on some conditions. ie: ref or partner_id is empty.
"""
return not (move_line.get("name", "/") != "/" and move_line.get("partner_id"))
@staticmethod
def _matchers(move_line):
"""
Return the values used as matchers to find the opposite lines
All the matcher keys in the dict must have their equivalent in
the `_opposite_matchers`.
The values of each matcher key will be searched in the
one returned by the `_opposite_matchers`
Must be inherited to implement the matchers for one method
For instance, it can return:
return ('ref', move_line['rec'])
or
return (('partner_id', move_line['partner_id']),
('ref', "prefix_%s" % move_line['rec']))
All the matchers have to be found in the opposite lines
to consider them as "opposite"
The matchers will be evaluated in the same order as declared
vs the opposite matchers, so you can gain performance by
declaring first the partners with the less computation.
All matchers should match with their opposite to be considered
as "matching".
So with the previous example, partner_id and ref have to be
equals on the opposite line matchers.
:return: tuple of tuples (key, value) where the keys are
the matchers keys
(They must be the same that `_opposite_matchers` returns,
and their values to match in the opposite lines.
A matching key can have multiples values.)
"""
return (
("partner_id", move_line["partner_id"]),
("name", (move_line["name"] or "").lower().strip()),
)
@staticmethod
def _opposite_matchers(move_line):
"""
Return the values of the opposite line used as matchers
so the line is matched
Must be inherited to implement the matchers for one method
It can be inherited to apply some formatting of fields
(strip(), lower() and so on)
This method is the counterpart of the `_matchers()` method.
Each matcher has to yield its value respecting the order
of the `_matchers()`.
When a matcher does not correspond, the next matchers won't
be evaluated so the ones which need the less computation
have to be executed first.
If the `_matchers()` returns:
(('partner_id', move_line['partner_id']),
('ref', move_line['ref']))
Here, you should yield :
yield ('partner_id', move_line['partner_id'])
yield ('ref', move_line['ref'])
Note that a matcher can contain multiple values, as instance,
if for a move line, you want to search from its `ref` in the
`ref` or `name` fields of the opposite move lines, you have to
yield ('partner_id', move_line['partner_id'])
yield ('ref', (move_line['ref'], move_line['name'])
An OR is used between the values for the same key.
An AND is used between the different keys.
:param dict move_line: values of the move_line
:yield: matchers as tuple ('matcher key', value(s))
"""
yield ("partner_id", move_line["partner_id"])
yield (
"name",
((move_line["name"] or "").lower().strip(),),
)
| 36.116279 | 7,765 |
2,524 |
py
|
PYTHON
|
15.0
|
# Copyright 2012-2016 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import _, api, fields, models
class MassReconcileHistory(models.Model):
"""Store an history of the runs per profile
Each history stores the list of reconciliations done
"""
_name = "mass.reconcile.history"
_description = "Store an history of the runs per profile"
_rec_name = "mass_reconcile_id"
_order = "date DESC"
@api.depends("reconcile_ids")
def _compute_reconcile_line_ids(self):
for rec in self:
rec.reconcile_line_ids = rec.mapped("reconcile_ids.reconciled_line_ids").ids
mass_reconcile_id = fields.Many2one(
"account.mass.reconcile", string="Reconcile Profile", readonly=True
)
date = fields.Datetime(string="Run date", readonly=True, required=True)
reconcile_ids = fields.Many2many(
comodel_name="account.full.reconcile",
relation="account_full_reconcile_history_rel",
string="Full Reconciliations",
readonly=True,
)
reconcile_line_ids = fields.Many2many(
comodel_name="account.move.line",
relation="account_move_line_history_rel",
string="Reconciled Items",
compute="_compute_reconcile_line_ids",
)
company_id = fields.Many2one(
"res.company",
string="Company",
store=True,
readonly=True,
related="mass_reconcile_id.company_id",
)
def _open_move_lines(self):
"""For an history record, open the view of move line with
the reconciled move lines
:param history_id: id of the history
:return: action to open the move lines
"""
move_line_ids = self.mapped("reconcile_ids.reconciled_line_ids").ids
name = _("Reconciliations")
return {
"name": name,
"view_mode": "tree,form",
"view_id": False,
"res_model": "account.move.line",
"type": "ir.actions.act_window",
"nodestroy": True,
"target": "current",
"domain": [("id", "in", move_line_ids)],
}
def open_reconcile(self):
"""For an history record, open the view of move line
with the reconciled move lines
:param history_ids: id of the record as int or long
Accept a list with 1 id too to be
used from the client.
"""
self.ensure_one()
return self._open_move_lines()
| 33.210526 | 2,524 |
3,816 |
py
|
PYTHON
|
15.0
|
# Copyright 2012-2016 Camptocamp SA
# Copyright 2010 Sébastien Beau
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import logging
from odoo import models
_logger = logging.getLogger(__name__)
class MassReconcileSimple(models.AbstractModel):
_name = "mass.reconcile.simple"
_inherit = "mass.reconcile.base"
_description = "Mass Reconcile Simple"
# has to be subclassed
# field name used as key for matching the move lines
_key_field = None
def rec_auto_lines_simple(self, lines):
if self._key_field is None:
raise ValueError("_key_field has to be defined")
count = 0
res = []
while count < len(lines):
for i in range(count + 1, len(lines)):
if lines[count][self._key_field] != lines[i][self._key_field]:
break
check = False
if lines[count]["credit"] > 0 and lines[i]["debit"] > 0:
credit_line = lines[count]
debit_line = lines[i]
check = True
elif lines[i]["credit"] > 0 and lines[count]["debit"] > 0:
credit_line = lines[i]
debit_line = lines[count]
check = True
if not check:
continue
reconciled, dummy = self._reconcile_lines(
[credit_line, debit_line], allow_partial=False
)
if reconciled:
res += [credit_line["id"], debit_line["id"]]
del lines[i]
if (
self.env.context.get("commit_every", 0)
and len(res) % self.env.context["commit_every"] == 0
):
# new cursor is already open in cron
self.env.cr.commit() # pylint: disable=invalid-commit
_logger.info(
"Commit the reconciliations after %d groups", len(res)
)
break
count += 1
return res
def _simple_order(self, *args, **kwargs):
return "ORDER BY account_move_line.%s" % self._key_field
def _action_rec(self):
"""Match only 2 move lines, do not allow partial reconcile"""
select = self._select_query()
select += ", account_move_line.%s " % self._key_field
where, params = self._where_query()
where += " AND account_move_line.%s IS NOT NULL " % self._key_field
where2, params2 = self._get_filter()
query = " ".join(
(select, self._from_query(), where, where2, self._simple_order())
)
self.flush()
self.env.cr.execute(query, params + params2)
lines = self.env.cr.dictfetchall()
return self.rec_auto_lines_simple(lines)
class MassReconcileSimpleName(models.TransientModel):
_name = "mass.reconcile.simple.name"
_inherit = "mass.reconcile.simple"
_description = "Mass Reconcile Simple Name"
# has to be subclassed
# field name used as key for matching the move lines
_key_field = "name"
class MassReconcileSimplePartner(models.TransientModel):
_name = "mass.reconcile.simple.partner"
_inherit = "mass.reconcile.simple"
_description = "Mass Reconcile Simple Partner"
# has to be subclassed
# field name used as key for matching the move lines
_key_field = "partner_id"
class MassReconcileSimpleReference(models.TransientModel):
_name = "mass.reconcile.simple.reference"
_inherit = "mass.reconcile.simple"
_description = "Mass Reconcile Simple Reference"
# has to be subclassed
# field name used as key for matching the move lines
_key_field = "ref"
| 35.654206 | 3,815 |
11,044 |
py
|
PYTHON
|
15.0
|
# Copyright 2012-2016 Camptocamp SA
# Copyright 2010 Sébastien Beau
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import logging
from datetime import datetime
import psycopg2
from psycopg2.extensions import AsIs
from odoo import _, api, exceptions, fields, models, sql_db
from odoo.exceptions import Warning as UserError
_logger = logging.getLogger(__name__)
class MassReconcileOptions(models.AbstractModel):
"""Options of a reconciliation profile
Columns shared by the configuration of methods
and by the reconciliation wizards.
This allows decoupling of the methods and the
wizards and allows to launch the wizards alone
"""
_name = "mass.reconcile.options"
_description = "Options of a reconciliation profile"
@api.model
def _get_rec_base_date(self):
return [("newest", "Most recent move line"), ("actual", "Today")]
write_off = fields.Float("Write off allowed", default=0.0)
account_lost_id = fields.Many2one("account.account", string="Account Lost")
account_profit_id = fields.Many2one("account.account", string="Account Profit")
journal_id = fields.Many2one("account.journal", string="Journal")
date_base_on = fields.Selection(
"_get_rec_base_date",
required=True,
string="Date of reconciliation",
default="newest",
)
_filter = fields.Char(string="Filter")
class AccountMassReconcileMethod(models.Model):
_name = "account.mass.reconcile.method"
_description = "Reconcile Method for account_mass_reconcile"
_inherit = "mass.reconcile.options"
_order = "sequence"
@staticmethod
def _get_reconcilation_methods():
return [
("mass.reconcile.simple.name", "Simple. Amount and Name"),
("mass.reconcile.simple.partner", "Simple. Amount and Partner"),
("mass.reconcile.simple.reference", "Simple. Amount and Reference"),
("mass.reconcile.advanced.ref", "Advanced. Partner and Ref."),
("mass.reconcile.advanced.name", "Advanced. Partner and Name."),
]
def _selection_name(self):
return self._get_reconcilation_methods()
name = fields.Selection("_selection_name", string="Type", required=True)
sequence = fields.Integer(
default=1,
required=True,
help="The sequence field is used to order the reconcile method",
)
task_id = fields.Many2one(
"account.mass.reconcile", string="Task", required=True, ondelete="cascade"
)
company_id = fields.Many2one(
"res.company",
string="Company",
related="task_id.company_id",
store=True,
readonly=True,
)
class AccountMassReconcile(models.Model):
_name = "account.mass.reconcile"
_inherit = ["mail.thread"]
_description = "Account Mass Reconcile"
@api.depends("account")
def _compute_total_unrec(self):
obj_move_line = self.env["account.move.line"]
for rec in self:
rec.unreconciled_count = obj_move_line.search_count(
[
("account_id", "=", rec.account.id),
("reconciled", "=", False),
("parent_state", "=", "posted"),
]
)
@api.depends("history_ids")
def _compute_last_history(self):
# do a search() for retrieving the latest history line,
# as a read() will badly split the list of ids with 'date desc'
# and return the wrong result.
history_obj = self.env["mass.reconcile.history"]
for rec in self:
last_history_rs = history_obj.search(
[("mass_reconcile_id", "=", rec.id)], limit=1, order="date desc"
)
rec.last_history = last_history_rs or False
name = fields.Char(required=True)
account = fields.Many2one("account.account", required=True)
reconcile_method = fields.One2many(
"account.mass.reconcile.method", "task_id", string="Method"
)
unreconciled_count = fields.Integer(
string="Unreconciled Items", compute="_compute_total_unrec"
)
history_ids = fields.One2many(
"mass.reconcile.history", "mass_reconcile_id", string="History", readonly=True
)
last_history = fields.Many2one(
"mass.reconcile.history",
string="Last history",
readonly=True,
compute="_compute_last_history",
)
company_id = fields.Many2one("res.company", string="Company")
@staticmethod
def _prepare_run_transient(rec_method):
return {
"account_id": rec_method.task_id.account.id,
"write_off": rec_method.write_off,
"account_lost_id": rec_method.account_lost_id.id,
"account_profit_id": rec_method.account_profit_id.id,
"journal_id": rec_method.journal_id.id,
"date_base_on": rec_method.date_base_on,
"_filter": rec_method._filter,
}
def _run_reconcile_method(self, reconcile_method):
rec_model = self.env[reconcile_method.name]
auto_rec_id = rec_model.create(self._prepare_run_transient(reconcile_method))
return auto_rec_id.automatic_reconcile()
def run_reconcile(self):
def find_reconcile_ids(fieldname, move_line_ids):
if not move_line_ids:
return []
self.flush()
sql = """
SELECT DISTINCT %s FROM account_move_line
WHERE %s IS NOT NULL AND id in %s
"""
params = [AsIs(fieldname), AsIs(fieldname), tuple(move_line_ids)]
self.env.cr.execute(sql, params)
res = self.env.cr.fetchall()
return [row[0] for row in res]
# we use a new cursor to be able to commit the reconciliation
# often. We have to create it here and not later to avoid problems
# where the new cursor sees the lines as reconciles but the old one
# does not.
for rec in self:
# SELECT FOR UPDATE the mass reconcile row ; this is done in order
# to avoid 2 processes on the same mass reconcile method.
try:
self.env.cr.execute(
"SELECT id FROM account_mass_reconcile"
" WHERE id = %s"
" FOR UPDATE NOWAIT",
(rec.id,),
)
except psycopg2.OperationalError as e:
raise exceptions.UserError(
_(
"A mass reconcile is already ongoing for this account, "
"please try again later."
)
) from e
ctx = self.env.context.copy()
ctx["commit_every"] = rec.account.company_id.reconciliation_commit_every
if ctx["commit_every"]:
new_cr = sql_db.db_connect(self.env.cr.dbname).cursor()
new_env = api.Environment(new_cr, self.env.uid, ctx)
else:
new_cr = self.env.cr
new_env = self.env
try:
all_ml_rec_ids = []
for method in rec.reconcile_method:
ml_rec_ids = self.with_env(new_env)._run_reconcile_method(method)
all_ml_rec_ids += ml_rec_ids
reconcile_ids = find_reconcile_ids("full_reconcile_id", all_ml_rec_ids)
self.env["mass.reconcile.history"].create(
{
"mass_reconcile_id": rec.id,
"date": fields.Datetime.now(),
"reconcile_ids": [(4, rid) for rid in reconcile_ids],
}
)
except Exception as e:
# In case of error, we log it in the mail thread, log the
# stack trace and create an empty history line; otherwise,
# the cron will just loop on this reconcile task.
_logger.exception(
"The reconcile task %s had an exception: %s", rec.name, str(e)
)
message = _("There was an error during reconciliation : %s") % str(e)
rec.message_post(body=message)
self.env["mass.reconcile.history"].create(
{
"mass_reconcile_id": rec.id,
"date": fields.Datetime.now(),
"reconcile_ids": [],
}
)
finally:
if ctx["commit_every"]:
new_cr.commit()
new_cr.close()
return True
def _no_history(self):
"""Raise an `orm.except_orm` error, supposed to
be called when there is no history on the reconciliation
task.
"""
raise UserError(
_("There is no history of reconciled " "items on the task: %s.") % self.name
)
@staticmethod
def _open_move_line_list(move_line_ids, name):
return {
"name": name,
"view_mode": "tree,form",
"view_id": False,
"res_model": "account.move.line",
"type": "ir.actions.act_window",
"nodestroy": True,
"target": "current",
"domain": [("id", "in", move_line_ids)],
}
def open_unreconcile(self):
"""Open the view of move line with the unreconciled move lines"""
self.ensure_one()
obj_move_line = self.env["account.move.line"]
lines = obj_move_line.search(
[
("account_id", "=", self.account.id),
("reconciled", "=", False),
("parent_state", "=", "posted"),
]
)
name = _("Unreconciled items")
return self._open_move_line_list(lines.ids or [], name)
def last_history_reconcile(self):
"""Get the last history record for this reconciliation profile
and return the action which opens move lines reconciled
"""
if not self.last_history:
self._no_history()
return self.last_history.open_reconcile()
@api.model
def run_scheduler(self, run_all=None):
"""Launch the reconcile with the oldest run
This function is mostly here to be used with cron task
:param run_all: if set it will ignore lookup and launch
all reconciliation
:returns: True in case of success or raises an exception
"""
def _get_date(reconcile):
if reconcile.last_history.date:
return fields.Datetime.to_datetime(reconcile.last_history.date)
else:
return datetime.min
reconciles = self.search([])
assert reconciles.ids, "No mass reconcile available"
if run_all:
reconciles.run_reconcile()
return True
reconciles.sorted(key=_get_date)
older = reconciles[0]
older.run_reconcile()
return True
| 36.687708 | 11,043 |
8,039 |
py
|
PYTHON
|
15.0
|
# Copyright 2012-2016 Camptocamp SA
# Copyright 2010 Sébastien Beau
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from operator import itemgetter
from odoo import _, fields, models
from odoo.tools.safe_eval import safe_eval
class MassReconcileBase(models.AbstractModel):
"""Abstract Model for reconciliation methods"""
_name = "mass.reconcile.base"
_inherit = "mass.reconcile.options"
_description = "Mass Reconcile Base"
account_id = fields.Many2one("account.account", string="Account", required=True)
partner_ids = fields.Many2many(
comodel_name="res.partner", string="Restrict on partners"
)
# other fields are inherited from mass.reconcile.options
def automatic_reconcile(self):
"""Reconciliation method called from the view.
:return: list of reconciled ids
"""
self.ensure_one()
return self._action_rec()
def _action_rec(self):
"""Must be inherited to implement the reconciliation
:return: list of reconciled ids
"""
raise NotImplementedError
@staticmethod
def _base_columns():
"""Mandatory columns for move lines queries
An extra column aliased as ``key`` should be defined
in each query."""
aml_cols = (
"id",
"debit",
"credit",
"currency_id",
"amount_residual",
"amount_residual_currency",
"date",
"ref",
"name",
"partner_id",
"account_id",
"reconciled",
"move_id",
)
return ["account_move_line.{}".format(col) for col in aml_cols]
def _selection_columns(self):
return self._base_columns()
def _select_query(self, *args, **kwargs):
return "SELECT %s" % ", ".join(self._selection_columns())
def _from_query(self, *args, **kwargs):
return "FROM account_move_line "
def _where_query(self, *args, **kwargs):
self.ensure_one()
where = (
"WHERE account_move_line.account_id = %s "
"AND NOT account_move_line.reconciled "
"AND parent_state = 'posted'"
)
# it would be great to use dict for params
# but as we use _where_calc in _get_filter
# which returns a list, we have to
# accommodate with that
params = [self.account_id.id]
if self.partner_ids:
where += " AND account_move_line.partner_id IN %s"
params.append(tuple(line.id for line in self.partner_ids))
return where, params
def _get_filter(self):
self.ensure_one()
ml_obj = self.env["account.move.line"]
where = ""
params = []
if self._filter:
dummy, where, params = ml_obj._where_calc(safe_eval(self._filter)).get_sql()
if where:
where = " AND %s" % where
return where, params
def _below_writeoff_limit(self, lines, writeoff_limit):
self.ensure_one()
precision = self.env["decimal.precision"].precision_get("Account")
writeoff_amount = round(
sum(line["amount_residual"] for line in lines), precision
)
writeoff_amount_curr = round(
sum(line["amount_residual_currency"] for line in lines), precision
)
first_currency = lines[0]["currency_id"]
if all([line["currency_id"] == first_currency for line in lines]):
ref_amount = writeoff_amount_curr
same_curr = True
# TODO if currency != company currency compute writeoff_limit in currency
else:
ref_amount = writeoff_amount
same_curr = False
return (
bool(writeoff_limit >= abs(ref_amount)),
writeoff_amount,
writeoff_amount_curr,
same_curr,
)
def _get_rec_date(self, lines, based_on="end_period_last_credit"):
self.ensure_one()
def last_date(mlines):
return max(mlines, key=itemgetter("date"))
def credit(mlines):
return [line for line in mlines if line["credit"] > 0]
def debit(mlines):
return [line for line in mlines if line["debit"] > 0]
if based_on == "newest":
return last_date(lines)["date"]
elif based_on == "newest_credit":
return last_date(credit(lines))["date"]
elif based_on == "newest_debit":
return last_date(debit(lines))["date"]
# reconcilation date will be today
# when date is None
return None
def create_write_off(self, lines, amount, amount_curr, same_curr):
self.ensure_one()
if amount < 0:
account = self.account_profit_id
else:
account = self.account_lost_id
currency = same_curr and lines[0].currency_id or lines[0].company_id.currency_id
journal = self.journal_id
partners = lines.mapped("partner_id")
write_off_vals = {
"name": _("Automatic writeoff"),
"amount_currency": same_curr and amount_curr or amount,
"debit": amount > 0.0 and amount or 0.0,
"credit": amount < 0.0 and -amount or 0.0,
"partner_id": len(partners) == 1 and partners.id or False,
"account_id": account.id,
"journal_id": journal.id,
"currency_id": currency.id,
}
counterpart_account = lines.mapped("account_id")
counter_part = write_off_vals.copy()
counter_part["debit"] = write_off_vals["credit"]
counter_part["credit"] = write_off_vals["debit"]
counter_part["amount_currency"] = -write_off_vals["amount_currency"]
counter_part["account_id"] = (counterpart_account.id,)
move = self.env["account.move"].create(
{
"date": lines.env.context.get("date_p"),
"journal_id": journal.id,
"currency_id": currency.id,
"line_ids": [(0, 0, write_off_vals), (0, 0, counter_part)],
}
)
move.action_post()
return move.line_ids.filtered(
lambda l: l.account_id.id == counterpart_account.id
)
def _reconcile_lines(self, lines, allow_partial=False):
"""Try to reconcile given lines
:param list lines: list of dict of move lines, they must at least
contain values for : id, debit, credit, amount_residual and
amount_residual_currency
:param boolean allow_partial: if True, partial reconciliation will be
created, otherwise only Full
reconciliation will be created
:return: tuple of boolean values, first item is wether the items
have been reconciled or not,
the second is wether the reconciliation is full (True)
or partial (False)
"""
self.ensure_one()
ml_obj = self.env["account.move.line"]
(
below_writeoff,
amount_writeoff,
amount_writeoff_curr,
same_curr,
) = self._below_writeoff_limit(lines, self.write_off)
rec_date = self._get_rec_date(lines, self.date_base_on)
line_rs = ml_obj.browse([line["id"] for line in lines]).with_context(
date_p=rec_date, comment=_("Automatic Write Off")
)
if below_writeoff:
balance = amount_writeoff_curr if same_curr else amount_writeoff
if abs(balance) != 0.0:
writeoff_line = self.create_write_off(
line_rs, amount_writeoff, amount_writeoff_curr, same_curr
)
line_rs |= writeoff_line
line_rs.reconcile()
return True, True
elif allow_partial:
line_rs.reconcile()
return True, False
return False, False
| 35.883929 | 8,038 |
778 |
py
|
PYTHON
|
15.0
|
# Copyright 2014-2016 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class AccountConfigSettings(models.TransientModel):
_inherit = "res.config.settings"
reconciliation_commit_every = fields.Integer(
related="company_id.reconciliation_commit_every",
string="How often to commit when performing automatic reconciliation.",
help="Leave zero to commit only at the end of the process.",
readonly=False,
)
class Company(models.Model):
_inherit = "res.company"
reconciliation_commit_every = fields.Integer(
string="How often to commit when performing automatic reconciliation.",
help="Leave zero to commit only at the end of the process.",
)
| 32.416667 | 778 |
725 |
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Account Reconciliation Widget Due Date",
"version": "15.0.1.0.0",
"website": "https://github.com/OCA/account-reconcile",
"author": "Tecnativa, Odoo Community Association (OCA)",
"license": "AGPL-3",
"application": False,
"installable": True,
"depends": ["account_reconciliation_widget"],
"maintainers": ["victoralmau"],
"development_status": "Production/Stable",
"data": ["views/account_bank_statement_line_view.xml"],
"assets": {
"web.assets_backend": [
"/account_reconciliation_widget_due_date/static/src/js/*",
],
},
}
| 34.428571 | 723 |
6,381 |
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from datetime import date
from odoo.tests.common import Form, TransactionCase
class TestAccountReconciliationWidgetDueDate(TransactionCase):
def setUp(self):
super().setUp()
self.company = self.env.ref("base.main_company")
self.journal = self.env["account.journal"].create(
{"name": "Test journal bank", "type": "bank", "code": "BANK-TEST"}
)
self.account = self.env["account.account"].create(
{
"name": "Account Receivable",
"code": "AR",
"user_type_id": self.env.ref("account.data_account_type_receivable").id,
"reconcile": True,
}
)
self.partner_a = self.env["res.partner"].create(
{
"name": "Partner Test A",
"property_account_receivable_id": self.account.id,
}
)
self.partner_b = self.partner_a.copy({"name": "Partner Test B"})
self.partner_c = self.partner_a.copy({"name": "Partner Test C"})
self.statement = self._create_account_bank_statement()
def _create_account_bank_statement(self):
statement_form = Form(self.env["account.bank.statement"])
statement_form.journal_id = self.journal
statement_form.date = date(2021, 3, 1)
statement_form.balance_end_real = 600.00
with statement_form.line_ids.new() as line_form:
line_form.date = "2021-01-01"
line_form.payment_ref = "LINE_A"
line_form.partner_id = self.partner_a
line_form.amount = 100.00
with statement_form.line_ids.new() as line_form:
line_form.date = "2021-02-01"
line_form.date_due = "2021-02-05"
line_form.payment_ref = "LINE_B"
line_form.partner_id = self.partner_b
line_form.amount = 200.00
with statement_form.line_ids.new() as line_form:
line_form.date = "2021-03-01"
line_form.payment_ref = "LINE_C"
line_form.partner_id = self.partner_c
line_form.amount = 300.00
return statement_form.save()
def test_account_reconciliation_widget(self):
self.assertEqual(self.statement.state, "open")
self.statement.button_post()
self.assertEqual(self.statement.state, "posted")
self.assertEqual(len(self.statement.line_ids), 3)
reconciliation_widget = self.env["account.reconciliation.widget"]
account_move_model = self.env["account.move"]
# line_a
line_a = self.statement.line_ids.filtered(
lambda x: x.partner_id == self.partner_a
)
self.assertFalse(line_a.date_due, False)
new_aml_dicts = [
{
"account_id": self.partner_a.property_account_receivable_id.id,
"name": line_a.name,
"credit": line_a.amount,
}
]
res = reconciliation_widget.process_bank_statement_line(
line_a.id,
[{"partner_id": line_a.partner_id.id, "new_aml_dicts": new_aml_dicts}],
)
self.assertEqual(len(res["moves"]), 1)
move = account_move_model.browse(res["moves"][0])
self.assertEqual(move.line_ids, line_a.line_ids)
move_line_credit = move.line_ids.filtered(lambda x: x.debit > 0)
self.assertFalse(move_line_credit.date_maturity)
self.assertEqual(move_line_credit.partner_id, self.partner_a)
# Check that the date_maturity does not change
move_line_credit.date_maturity = date(2021, 2, 5)
reconciliation_widget.update_bank_statement_line_due_date(
res["moves"],
[line_a.id],
[line_a.date_due],
)
self.assertEqual(move_line_credit.date_maturity, date(2021, 2, 5))
# line_b
line_b = self.statement.line_ids.filtered(
lambda x: x.partner_id == self.partner_b
)
self.assertEqual(line_b.date_due, date(2021, 2, 5))
new_aml_dicts = [
{
"account_id": self.partner_b.property_account_receivable_id.id,
"name": line_b.name,
"credit": line_b.amount,
}
]
res = reconciliation_widget.process_bank_statement_line(
[line_b.id],
[{"partner_id": line_b.partner_id.id, "new_aml_dicts": new_aml_dicts}],
)
reconciliation_widget.update_bank_statement_line_due_date(
res["moves"],
[line_b.id],
[line_b.date_due],
)
self.assertEqual(len(res["moves"]), 1)
move = account_move_model.browse(res["moves"][0])
self.assertEqual(move.line_ids, line_b.line_ids)
move_line_credit = move.line_ids.filtered(lambda x: x.debit > 0)
self.assertEqual(move_line_credit.date_maturity, date(2021, 2, 5))
self.assertEqual(move_line_credit.partner_id, self.partner_b)
# line_c
line_c = self.statement.line_ids.filtered(
lambda x: x.partner_id == self.partner_c
)
self.assertFalse(line_c.date_due)
new_aml_dicts = [
{
"account_id": self.partner_c.property_account_receivable_id.id,
"name": line_c.name,
"credit": line_c.amount,
}
]
res = reconciliation_widget.process_bank_statement_line(
[line_c.id],
[{"partner_id": line_c.partner_id.id, "new_aml_dicts": new_aml_dicts}],
)
reconciliation_widget.update_bank_statement_line_due_date(
res["moves"],
[line_c.id],
["2021-02-05"],
)
self.assertEqual(line_c.date_due, date(2021, 2, 5))
self.assertEqual(len(res["moves"]), 1)
move = account_move_model.browse(res["moves"][0])
self.assertEqual(move.line_ids, line_c.line_ids)
move_line_credit = move.line_ids.filtered(lambda x: x.debit > 0)
self.assertEqual(move_line_credit.date_maturity, date(2021, 2, 5))
self.assertEqual(move_line_credit.partner_id, self.partner_c)
# Confirm statement
self.statement.button_validate_or_action()
self.assertEqual(self.statement.state, "confirm")
| 42.245033 | 6,379 |
1,185 |
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - Víctor Martínez
# Copyright 2021 Tecnativa - Alexandre D. Díaz
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import api, models
from odoo.tools.misc import format_date, parse_date
class AccountReconciliation(models.AbstractModel):
_inherit = "account.reconciliation.widget"
@api.model
def _get_statement_line(self, st_line):
data = super()._get_statement_line(st_line)
data["date_due"] = format_date(self.env, st_line.date_due)
return data
@api.model
def update_bank_statement_line_due_date(self, move_ids, st_line_ids, dates):
"""'move_ids', 'st_line_ids' and 'dates' must have the same length"""
account_move_obj = self.env["account.move"]
st_line_move_obj = self.env["account.bank.statement.line"]
for index, move_id in enumerate(move_ids):
move_record = account_move_obj.browse(move_id)
st_line = st_line_move_obj.browse(st_line_ids[index])
st_line.date_due = parse_date(self.env, dates[index])
if st_line.date_due:
move_record.line_ids.date_maturity = st_line.date_due
| 42.214286 | 1,182 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.