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
512
py
PYTHON
15.0
# Copyright 2016 Cédric Pigeon # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Queue Job Subscribe", "version": "15.0.1.0.0", "author": "Acsone SA/NV, Odoo Community Association (OCA)", "website": "https://github.com/OCA/queue", "summary": "Control which users are subscribed to queue job notifications", "license": "AGPL-3", "category": "Generic Modules", "depends": ["queue_job"], "data": ["views/res_users_view.xml"], "installable": True, }
36.5
511
3,570
py
PYTHON
15.0
# Copyright 2016 Cédric Pigeon # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import odoo.tests.common as common from odoo.addons.queue_job.job import Job class TestJobSubscribe(common.TransactionCase): def setUp(self): super(TestJobSubscribe, self).setUp() grp_queue_job_manager = self.ref("queue_job.group_queue_job_manager") self.other_partner_a = self.env["res.partner"].create( {"name": "My Company a", "is_company": True, "email": "[email protected]"} ) self.other_user_a = self.env["res.users"].create( { "partner_id": self.other_partner_a.id, "login": "my_login a", "name": "my user", "groups_id": [(4, grp_queue_job_manager)], } ) self.other_partner_b = self.env["res.partner"].create( {"name": "My Company b", "is_company": True, "email": "[email protected]"} ) self.other_user_b = self.env["res.users"].create( { "partner_id": self.other_partner_b.id, "login": "my_login_b", "name": "my user 1", "groups_id": [(4, grp_queue_job_manager)], } ) def _create_failed_job(self): method = self.env["res.users"].with_user(self.other_user_a).mapped test_job = Job(method) test_job.store() test_job_record = self.env["queue.job"].search([("uuid", "=", test_job.uuid)]) test_job_record.write({"state": "failed"}) return test_job_record def test_job_subscription(self): """ When a job is created, all user of group queue_job.group_queue_job_manager are automatically set as follower except if the flag subscribe_job is not set """ ################################# # Test 1: All users are followers ################################# stored = self._create_failed_job() users = self.env["res.users"].search( [("groups_id", "=", self.ref("queue_job.group_queue_job_manager"))] ) self.assertEqual(len(stored.message_follower_ids), len(users)) expected_partners = [u.partner_id for u in users] self.assertSetEqual( set(stored.mapped("message_follower_ids.partner_id")), set(expected_partners), ) followers_id = [f.id for f in stored.mapped("message_follower_ids.partner_id")] self.assertIn(self.other_partner_a.id, followers_id) self.assertIn(self.other_partner_b.id, followers_id) ########################################### # Test 2: User b request to not be follower ########################################### self.other_user_b.write({"subscribe_job": False}) stored = self._create_failed_job() users = self.env["res.users"].search( [ ("groups_id", "=", self.ref("queue_job.group_queue_job_manager")), ("subscribe_job", "=", True), ] ) self.assertEqual(len(stored.message_follower_ids), len(users)) expected_partners = [u.partner_id for u in users] self.assertSetEqual( set(stored.mapped("message_follower_ids.partner_id")), set(expected_partners), ) followers_id = [f.id for f in stored.mapped("message_follower_ids.partner_id")] self.assertIn(self.other_partner_a.id, followers_id) self.assertNotIn(self.other_partner_b.id, followers_id)
41.022989
3,569
345
py
PYTHON
15.0
# Copyright 2016 Cédric Pigeon # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import models class QueueJob(models.Model): _inherit = "queue.job" def _subscribe_users_domain(self): domain = super()._subscribe_users_domain() domain.append(("subscribe_job", "=", True)) return domain
26.461538
344
435
py
PYTHON
15.0
# Copyright 2016 Cédric Pigeon # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class ResUsers(models.Model): _inherit = "res.users" subscribe_job = fields.Boolean( "Job Notifications", default=True, help="If this flag is checked and the " "user is Connector Manager, he will " "receive job notifications.", index=True, )
24.111111
434
535
py
PYTHON
15.0
# Copyright 2016 Camptocamp SA # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) { "name": "Queue Job Tests", "version": "15.0.2.2.0", "author": "Camptocamp,Odoo Community Association (OCA)", "license": "LGPL-3", "category": "Generic Modules", "depends": ["queue_job"], "website": "https://github.com/OCA/queue", "data": [ "data/queue_job_channel_data.xml", "data/queue_job_function_data.xml", "security/ir.model.access.csv", ], "installable": True, }
29.722222
535
29,453
py
PYTHON
15.0
# Copyright 2016 Camptocamp SA # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) import hashlib from datetime import datetime, timedelta from unittest import mock import odoo.tests.common as common from odoo.addons.queue_job import identity_exact from odoo.addons.queue_job.delay import DelayableGraph from odoo.addons.queue_job.exception import ( FailedJobError, NoSuchJobError, RetryableJobError, ) from odoo.addons.queue_job.job import ( DONE, ENQUEUED, FAILED, PENDING, RETRY_INTERVAL, STARTED, WAIT_DEPENDENCIES, Job, ) from .common import JobCommonCase class TestJobsOnTestingMethod(JobCommonCase): """Test Job""" def test_new_job(self): """ Create a job """ test_job = Job(self.method) self.assertEqual(test_job.func.__func__, self.method.__func__) def test_eta(self): """When an `eta` is datetime, it uses it""" now = datetime.now() method = self.env["res.users"].mapped job_a = Job(method, eta=now) self.assertEqual(job_a.eta, now) def test_eta_integer(self): """When an `eta` is an integer, it adds n seconds up to now""" datetime_path = "odoo.addons.queue_job.job.datetime" with mock.patch(datetime_path, autospec=True) as mock_datetime: mock_datetime.now.return_value = datetime(2015, 3, 15, 16, 41, 0) job_a = Job(self.method, eta=60) self.assertEqual(job_a.eta, datetime(2015, 3, 15, 16, 42, 0)) def test_eta_timedelta(self): """When an `eta` is a timedelta, it adds it up to now""" datetime_path = "odoo.addons.queue_job.job.datetime" with mock.patch(datetime_path, autospec=True) as mock_datetime: mock_datetime.now.return_value = datetime(2015, 3, 15, 16, 41, 0) delta = timedelta(hours=3) job_a = Job(self.method, eta=delta) self.assertEqual(job_a.eta, datetime(2015, 3, 15, 19, 41, 0)) def test_perform_args(self): test_job = Job(self.method, args=("o", "k"), kwargs={"c": "!"}) result = test_job.perform() self.assertEqual(result, (("o", "k"), {"c": "!"})) def test_retryable_error(self): test_job = Job(self.method, kwargs={"raise_retry": True}, max_retries=3) self.assertEqual(test_job.retry, 0) with self.assertRaises(RetryableJobError): test_job.perform() self.assertEqual(test_job.retry, 1) with self.assertRaises(RetryableJobError): test_job.perform() self.assertEqual(test_job.retry, 2) with self.assertRaises(FailedJobError): test_job.perform() self.assertEqual(test_job.retry, 3) def test_infinite_retryable_error(self): test_job = Job(self.method, kwargs={"raise_retry": True}, max_retries=0) self.assertEqual(test_job.retry, 0) with self.assertRaises(RetryableJobError): test_job.perform() self.assertEqual(test_job.retry, 1) def test_on_instance_method(self): class A(object): def method(self): pass with self.assertRaises(TypeError): Job(A.method) def test_on_model_method(self): job_ = Job(self.env["test.queue.job"].testing_method) self.assertEqual(job_.model_name, "test.queue.job") self.assertEqual(job_.method_name, "testing_method") def test_invalid_function(self): with self.assertRaises(TypeError): Job(1) def test_set_pending(self): job_a = Job(self.method) job_a.set_pending(result="test") self.assertEqual(job_a.state, PENDING) self.assertFalse(job_a.date_enqueued) self.assertFalse(job_a.date_started) self.assertEqual(job_a.retry, 0) self.assertEqual(job_a.result, "test") def test_set_enqueued(self): job_a = Job(self.method) datetime_path = "odoo.addons.queue_job.job.datetime" with mock.patch(datetime_path, autospec=True) as mock_datetime: mock_datetime.now.return_value = datetime(2015, 3, 15, 16, 41, 0) job_a.set_enqueued() self.assertEqual(job_a.state, ENQUEUED) self.assertEqual(job_a.date_enqueued, datetime(2015, 3, 15, 16, 41, 0)) self.assertFalse(job_a.date_started) def test_set_started(self): job_a = Job(self.method) datetime_path = "odoo.addons.queue_job.job.datetime" with mock.patch(datetime_path, autospec=True) as mock_datetime: mock_datetime.now.return_value = datetime(2015, 3, 15, 16, 41, 0) job_a.set_started() self.assertEqual(job_a.state, STARTED) self.assertEqual(job_a.date_started, datetime(2015, 3, 15, 16, 41, 0)) def test_worker_pid(self): """When a job is started, it gets the PID of the worker that starts it""" method = self.env["res.users"].mapped job_a = Job(method) self.assertFalse(job_a.worker_pid) with mock.patch("os.getpid", autospec=True) as mock_getpid: mock_getpid.return_value = 99999 job_a.set_started() self.assertEqual(job_a.worker_pid, 99999) # reset the pid job_a.set_pending() self.assertFalse(job_a.worker_pid) def test_set_done(self): job_a = Job(self.method) job_a.date_started = datetime(2015, 3, 15, 16, 40, 0) datetime_path = "odoo.addons.queue_job.job.datetime" with mock.patch(datetime_path, autospec=True) as mock_datetime: mock_datetime.now.return_value = datetime(2015, 3, 15, 16, 41, 0) job_a.set_done(result="test") self.assertEqual(job_a.state, DONE) self.assertEqual(job_a.result, "test") self.assertEqual(job_a.date_done, datetime(2015, 3, 15, 16, 41, 0)) self.assertEqual(job_a.exec_time, 60.0) self.assertFalse(job_a.exc_info) def test_set_failed(self): job_a = Job(self.method) job_a.set_failed( exc_info="failed test", exc_name="FailedTest", exc_message="Sadly this job failed", ) self.assertEqual(job_a.state, FAILED) self.assertEqual(job_a.exc_info, "failed test") self.assertEqual(job_a.exc_name, "FailedTest") self.assertEqual(job_a.exc_message, "Sadly this job failed") def test_postpone(self): job_a = Job(self.method) datetime_path = "odoo.addons.queue_job.job.datetime" with mock.patch(datetime_path, autospec=True) as mock_datetime: mock_datetime.now.return_value = datetime(2015, 3, 15, 16, 41, 0) job_a.postpone(result="test", seconds=60) self.assertEqual(job_a.eta, datetime(2015, 3, 15, 16, 42, 0)) self.assertEqual(job_a.result, "test") self.assertFalse(job_a.exc_info) def test_store(self): test_job = Job(self.method) test_job.store() stored = self.queue_job.search([("uuid", "=", test_job.uuid)]) self.assertEqual(len(stored), 1) def test_store_extra_data(self): test_job = Job(self.method) test_job.store() stored = self.queue_job.search([("uuid", "=", test_job.uuid)]) self.assertEqual(stored.additional_info, "JUST_TESTING") test_job.set_failed(exc_info="failed test", exc_name="FailedTest") test_job.store() stored.invalidate_cache() self.assertEqual(stored.additional_info, "JUST_TESTING_BUT_FAILED") def test_read(self): eta = datetime.now() + timedelta(hours=5) test_job = Job( self.method, args=("o", "k"), kwargs={"c": "!"}, priority=15, eta=eta, description="My description", ) test_job.worker_pid = 99999 # normally set on "set_start" test_job.company_id = self.env.ref("base.main_company").id test_job.store() job_read = Job.load(self.env, test_job.uuid) self.assertEqual(test_job.uuid, job_read.uuid) self.assertEqual(test_job.model_name, job_read.model_name) self.assertEqual(test_job.func.__func__, job_read.func.__func__) self.assertEqual(test_job.args, job_read.args) self.assertEqual(test_job.kwargs, job_read.kwargs) self.assertEqual(test_job.method_name, job_read.method_name) self.assertEqual(test_job.description, job_read.description) self.assertEqual(test_job.state, job_read.state) self.assertEqual(test_job.priority, job_read.priority) self.assertEqual(test_job.exc_info, job_read.exc_info) self.assertEqual(test_job.result, job_read.result) self.assertEqual(test_job.user_id, job_read.user_id) self.assertEqual(test_job.company_id, job_read.company_id) self.assertEqual(test_job.worker_pid, 99999) delta = timedelta(seconds=1) # DB does not keep milliseconds self.assertAlmostEqual( test_job.date_created, job_read.date_created, delta=delta ) self.assertAlmostEqual( test_job.date_started, job_read.date_started, delta=delta ) self.assertAlmostEqual( test_job.date_enqueued, job_read.date_enqueued, delta=delta ) self.assertAlmostEqual(test_job.date_done, job_read.date_done, delta=delta) self.assertAlmostEqual(test_job.eta, job_read.eta, delta=delta) test_date = datetime(2015, 3, 15, 21, 7, 0) job_read.date_enqueued = test_date job_read.date_started = test_date job_read.date_done = test_date job_read.store() job_read = Job.load(self.env, test_job.uuid) self.assertAlmostEqual(job_read.date_started, test_date, delta=delta) self.assertAlmostEqual(job_read.date_enqueued, test_date, delta=delta) self.assertAlmostEqual(job_read.date_done, test_date, delta=delta) self.assertAlmostEqual(job_read.exec_time, 0.0) def test_job_unlinked(self): test_job = Job(self.method, args=("o", "k"), kwargs={"c": "!"}) test_job.store() stored = self.queue_job.search([("uuid", "=", test_job.uuid)]) stored.unlink() with self.assertRaises(NoSuchJobError): Job.load(self.env, test_job.uuid) def test_unicode(self): test_job = Job( self.method, args=("öô¿‽", "ñě"), kwargs={"c": "ßø"}, priority=15, description="My dé^Wdescription", ) test_job.store() job_read = Job.load(self.env, test_job.uuid) self.assertEqual(test_job.args, job_read.args) self.assertEqual(job_read.args, ("öô¿‽", "ñě")) self.assertEqual(test_job.kwargs, job_read.kwargs) self.assertEqual(job_read.kwargs, {"c": "ßø"}) self.assertEqual(test_job.description, job_read.description) self.assertEqual(job_read.description, "My dé^Wdescription") def test_accented_bytestring(self): test_job = Job( self.method, args=("öô¿‽", "ñě"), kwargs={"c": "ßø"}, priority=15, description="My dé^Wdescription", ) test_job.store() job_read = Job.load(self.env, test_job.uuid) self.assertEqual(job_read.args, ("öô¿‽", "ñě")) self.assertEqual(job_read.kwargs, {"c": "ßø"}) self.assertEqual(job_read.description, "My dé^Wdescription") def test_job_delay(self): self.cr.execute("delete from queue_job") job_ = self.env["test.queue.job"].with_delay().testing_method() stored = self.queue_job.search([]) self.assertEqual(len(stored), 1) self.assertEqual(stored.uuid, job_.uuid, "Incorrect returned Job UUID") def test_job_delay_model_method(self): self.cr.execute("delete from queue_job") delayable = self.env["test.queue.job"].with_delay() job_instance = delayable.testing_method("a", k=1) self.assertTrue(job_instance) result = job_instance.perform() self.assertEqual(result, (("a",), {"k": 1})) def test_job_identity_key_str(self): id_key = "e294e8444453b09d59bdb6efbfec1323" test_job_1 = Job( self.method, priority=15, description="Test I am the first one", identity_key=id_key, ) test_job_1.store() job1 = Job.load(self.env, test_job_1.uuid) self.assertEqual(job1.identity_key, id_key) def test_job_identity_key_func_exact(self): hasher = hashlib.sha1() hasher.update(b"test.queue.job") hasher.update(b"testing_method") hasher.update(str(sorted([])).encode("utf-8")) hasher.update(str((1, "foo")).encode("utf-8")) hasher.update(str(sorted({"bar": "baz"}.items())).encode("utf-8")) expected_key = hasher.hexdigest() test_job_1 = Job( self.method, args=[1, "foo"], kwargs={"bar": "baz"}, identity_key=identity_exact, ) self.assertEqual(test_job_1.identity_key, expected_key) test_job_1.store() job1 = Job.load(self.env, test_job_1.uuid) self.assertEqual(job1.identity_key, expected_key) class TestJobs(JobCommonCase): """Test jobs on other methods or with different job configuration""" def test_description(self): """If no description is given to the job, it should be computed from the function """ # if a docstring is defined for the function # it's used as description job_a = Job(self.env["test.queue.job"].testing_method) self.assertEqual(job_a.description, "Method used for tests") # if no docstring, the description is computed job_b = Job(self.env["test.queue.job"].no_description) self.assertEqual(job_b.description, "test.queue.job.no_description") # case when we explicitly specify the description description = "My description" job_a = Job(self.env["test.queue.job"].testing_method, description=description) self.assertEqual(job_a.description, description) def test_retry_pattern(self): """When we specify a retry pattern, the eta must follow it""" datetime_path = "odoo.addons.queue_job.job.datetime" method = self.env["test.queue.job"].job_with_retry_pattern with mock.patch(datetime_path, autospec=True) as mock_datetime: mock_datetime.now.return_value = datetime(2015, 6, 1, 15, 10, 0) test_job = Job(method, max_retries=0) test_job.retry += 1 test_job.postpone(self.env) self.assertEqual(test_job.retry, 1) self.assertEqual(test_job.eta, datetime(2015, 6, 1, 15, 11, 0)) test_job.retry += 1 test_job.postpone(self.env) self.assertEqual(test_job.retry, 2) self.assertEqual(test_job.eta, datetime(2015, 6, 1, 15, 13, 0)) test_job.retry += 1 test_job.postpone(self.env) self.assertEqual(test_job.retry, 3) self.assertEqual(test_job.eta, datetime(2015, 6, 1, 15, 10, 10)) test_job.retry += 1 test_job.postpone(self.env) self.assertEqual(test_job.retry, 4) self.assertEqual(test_job.eta, datetime(2015, 6, 1, 15, 10, 10)) test_job.retry += 1 test_job.postpone(self.env) self.assertEqual(test_job.retry, 5) self.assertEqual(test_job.eta, datetime(2015, 6, 1, 15, 15, 0)) def test_retry_pattern_no_zero(self): """When we specify a retry pattern without 0, uses RETRY_INTERVAL""" method = self.env["test.queue.job"].job_with_retry_pattern__no_zero test_job = Job(method, max_retries=0) test_job.retry += 1 self.assertEqual(test_job.retry, 1) self.assertEqual(test_job._get_retry_seconds(), RETRY_INTERVAL) test_job.retry += 1 self.assertEqual(test_job.retry, 2) self.assertEqual(test_job._get_retry_seconds(), RETRY_INTERVAL) test_job.retry += 1 self.assertEqual(test_job.retry, 3) self.assertEqual(test_job._get_retry_seconds(), 180) test_job.retry += 1 self.assertEqual(test_job.retry, 4) self.assertEqual(test_job._get_retry_seconds(), 180) def test_job_delay_model_method_multi(self): rec1 = self.env["test.queue.job"].create({"name": "test1"}) rec2 = self.env["test.queue.job"].create({"name": "test2"}) recs = rec1 + rec2 job_instance = recs.with_delay().mapped("name") self.assertTrue(job_instance) self.assertEqual(job_instance.args, ("name",)) self.assertEqual(job_instance.recordset, recs) self.assertEqual(job_instance.model_name, "test.queue.job") self.assertEqual(job_instance.method_name, "mapped") self.assertEqual(["test1", "test2"], job_instance.perform()) def test_job_identity_key_no_duplicate(self): """If a job with same identity key in queue do not add a new one""" id_key = "e294e8444453b09d59bdb6efbfec1323" rec1 = self.env["test.queue.job"].create({"name": "test1"}) job_1 = rec1.with_delay(identity_key=id_key).mapped("name") self.assertTrue(job_1) job_2 = rec1.with_delay(identity_key=id_key).mapped("name") self.assertEqual(job_2.uuid, job_1.uuid) def test_job_with_mutable_arguments(self): """Job with mutable arguments do not mutate on perform()""" delayable = self.env["test.queue.job"].with_delay() job_instance = delayable.job_alter_mutable([1], mutable_kwarg={"a": 1}) self.assertTrue(job_instance) result = job_instance.perform() self.assertEqual(result, ([1, 2], {"a": 1, "b": 2})) job_instance.set_done() # at this point, the 'args' and 'kwargs' of the job instance # might have been modified, but they must never be modified in # the queue_job table after their creation, so a new 'load' will # get the initial values. job_instance.store() # jobs are always loaded before being performed, so we simulate # this behavior here to check if we have the correct initial arguments job_instance = Job.load(self.env, job_instance.uuid) self.assertEqual(([1],), job_instance.args) self.assertEqual({"mutable_kwarg": {"a": 1}}, job_instance.kwargs) def test_store_env_su_no_sudo(self): demo_user = self.env.ref("base.user_demo") self.env = self.env(user=demo_user) delayable = self.env["test.queue.job"].with_delay() test_job = delayable.testing_method() stored = test_job.db_record() job_instance = Job.load(self.env, stored.uuid) self.assertFalse(job_instance.recordset.env.su) self.assertTrue(job_instance.user_id, demo_user) def test_store_env_su_sudo(self): demo_user = self.env.ref("base.user_demo") self.env = self.env(user=demo_user) delayable = self.env["test.queue.job"].sudo().with_delay() test_job = delayable.testing_method() stored = test_job.db_record() job_instance = Job.load(self.env, stored.uuid) self.assertTrue(job_instance.recordset.env.su) self.assertTrue(job_instance.user_id, demo_user) class TestJobModel(JobCommonCase): def test_job_change_state(self): stored = self._create_job() stored._change_job_state(DONE, result="test") self.assertEqual(stored.state, DONE) self.assertEqual(stored.result, "test") stored._change_job_state(PENDING, result="test2") self.assertEqual(stored.state, PENDING) self.assertEqual(stored.result, "test2") with self.assertRaises(ValueError): # only PENDING and DONE supported stored._change_job_state(STARTED) def test_button_done(self): stored = self._create_job() stored.button_done() self.assertEqual(stored.state, DONE) self.assertEqual( stored.result, "Manually set to done by %s" % self.env.user.name ) def test_requeue(self): stored = self._create_job() stored.write({"state": "failed"}) stored.requeue() self.assertEqual(stored.state, PENDING) def test_requeue_wait_dependencies_not_touched(self): job_root = Job(self.env["test.queue.job"].testing_method) job_child = Job(self.env["test.queue.job"].testing_method) job_child.add_depends({job_root}) job_root.store() job_child.store() DelayableGraph._ensure_same_graph_uuid([job_root, job_child]) record_root = job_root.db_record() record_child = job_child.db_record() self.assertEqual(record_root.state, PENDING) self.assertEqual(record_child.state, WAIT_DEPENDENCIES) record_root.write({"state": "failed"}) (record_root + record_child).requeue() self.assertEqual(record_root.state, PENDING) self.assertEqual(record_child.state, WAIT_DEPENDENCIES) def test_message_when_write_fail(self): stored = self._create_job() stored.write({"state": "failed"}) self.assertEqual(stored.state, FAILED) messages = stored.message_ids self.assertEqual(len(messages), 1) def test_follower_when_write_fail(self): """Check that inactive users doesn't are not followers even if they are linked to an active partner""" group = self.env.ref("queue_job.group_queue_job_manager") vals = { "name": "xx", "login": "xx", "groups_id": [(6, 0, [group.id])], "active": False, } inactiveusr = self.user.create(vals) inactiveusr.partner_id.active = True self.assertFalse(inactiveusr in group.users) stored = self._create_job() stored.write({"state": "failed"}) followers = stored.message_follower_ids.mapped("partner_id") self.assertFalse(inactiveusr.partner_id in followers) self.assertFalse({u.partner_id for u in group.users} - set(followers)) def test_wizard_requeue(self): stored = self._create_job() stored.write({"state": "failed"}) model = self.env["queue.requeue.job"] model = model.with_context(active_model="queue.job", active_ids=stored.ids) model.create({}).requeue() self.assertEqual(stored.state, PENDING) def test_context_uuid(self): delayable = self.env["test.queue.job"].with_delay() test_job = delayable.testing_method(return_context=True) result = test_job.perform() key_present = "job_uuid" in result self.assertTrue(key_present) self.assertEqual(result["job_uuid"], test_job._uuid) def test_override_channel(self): delayable = self.env["test.queue.job"].with_delay(channel="root.sub.sub") test_job = delayable.testing_method(return_context=True) self.assertEqual("root.sub.sub", test_job.channel) def test_job_change_user_id(self): demo_user = self.env.ref("base.user_demo") stored = self._create_job() stored.user_id = demo_user self.assertEqual(stored.records.env.uid, demo_user.id) class TestJobStorageMultiCompany(common.TransactionCase): """Test storage of jobs""" def setUp(self): super(TestJobStorageMultiCompany, self).setUp() self.queue_job = self.env["queue.job"] grp_queue_job_manager = self.ref("queue_job.group_queue_job_manager") User = self.env["res.users"] Company = self.env["res.company"] Partner = self.env["res.partner"] main_company = self.env.ref("base.main_company") self.partner_user = Partner.create( {"name": "Simple User", "email": "[email protected]"} ) self.simple_user = User.create( { "partner_id": self.partner_user.id, "company_ids": [(4, main_company.id)], "login": "simple_user", "name": "simple user", "groups_id": [], } ) self.other_partner_a = Partner.create( {"name": "My Company a", "is_company": True, "email": "[email protected]"} ) self.other_company_a = Company.create( { "name": "My Company a", "partner_id": self.other_partner_a.id, "currency_id": self.ref("base.EUR"), } ) self.other_user_a = User.create( { "partner_id": self.other_partner_a.id, "company_id": self.other_company_a.id, "company_ids": [(4, self.other_company_a.id)], "login": "my_login a", "name": "my user A", "groups_id": [(4, grp_queue_job_manager)], } ) self.other_partner_b = Partner.create( {"name": "My Company b", "is_company": True, "email": "[email protected]"} ) self.other_company_b = Company.create( { "name": "My Company b", "partner_id": self.other_partner_b.id, "currency_id": self.ref("base.EUR"), } ) self.other_user_b = User.create( { "partner_id": self.other_partner_b.id, "company_id": self.other_company_b.id, "company_ids": [(4, self.other_company_b.id)], "login": "my_login_b", "name": "my user B", "groups_id": [(4, grp_queue_job_manager)], } ) def _create_job(self, env): self.cr.execute("delete from queue_job") env["test.queue.job"].with_delay().testing_method() stored = self.queue_job.search([]) self.assertEqual(len(stored), 1) return stored def test_job_default_company_id(self): """the default company is the one from the current user_id""" stored = self._create_job(self.env) self.assertEqual( stored.company_id.id, self.ref("base.main_company"), "Incorrect default company_id", ) env = self.env(user=self.other_user_b.id) stored = self._create_job(env) self.assertEqual( stored.company_id.id, self.other_company_b.id, "Incorrect default company_id", ) def test_job_no_company_id(self): """if we put an empty company_id in the context jobs are created without company_id """ env = self.env(context={"company_id": None}) stored = self._create_job(env) self.assertFalse(stored.company_id, "Company_id should be empty") def test_job_specific_company_id(self): """If a company_id specified in the context it's used by default for the job creation""" env = self.env(context={"company_id": self.other_company_a.id}) stored = self._create_job(env) self.assertEqual( stored.company_id.id, self.other_company_a.id, "Incorrect company_id" ) def test_job_subscription(self): # if the job is created without company_id, all members of # queue_job.group_queue_job_manager must be followers User = self.env["res.users"] no_company_context = dict(self.env.context, company_id=None) no_company_env = self.env(user=self.simple_user, context=no_company_context) stored = self._create_job(no_company_env) stored._message_post_on_failure() users = ( User.search( [("groups_id", "=", self.ref("queue_job.group_queue_job_manager"))] ) + stored.user_id ) self.assertEqual(len(stored.message_follower_ids), len(users)) expected_partners = [u.partner_id for u in users] self.assertSetEqual( set(stored.message_follower_ids.mapped("partner_id")), set(expected_partners), ) followers_id = stored.message_follower_ids.mapped("partner_id.id") self.assertIn(self.other_partner_a.id, followers_id) self.assertIn(self.other_partner_b.id, followers_id) # jobs created for a specific company_id are followed only by # company's members company_a_context = dict(self.env.context, company_id=self.other_company_a.id) company_a_env = self.env(user=self.simple_user, context=company_a_context) stored = self._create_job(company_a_env) stored.with_user(self.other_user_a.id) stored._message_post_on_failure() # 2 because simple_user (creator of job) + self.other_partner_a self.assertEqual(len(stored.message_follower_ids), 2) users = self.simple_user + self.other_user_a expected_partners = [u.partner_id for u in users] self.assertSetEqual( set(stored.message_follower_ids.mapped("partner_id")), set(expected_partners), ) followers_id = stored.message_follower_ids.mapped("partner_id.id") self.assertIn(self.other_partner_a.id, followers_id) self.assertNotIn(self.other_partner_b.id, followers_id)
40.965181
29,413
2,025
py
PYTHON
15.0
# Copyright 2020 Camptocamp SA # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) from odoo.tests.common import tagged from odoo.addons.queue_job.job import Job from .common import JobCommonCase @tagged("post_install", "-at_install") class TestJobAutoDelay(JobCommonCase): """Test auto delay of jobs""" def test_auto_delay(self): """method decorated by @job_auto_delay is automatically delayed""" result = self.env["test.queue.job"].delay_me(1, kwarg=2) self.assertTrue(isinstance(result, Job)) self.assertEqual(result.args, (1,)) self.assertEqual(result.kwargs, {"kwarg": 2}) def test_auto_delay_options(self): """method automatically delayed une <method>_job_options arguments""" result = self.env["test.queue.job"].delay_me_options() self.assertTrue(isinstance(result, Job)) self.assertEqual(result.identity_key, "my_job_identity") def test_auto_delay_inside_job(self): """when a delayed job is processed, it must not delay itself""" job_ = self.env["test.queue.job"].delay_me(1, kwarg=2) self.assertTrue(job_.perform(), (1, 2)) def test_auto_delay_force_sync(self): """method forced to run synchronously""" result = ( self.env["test.queue.job"] .with_context(_job_force_sync=True) .delay_me(1, kwarg=2) ) self.assertTrue(result, (1, 2)) def test_auto_delay_context_key_set(self): """patched with context_key delays only if context keys is set""" result = ( self.env["test.queue.job"] .with_context(auto_delay_delay_me_context_key=True) .delay_me_context_key() ) self.assertTrue(isinstance(result, Job)) def test_auto_delay_context_key_unset(self): """patched with context_key do not delay if context keys is not set""" result = self.env["test.queue.job"].delay_me_context_key() self.assertEqual(result, "ok")
37.5
2,025
10,135
py
PYTHON
15.0
# Copyright 2019 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html) import odoo.tests.common as common from odoo.addons.queue_job.delay import DelayableGraph, chain, group from odoo.addons.queue_job.job import PENDING, WAIT_DEPENDENCIES, Job class TestJobDependencies(common.TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.queue_job = cls.env["queue.job"] cls.method = cls.env["test.queue.job"].testing_method def test_depends_store(self): job_root = Job(self.method) job_lvl1_a = Job(self.method) job_lvl1_a.add_depends({job_root}) job_lvl1_b = Job(self.method) job_lvl1_b.add_depends({job_root}) job_lvl2_a = Job(self.method) job_lvl2_a.add_depends({job_lvl1_a}) # Jobs must be stored after the dependencies are set up. # (Or if not, a new store must be called on the parent) job_root.store() job_lvl1_a.store() job_lvl1_b.store() job_lvl2_a.store() # test properties self.assertFalse(job_root.depends_on) self.assertEqual(job_lvl1_a.depends_on, {job_root}) self.assertEqual(job_lvl1_b.depends_on, {job_root}) self.assertEqual(job_lvl2_a.depends_on, {job_lvl1_a}) self.assertEqual(job_root.reverse_depends_on, {job_lvl1_a, job_lvl1_b}) self.assertEqual(job_lvl1_a.reverse_depends_on, {job_lvl2_a}) self.assertFalse(job_lvl1_b.reverse_depends_on) self.assertFalse(job_lvl2_a.reverse_depends_on) # test DB state self.assertEqual(job_root.db_record().dependencies["depends_on"], []) self.assertEqual( sorted(job_root.db_record().dependencies["reverse_depends_on"]), sorted([job_lvl1_a.uuid, job_lvl1_b.uuid]), ) self.assertEqual( job_lvl1_a.db_record().dependencies["depends_on"], [job_root.uuid] ) self.assertEqual( job_lvl1_a.db_record().dependencies["reverse_depends_on"], [job_lvl2_a.uuid] ) self.assertEqual( job_lvl1_b.db_record().dependencies["depends_on"], [job_root.uuid] ) self.assertEqual(job_lvl1_b.db_record().dependencies["reverse_depends_on"], []) self.assertEqual( job_lvl2_a.db_record().dependencies["depends_on"], [job_lvl1_a.uuid] ) self.assertEqual(job_lvl2_a.db_record().dependencies["reverse_depends_on"], []) def test_depends_store_after(self): job_root = Job(self.method) job_root.store() job_a = Job(self.method) job_a.add_depends({job_root}) job_a.store() # as the reverse dependency has been added after the root job has been # stored, it is not reflected in DB self.assertEqual(job_root.db_record().dependencies["reverse_depends_on"], []) # a new store will write it job_root.store() self.assertEqual( job_root.db_record().dependencies["reverse_depends_on"], [job_a.uuid] ) def test_depends_load(self): job_root = Job(self.method) job_a = Job(self.method) job_a.add_depends({job_root}) job_root.store() job_a.store() read_job_root = Job.load(self.env, job_root.uuid) self.assertEqual(read_job_root.reverse_depends_on, {job_a}) read_job_a = Job.load(self.env, job_a.uuid) self.assertEqual(read_job_a.depends_on, {job_root}) def test_depends_enqueue_waiting_single(self): job_root = Job(self.method) job_a = Job(self.method) job_a.add_depends({job_root}) DelayableGraph._ensure_same_graph_uuid([job_root, job_a]) job_root.store() job_a.store() self.assertEqual(job_a.state, WAIT_DEPENDENCIES) # these are the steps run by RunJobController job_root.perform() job_root.set_done() job_root.store() self.env["base"].flush() job_root.enqueue_waiting() # Will be picked up by the jobrunner. # Warning: as the state has been changed in memory but # not in the job_a instance, here, we re-read it. # In practice, it won't be an issue for the jobrunner. self.assertEqual(Job.load(self.env, job_a.uuid).state, PENDING) def test_dependency_graph(self): job_root = Job(self.method) job_lvl1_a = Job(self.method) job_lvl1_a.add_depends({job_root}) job_lvl1_b = Job(self.method) job_lvl1_b.add_depends({job_root}) job_lvl2_a = Job(self.method) job_lvl2_a.add_depends({job_lvl1_a}) DelayableGraph._ensure_same_graph_uuid( [ job_root, job_lvl1_a, job_lvl1_b, job_lvl2_a, ] ) job_2_root = Job(self.method) job_2_child = Job(self.method) job_2_child.add_depends({job_2_root}) DelayableGraph._ensure_same_graph_uuid([job_2_root, job_2_child]) # Jobs must be stored after the dependencies are set up. # (Or if not, a new store must be called on the parent) job_root.store() job_lvl1_a.store() job_lvl1_b.store() job_lvl2_a.store() job_2_root.store() job_2_child.store() record_root = job_root.db_record() record_lvl1_a = job_lvl1_a.db_record() record_lvl1_b = job_lvl1_b.db_record() record_lvl2_a = job_lvl2_a.db_record() record_2_root = job_2_root.db_record() record_2_child = job_2_child.db_record() expected_nodes = [ { "id": record_root.id, "title": "<strong>Method used for tests</strong><br/>" "test.queue.job().testing_method()", "color": "#D2E5FF", "border": "#2B7CE9", "shadow": True, }, { "id": record_lvl1_a.id, "title": "<strong>Method used for tests</strong><br/>" "test.queue.job().testing_method()", "color": "#D2E5FF", "border": "#2B7CE9", "shadow": True, }, { "id": record_lvl1_b.id, "title": "<strong>Method used for tests</strong><br/>" "test.queue.job().testing_method()", "color": "#D2E5FF", "border": "#2B7CE9", "shadow": True, }, { "id": record_lvl2_a.id, "title": "<strong>Method used for tests</strong><br/>" "test.queue.job().testing_method()", "color": "#D2E5FF", "border": "#2B7CE9", "shadow": True, }, ] expected_edges = sorted( [ [record_root.id, record_lvl1_a.id], [record_lvl1_a.id, record_lvl2_a.id], [record_root.id, record_lvl1_b.id], ] ) records = [record_root, record_lvl1_a, record_lvl1_b, record_lvl2_a] for record in records: self.assertEqual( sorted(record.dependency_graph["nodes"], key=lambda d: d["id"]), expected_nodes, ) self.assertEqual(sorted(record.dependency_graph["edges"]), expected_edges) expected_nodes = [ { "id": record_2_root.id, "title": "<strong>Method used for tests</strong><br/>" "test.queue.job().testing_method()", "color": "#D2E5FF", "border": "#2B7CE9", "shadow": True, }, { "id": record_2_child.id, "title": "<strong>Method used for tests</strong><br/>" "test.queue.job().testing_method()", "color": "#D2E5FF", "border": "#2B7CE9", "shadow": True, }, ] expected_edges = sorted([[record_2_root.id, record_2_child.id]]) for record in [record_2_root, record_2_child]: self.assertEqual( sorted(record.dependency_graph["nodes"], key=lambda d: d["id"]), expected_nodes, ) self.assertEqual(sorted(record.dependency_graph["edges"]), expected_edges) def test_no_dependency_graph_single_job(self): """A single job has no graph""" job = self.env["test.queue.job"].with_delay().testing_method() self.assertEqual(job.db_record().dependency_graph, {}) self.assertIsNone(job.graph_uuid) def test_depends_graph_uuid(self): """All jobs in a graph share the same graph uuid""" model = self.env["test.queue.job"] delayable1 = model.delayable().testing_method(1) delayable2 = model.delayable().testing_method(2) delayable3 = model.delayable().testing_method(3) delayable4 = model.delayable().testing_method(4) group1 = group(delayable1, delayable2) group2 = group(delayable3, delayable4) chain_root = chain(group1, group2) chain_root.delay() jobs = [ delayable._generated_job for delayable in [delayable1, delayable2, delayable3, delayable4] ] self.assertTrue(jobs[0].graph_uuid) self.assertEqual(len({j.graph_uuid for j in jobs}), 1) for job in jobs: self.assertEqual(job.graph_uuid, job.db_record().graph_uuid) def test_depends_graph_uuid_group(self): """All jobs in a group share the same graph uuid""" g = group( self.env["test.queue.job"].delayable().testing_method(), self.env["test.queue.job"].delayable().testing_method(), ) g.delay() jobs = [delayable._generated_job for delayable in g._delayables] self.assertTrue(jobs[0].graph_uuid) self.assertTrue(jobs[1].graph_uuid) self.assertEqual(jobs[0].graph_uuid, jobs[1].graph_uuid)
35.069204
10,135
13,998
py
PYTHON
15.0
# Copyright 2021 Guewen Baconnier # license lgpl-3.0 or later (http://www.gnu.org/licenses/lgpl.html) import os from unittest import mock import odoo.tests.common as common from odoo.tools import mute_logger from odoo.addons.queue_job.delay import Delayable from odoo.addons.queue_job.job import identity_exact from odoo.addons.queue_job.tests.common import mock_with_delay, trap_jobs class TestDelayMocks(common.TransactionCase): def test_trap_jobs_on_with_delay_model(self): with trap_jobs() as trap: self.env["test.queue.job"].button_that_uses_with_delay() trap.assert_jobs_count(1) trap.assert_jobs_count(1, only=self.env["test.queue.job"].testing_method) trap.assert_enqueued_job( self.env["test.queue.job"].testing_method, args=(1,), kwargs={"foo": 2}, properties=dict( channel="root.test", description="Test", eta=15, identity_key=identity_exact, max_retries=1, priority=15, ), ) def test_trap_jobs_on_with_delay_recordset(self): recordset = self.env["test.queue.job"].create({"name": "test"}) with trap_jobs() as trap: recordset.button_that_uses_with_delay() trap.assert_jobs_count(1) trap.assert_jobs_count(1, only=recordset.testing_method) trap.assert_enqueued_job( recordset.testing_method, args=(1,), kwargs={"foo": 2}, properties=dict( channel="root.test", description="Test", eta=15, identity_key=identity_exact, max_retries=1, priority=15, ), ) def test_trap_jobs_on_with_delay_recordset_no_properties(self): """Verify that trap_jobs() can omit properties""" recordset = self.env["test.queue.job"].create({"name": "test"}) with trap_jobs() as trap: recordset.button_that_uses_with_delay() trap.assert_enqueued_job( recordset.testing_method, args=(1,), kwargs={"foo": 2}, ) def test_trap_jobs_on_with_delay_recordset_partial_properties(self): """Verify that trap_jobs() can check partially properties""" recordset = self.env["test.queue.job"].create({"name": "test"}) with trap_jobs() as trap: recordset.button_that_uses_with_delay() trap.assert_enqueued_job( recordset.testing_method, args=(1,), kwargs={"foo": 2}, properties=dict( description="Test", eta=15, ), ) def test_trap_jobs_on_with_delay_assert_model_count_mismatch(self): recordset = self.env["test.queue.job"].create({"name": "test"}) with trap_jobs() as trap: self.env["test.queue.job"].button_that_uses_with_delay() trap.assert_jobs_count(1) with self.assertRaises(AssertionError, msg="0 != 1"): trap.assert_jobs_count(1, only=recordset.testing_method) def test_trap_jobs_on_with_delay_assert_recordset_count_mismatch(self): recordset = self.env["test.queue.job"].create({"name": "test"}) with trap_jobs() as trap: recordset.button_that_uses_with_delay() trap.assert_jobs_count(1) with self.assertRaises(AssertionError, msg="0 != 1"): trap.assert_jobs_count( 1, only=self.env["test.queue.job"].testing_method ) def test_trap_jobs_on_with_delay_assert_model_enqueued_mismatch(self): recordset = self.env["test.queue.job"].create({"name": "test"}) with trap_jobs() as trap: recordset.button_that_uses_with_delay() trap.assert_jobs_count(1) message = ( r"Job <test\.queue.job\(\)>\.testing_method\(1, foo=2\) with " r"properties \(channel=root\.test, description=Test, eta=15, " "identity_key=<function identity_exact at 0x[0-9a-fA-F]+>, " "max_retries=1, priority=15\\) was not enqueued\\.\n" "Actual enqueued jobs:\n" r" \* <test.queue.job\(%s,\)>.testing_method\(1, foo=2\) with properties " r"\(priority=15, max_retries=1, eta=15, description=Test, channel=root.test, " r"identity_key=<function identity_exact at 0x[0-9a-fA-F]+>\)" ) % (recordset.id,) with self.assertRaisesRegex(AssertionError, message): trap.assert_enqueued_job( self.env["test.queue.job"].testing_method, args=(1,), kwargs={"foo": 2}, properties=dict( channel="root.test", description="Test", eta=15, identity_key=identity_exact, max_retries=1, priority=15, ), ) def test_trap_jobs_on_with_delay_assert_recordset_enqueued_mismatch(self): recordset = self.env["test.queue.job"].create({"name": "test"}) with trap_jobs() as trap: self.env["test.queue.job"].button_that_uses_with_delay() trap.assert_jobs_count(1) message = ( r"Job <test\.queue.job\(%s,\)>\.testing_method\(1, foo=2\) with " r"properties \(channel=root\.test, description=Test, eta=15, " "identity_key=<function identity_exact at 0x[0-9a-fA-F]+>, " "max_retries=1, priority=15\\) was not enqueued\\.\n" "Actual enqueued jobs:\n" r" \* <test.queue.job\(\)>.testing_method\(1, foo=2\) with properties " r"\(priority=15, max_retries=1, eta=15, description=Test, channel=root.test, " r"identity_key=<function identity_exact at 0x[0-9a-fA-F]+>\)" ) % (recordset.id,) with self.assertRaisesRegex(AssertionError, message): trap.assert_enqueued_job( recordset.testing_method, args=(1,), kwargs={"foo": 2}, properties=dict( channel="root.test", description="Test", eta=15, identity_key=identity_exact, max_retries=1, priority=15, ), ) def test_trap_jobs_on_graph(self): with trap_jobs() as trap: self.env["test.queue.job"].button_that_uses_delayable_chain() trap.assert_jobs_count(3) trap.assert_jobs_count(2, only=self.env["test.queue.job"].testing_method) trap.assert_jobs_count(1, only=self.env["test.queue.job"].no_description) trap.assert_enqueued_job( self.env["test.queue.job"].testing_method, args=(1,), kwargs={"foo": 2}, properties=dict( channel="root.test", description="Test", eta=15, identity_key=identity_exact, max_retries=1, priority=15, ), ) trap.assert_enqueued_job( self.env["test.queue.job"].testing_method, args=("x",), kwargs={"foo": "y"}, ) trap.assert_enqueued_job( self.env["test.queue.job"].no_description, ) trap.perform_enqueued_jobs() def test_trap_jobs_perform(self): with trap_jobs() as trap: model = self.env["test.queue.job"] model.with_delay(priority=1).create_ir_logging( "test_trap_jobs_perform single" ) node = Delayable(model).create_ir_logging("test_trap_jobs_perform graph 1") node2 = Delayable(model).create_ir_logging("test_trap_jobs_perform graph 2") node3 = Delayable(model).create_ir_logging("test_trap_jobs_perform graph 3") node2.on_done(node3) node3.on_done(node) node2.delay() # jobs are not executed logs = self.env["ir.logging"].search( [ ("name", "=", "test_queue_job"), ("func", "=", "create_ir_logging"), ], order="id asc", ) self.assertEqual(len(logs), 0) trap.assert_jobs_count(4) # perform the jobs trap.perform_enqueued_jobs() logs = self.env["ir.logging"].search( [ ("name", "=", "test_queue_job"), ("func", "=", "create_ir_logging"), ], order="id asc", ) self.assertEqual(len(logs), 4) # check if they are executed in order self.assertEqual(logs[0].message, "test_trap_jobs_perform single") self.assertEqual(logs[1].message, "test_trap_jobs_perform graph 2") self.assertEqual(logs[2].message, "test_trap_jobs_perform graph 3") self.assertEqual(logs[3].message, "test_trap_jobs_perform graph 1") def test_mock_with_delay(self): with mock_with_delay() as (delayable_cls, delayable): self.env["test.queue.job"].button_that_uses_with_delay() self.assertEqual(delayable_cls.call_count, 1) # arguments passed in 'with_delay()' delay_args, delay_kwargs = delayable_cls.call_args self.assertEqual(delay_args, (self.env["test.queue.job"],)) self.assertDictEqual( delay_kwargs, { "channel": "root.test", "description": "Test", "eta": 15, "identity_key": identity_exact, "max_retries": 1, "priority": 15, }, ) # check what's passed to the job method 'testing_method' self.assertEqual(delayable.testing_method.call_count, 1) delay_args, delay_kwargs = delayable.testing_method.call_args self.assertEqual(delay_args, (1,)) self.assertDictEqual(delay_kwargs, {"foo": 2}) @mute_logger("odoo.addons.queue_job.models.base") @mock.patch.dict(os.environ, {"TEST_QUEUE_JOB_NO_DELAY": "1"}) def test_delay_graph_direct_exec_env_var(self): node = Delayable(self.env["test.queue.job"]).create_ir_logging( "test_delay_graph_direct_exec 1" ) node2 = Delayable(self.env["test.queue.job"]).create_ir_logging( "test_delay_graph_direct_exec 2" ) node2.on_done(node) node2.delay() # jobs are executed directly logs = self.env["ir.logging"].search( [ ("name", "=", "test_queue_job"), ("func", "=", "create_ir_logging"), ], order="id asc", ) self.assertEqual(len(logs), 2) # check if they are executed in order self.assertEqual(logs[0].message, "test_delay_graph_direct_exec 2") self.assertEqual(logs[1].message, "test_delay_graph_direct_exec 1") @mute_logger("odoo.addons.queue_job.models.base") def test_delay_graph_direct_exec_context_key(self): node = Delayable( self.env["test.queue.job"].with_context(test_queue_job_no_delay=True) ).create_ir_logging("test_delay_graph_direct_exec 1") node2 = Delayable(self.env["test.queue.job"]).create_ir_logging( "test_delay_graph_direct_exec 2" ) node2.on_done(node) node2.delay() # jobs are executed directly logs = self.env["ir.logging"].search( [ ("name", "=", "test_queue_job"), ("func", "=", "create_ir_logging"), ], order="id asc", ) self.assertEqual(len(logs), 2) # check if they are executed in order self.assertEqual(logs[0].message, "test_delay_graph_direct_exec 2") self.assertEqual(logs[1].message, "test_delay_graph_direct_exec 1") @mute_logger("odoo.addons.queue_job.models.base") @mock.patch.dict(os.environ, {"TEST_QUEUE_JOB_NO_DELAY": "1"}) def test_delay_with_delay_direct_exec_env_var(self): model = self.env["test.queue.job"] model.with_delay().create_ir_logging("test_delay_graph_direct_exec 1") # jobs are executed directly logs = self.env["ir.logging"].search( [ ("name", "=", "test_queue_job"), ("func", "=", "create_ir_logging"), ], order="id asc", ) self.assertEqual(len(logs), 1) self.assertEqual(logs[0].message, "test_delay_graph_direct_exec 1") @mute_logger("odoo.addons.queue_job.models.base") def test_delay_with_delay_direct_exec_context_key(self): model = self.env["test.queue.job"].with_context(test_queue_job_no_delay=True) model.with_delay().create_ir_logging("test_delay_graph_direct_exec 1") # jobs are executed directly logs = self.env["ir.logging"].search( [ ("name", "=", "test_queue_job"), ("func", "=", "create_ir_logging"), ], order="id asc", ) self.assertEqual(len(logs), 1) self.assertEqual(logs[0].message, "test_delay_graph_direct_exec 1")
41.292035
13,998
2,266
py
PYTHON
15.0
# Copyright 2019 Versada UAB # License LGPL-3 or later (https://www.gnu.org/licenses/lgpl). from datetime import datetime, timedelta from .common import JobCommonCase class TestQueueJobAutovacuumCronJob(JobCommonCase): @classmethod def setUpClass(cls): super().setUpClass() cls.cron_job = cls.env.ref("queue_job.ir_cron_autovacuum_queue_jobs") def test_old_jobs_are_deleted_by_cron_job(self): """Old jobs are deleted by the autovacuum cron job.""" date_done = datetime.now() - timedelta( days=self.queue_job._removal_interval + 1 ) stored = self._create_job() stored.write({"date_done": date_done}) self.cron_job.method_direct_trigger() self.assertFalse(stored.exists()) def test_autovacuum(self): # test default removal interval stored = self._create_job() date_done = datetime.now() - timedelta(days=29) stored.write({"date_done": date_done}) self.env["queue.job"].autovacuum() self.assertEqual(len(self.env["queue.job"].search([])), 1) date_done = datetime.now() - timedelta(days=31) stored.write({"date_done": date_done}) self.env["queue.job"].autovacuum() self.assertEqual(len(self.env["queue.job"].search([])), 0) def test_autovacuum_multi_channel(self): root_channel = self.env.ref("queue_job.channel_root") channel_60days = self.env["queue.job.channel"].create( {"name": "60days", "removal_interval": 60, "parent_id": root_channel.id} ) date_done = datetime.now() - timedelta(days=31) job_root = self._create_job() job_root.write({"date_done": date_done}) job_60days = self._create_job() job_60days.write( {"channel": channel_60days.complete_name, "date_done": date_done} ) self.assertEqual(len(self.env["queue.job"].search([])), 2) self.env["queue.job"].autovacuum() self.assertEqual(len(self.env["queue.job"].search([])), 1) date_done = datetime.now() - timedelta(days=61) job_60days.write({"date_done": date_done}) self.env["queue.job"].autovacuum() self.assertEqual(len(self.env["queue.job"].search([])), 0)
39.068966
2,266
4,167
py
PYTHON
15.0
# Copyright 2014-2016 Camptocamp SA # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) import odoo.tests.common as common from odoo import exceptions class TestRelatedAction(common.TransactionCase): """Test Related Actions""" @classmethod def setUpClass(cls): super().setUpClass() cls.model = cls.env["test.related.action"] cls.record = cls.model.create({}) cls.records = cls.record + cls.model.create({}) def test_attributes(self): """Job with related action check if action returns correctly""" job_ = self.record.with_delay().testing_related_action__kwargs() act_job, act_kwargs = job_.related_action() self.assertEqual(act_job, job_.db_record()) self.assertEqual(act_kwargs, {"b": 4}) def test_decorator_empty(self): """Job with decorator without value disable the default action The ``related_action`` configuration is: ``{"enable": False}`` """ # default action returns None job_ = self.record.with_delay().testing_related_action__return_none() self.assertIsNone(job_.related_action()) def test_model_no_action(self): """Model shows an error when no action exist""" job_ = self.record.with_delay().testing_related_action__return_none() with self.assertRaises(exceptions.UserError): # db_record is the 'job.queue' record on which we click on the # button to open the related action job_.db_record().open_related_action() def test_default_no_record(self): """Default related action called when no decorator is set When called on no record. The ``related_action`` configuration is: ``{}`` """ job_ = self.model.with_delay().testing_related_action__no() expected = None self.assertEqual(job_.related_action(), expected) def test_model_default_no_record(self): """Model shows an error when using the default action and we have no record linke to the job""" job_ = self.model.with_delay().testing_related_action__no() with self.assertRaises(exceptions.UserError): # db_record is the 'job.queue' record on which we click on the # button to open the related action job_.db_record().open_related_action() def test_default_one_record(self): """Default related action called when no decorator is set When called on one record. The ``related_action`` configuration is: ``{}`` """ job_ = self.record.with_delay().testing_related_action__no() expected = { "name": "Related Record", "res_id": self.record.id, "res_model": self.record._name, "type": "ir.actions.act_window", "view_mode": "form", } self.assertEqual(job_.related_action(), expected) def test_default_several_record(self): """Default related action called when no decorator is set When called on several record. The ``related_action`` configuration is: ``{}`` """ job_ = self.records.with_delay().testing_related_action__no() expected = { "name": "Related Records", "domain": [("id", "in", self.records.ids)], "res_model": self.record._name, "type": "ir.actions.act_window", "view_mode": "tree,form", } self.assertEqual(job_.related_action(), expected) def test_decorator(self): """Call the related action on the model The function is:: The ``related_action`` configuration is:: { "func_name": "testing_related__url", "kwargs": {"url": "https://en.wikipedia.org/wiki/{subject}"} } """ job_ = self.record.with_delay().testing_related_action__store("Discworld") expected = { "type": "ir.actions.act_url", "target": "new", "url": "https://en.wikipedia.org/wiki/Discworld", } self.assertEqual(job_.related_action(), expected)
36.552632
4,167
1,397
py
PYTHON
15.0
# copyright 2022 Guewen Baconnier # license lgpl-3.0 or later (http://www.gnu.org/licenses/lgpl.html) import json from odoo.tests import common # pylint: disable=odoo-addons-relative-import # we are testing, we want to test as if we were an external consumer of the API from odoo.addons.queue_job.fields import JobEncoder class TestJsonField(common.TransactionCase): # TODO: when migrating to 16.0, adapt the checks in queue_job/tests/test_json_field.py # to verify the context keys are encoded and remove these def test_encoder_recordset_store_context(self): demo_user = self.env.ref("base.user_demo") user_context = {"lang": "en_US", "tz": "Europe/Brussels"} test_model = self.env(user=demo_user, context=user_context)["test.queue.job"] value_json = json.dumps(test_model, cls=JobEncoder) self.assertEqual(json.loads(value_json)["context"], user_context) def test_encoder_recordset_context_filter_keys(self): demo_user = self.env.ref("base.user_demo") user_context = {"lang": "en_US", "tz": "Europe/Brussels"} tampered_context = dict(user_context, foo=object()) test_model = self.env(user=demo_user, context=tampered_context)[ "test.queue.job" ] value_json = json.dumps(test_model, cls=JobEncoder) self.assertEqual(json.loads(value_json)["context"], user_context)
43.65625
1,397
661
py
PYTHON
15.0
# Copyright 2016-2019 Camptocamp SA # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) from odoo.tests import common from odoo.addons.queue_job.job import Job class JobCommonCase(common.TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.queue_job = cls.env["queue.job"] cls.user = cls.env["res.users"] cls.method = cls.env["test.queue.job"].testing_method def _create_job(self): test_job = Job(self.method) test_job.store() stored = Job.db_record_from_uuid(self.env, test_job.uuid) self.assertEqual(len(stored), 1) return stored
30.045455
661
3,504
py
PYTHON
15.0
# Copyright 2016 Camptocamp SA # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) import odoo.tests.common as common from odoo import exceptions from odoo.addons.queue_job.job import Job class TestJobChannels(common.TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.function_model = cls.env["queue.job.function"] cls.channel_model = cls.env["queue.job.channel"] cls.test_model = cls.env["test.queue.channel"] cls.root_channel = cls.env.ref("queue_job.channel_root") def test_channel_complete_name(self): channel = self.channel_model.create( {"name": "number", "parent_id": self.root_channel.id} ) subchannel = self.channel_model.create( {"name": "five", "parent_id": channel.id} ) self.assertEqual(channel.complete_name, "root.number") self.assertEqual(subchannel.complete_name, "root.number.five") def test_channel_tree(self): with self.assertRaises(exceptions.ValidationError): self.channel_model.create({"name": "sub"}) def test_channel_root(self): with self.assertRaises(exceptions.UserError): self.root_channel.unlink() with self.assertRaises(exceptions.UserError): self.root_channel.name = "leaf" def test_channel_on_job(self): method = self.env["test.queue.channel"].job_a path_a = self.env["queue.job.function"].job_function_name( "test.queue.channel", "job_a" ) job_func = self.function_model.search([("name", "=", path_a)]) self.assertEqual(job_func.channel, "root") test_job = Job(method) test_job.store() stored = test_job.db_record() self.assertEqual(stored.channel, "root") job_read = Job.load(self.env, test_job.uuid) self.assertEqual(job_read.channel, "root") sub_channel = self.env.ref("test_queue_job.channel_sub") job_func.channel_id = sub_channel test_job = Job(method) test_job.store() stored = test_job.db_record() self.assertEqual(stored.channel, "root.sub") # it's also possible to override the channel test_job = Job(method, channel="root.sub") test_job.store() stored = test_job.db_record() self.assertEqual(stored.channel, test_job.channel) def test_default_channel_no_xml(self): """Channel on job is root if there is no queue.job.function record""" test_job = Job(self.env["res.users"].browse) test_job.store() stored = test_job.db_record() self.assertEqual(stored.channel, "root") def test_set_channel_from_record(self): func_name = self.env["queue.job.function"].job_function_name( "test.queue.channel", "job_sub_channel" ) job_func = self.function_model.search([("name", "=", func_name)]) self.assertEqual(job_func.channel, "root.sub.subsub") channel = job_func.channel_id self.assertEqual(channel.name, "subsub") self.assertEqual(channel.parent_id.name, "sub") self.assertEqual(channel.parent_id.parent_id.name, "root") self.assertEqual(job_func.channel, "root.sub.subsub") def test_default_removal_interval(self): channel = self.channel_model.create( {"name": "number", "parent_id": self.root_channel.id} ) self.assertEqual(channel.removal_interval, 30)
37.677419
3,504
9,913
py
PYTHON
15.0
# copyright 2019 Camptocamp # Copyright 2019 Guewen Baconnier # license lgpl-3.0 or later (http://www.gnu.org/licenses/lgpl.html) import odoo.tests.common as common from odoo.addons.queue_job.delay import ( Delayable, DelayableChain, DelayableGroup, chain, group, ) class TestDelayable(common.TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.queue_job = cls.env["queue.job"] cls.test_model = cls.env["test.queue.job"] cls.method = cls.env["test.queue.job"].testing_method def job_node(self, id_): return Delayable(self.test_model).testing_method(id_) def assert_generated_job(self, *nodes): for node in nodes: self.assertTrue(node._generated_job) job = node._generated_job self.assertTrue(job.db_record().id) def assert_depends_on(self, delayable, parent_delayables): self.assertEqual( delayable._generated_job._depends_on, {parent._generated_job for parent in parent_delayables}, ) def assert_reverse_depends_on(self, delayable, child_delayables): self.assertEqual( set(delayable._generated_job._reverse_depends_on), {child._generated_job for child in child_delayables}, ) def assert_dependencies(self, nodes): reverse_dependencies = {} for child, parents in nodes.items(): self.assert_depends_on(child, parents) for parent in parents: reverse_dependencies.setdefault(parent, set()).add(child) for parent, children in reverse_dependencies.items(): self.assert_reverse_depends_on(parent, children) def test_delayable_delay_single(self): node = self.job_node(1) node.delay() self.assert_generated_job(node) def test_delayable_delay_on_done(self): node = self.job_node(1) node2 = self.job_node(2) node.on_done(node2).delay() self.assert_generated_job(node, node2) self.assert_dependencies({node: {}, node2: {node}}) def test_delayable_delay_done_multi(self): node = self.job_node(1) node2 = self.job_node(2) node3 = self.job_node(3) node.on_done(node2, node3).delay() self.assert_generated_job(node, node2, node3) self.assert_dependencies({node: {}, node2: {node}, node3: {node}}) def test_delayable_delay_group(self): node = self.job_node(1) node2 = self.job_node(2) node3 = self.job_node(3) DelayableGroup(node, node2, node3).delay() self.assert_generated_job(node, node2, node3) self.assert_dependencies({node: {}, node2: {}, node3: {}}) def test_group_function(self): node = self.job_node(1) node2 = self.job_node(2) node3 = self.job_node(3) group(node, node2, node3).delay() self.assert_generated_job(node, node2, node3) self.assert_dependencies({node: {}, node2: {}, node3: {}}) def test_delayable_delay_job_after_group(self): node = self.job_node(1) node2 = self.job_node(2) node3 = self.job_node(3) DelayableGroup(node, node2).on_done(node3).delay() self.assert_generated_job(node, node2, node3) self.assert_dependencies({node: {}, node2: {}, node3: {node, node2}}) def test_delayable_delay_group_after_group(self): node = self.job_node(1) node2 = self.job_node(2) node3 = self.job_node(3) node4 = self.job_node(4) g1 = DelayableGroup(node, node2) g2 = DelayableGroup(node3, node4) g1.on_done(g2).delay() self.assert_generated_job(node, node2, node3, node4) self.assert_dependencies( { node: {}, node2: {}, node3: {node, node2}, node4: {node, node2}, } ) def test_delayable_delay_implicit_group_after_group(self): node = self.job_node(1) node2 = self.job_node(2) node3 = self.job_node(3) node4 = self.job_node(4) g1 = DelayableGroup(node, node2).on_done(node3, node4) g1.delay() self.assert_generated_job(node, node2, node3, node4) self.assert_dependencies( { node: {}, node2: {}, node3: {node, node2}, node4: {node, node2}, } ) def test_delayable_delay_group_after_group_after_group(self): node = self.job_node(1) node2 = self.job_node(2) node3 = self.job_node(3) node4 = self.job_node(4) g1 = DelayableGroup(node) g2 = DelayableGroup(node2) g3 = DelayableGroup(node3) g4 = DelayableGroup(node4) g1.on_done(g2.on_done(g3.on_done(g4))).delay() self.assert_generated_job(node, node2, node3, node4) self.assert_dependencies( { node: {}, node2: {node}, node3: {node2}, node4: {node3}, } ) def test_delayable_diamond(self): node = self.job_node(1) node2 = self.job_node(2) node3 = self.job_node(3) node4 = self.job_node(4) g1 = DelayableGroup(node2, node3) g1.on_done(node4) node.on_done(g1) node.delay() self.assert_generated_job(node, node2, node3, node4) self.assert_dependencies( { node: {}, node2: {node}, node3: {node}, node4: {node2, node3}, } ) def test_delayable_chain(self): node = self.job_node(1) node2 = self.job_node(2) node3 = self.job_node(3) c1 = DelayableChain(node, node2, node3) c1.delay() self.assert_generated_job(node, node2, node3) self.assert_dependencies( { node: {}, node2: {node}, node3: {node2}, } ) def test_chain_function(self): node = self.job_node(1) node2 = self.job_node(2) node3 = self.job_node(3) c1 = chain(node, node2, node3) c1.delay() self.assert_generated_job(node, node2, node3) self.assert_dependencies( { node: {}, node2: {node}, node3: {node2}, } ) def test_delayable_chain_after_job(self): node = self.job_node(1) node2 = self.job_node(2) node3 = self.job_node(3) node4 = self.job_node(4) c1 = DelayableChain(node2, node3, node4) node.on_done(c1) node.delay() self.assert_generated_job(node, node2, node3, node4) self.assert_dependencies( { node: {}, node2: {node}, node3: {node2}, node4: {node3}, } ) def test_delayable_chain_after_chain(self): node = self.job_node(1) node2 = self.job_node(2) node3 = self.job_node(3) node4 = self.job_node(4) node5 = self.job_node(5) node6 = self.job_node(6) chain1 = DelayableChain(node, node2, node3) chain2 = DelayableChain(node4, node5, node6) chain1.on_done(chain2) chain1.delay() self.assert_generated_job(node, node2, node3, node4, node5, node6) self.assert_dependencies( { node: {}, node2: {node}, node3: {node2}, node4: {node3}, node5: {node4}, node6: {node5}, } ) def test_delayable_group_of_chain(self): node = self.job_node(1) node2 = self.job_node(2) node3 = self.job_node(3) node4 = self.job_node(4) node5 = self.job_node(5) node6 = self.job_node(6) node7 = self.job_node(7) node8 = self.job_node(8) chain1 = DelayableChain(node, node2) chain2 = DelayableChain(node3, node4) chain3 = DelayableChain(node5, node6) chain4 = DelayableChain(node7, node8) g1 = DelayableGroup(chain1, chain2).on_done(chain3, chain4) g1.delay() self.assert_generated_job( node, node2, node3, node4, node5, node6, node7, node8, ) self.assert_dependencies( { node: {}, node3: {}, node2: {node}, node4: {node3}, node5: {node4, node2}, node7: {node4, node2}, node6: {node5}, node8: {node7}, } ) def test_log_not_delayed(self): logger_name = "odoo.addons.queue_job" with self.assertLogs(logger_name, level="WARN") as test: # When a Delayable never gets a delay() call, # when the GC collects it and calls __del__, a warning # will be displayed. We cannot test this is a scenario # using the GC as it isn't predictable. Call __del__ # directly node = self.job_node(1) node.__del__() expected = ( "WARNING:odoo.addons.queue_job.delay:Delayable " "Delayable(test.queue.job().testing_method((1,), {}))" " was prepared but never delayed" ) self.assertEqual(test.output, [expected]) def test_delay_job_already_exists(self): node = self.job_node(1) node2 = self.job_node(2) node2.delay() node.on_done(node2).delay() self.assert_generated_job(node, node2) self.assert_dependencies({node: {}, node2: {node}})
32.608553
9,913
4,680
py
PYTHON
15.0
# Copyright 2016 Camptocamp SA # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) from odoo import api, fields, models from odoo.addons.queue_job.delay import chain from odoo.addons.queue_job.exception import RetryableJobError from odoo.addons.queue_job.job import identity_exact class QueueJob(models.Model): _inherit = "queue.job" additional_info = fields.Char() def testing_related_method(self, **kwargs): return self, kwargs def testing_related__none(self, **kwargs): return None def testing_related__url(self, **kwargs): assert "url" in kwargs, "url required" subject = self.args[0] return { "type": "ir.actions.act_url", "target": "new", "url": kwargs["url"].format(subject=subject), } class ModelTestQueueJob(models.Model): _name = "test.queue.job" _description = "Test model for queue.job" name = fields.Char() # to test the context is serialized/deserialized properly @api.model def _job_prepare_context_before_enqueue_keys(self): return ("tz", "lang") def testing_method(self, *args, **kwargs): """Method used for tests Return always the arguments and keyword arguments received """ if kwargs.get("raise_retry"): raise RetryableJobError("Must be retried later") if kwargs.get("return_context"): return self.env.context return args, kwargs def create_ir_logging(self, message, level="info"): return self.env["ir.logging"].create( { "name": "test_queue_job", "type": "server", "dbname": self.env.cr.dbname, "message": message, "path": "job", "func": "create_ir_logging", "line": 1, } ) def no_description(self): return def job_with_retry_pattern(self): return def job_with_retry_pattern__no_zero(self): return def mapped(self, func): return super(ModelTestQueueJob, self).mapped(func) def job_alter_mutable(self, mutable_arg, mutable_kwarg=None): mutable_arg.append(2) mutable_kwarg["b"] = 2 return mutable_arg, mutable_kwarg def delay_me(self, arg, kwarg=None): return arg, kwarg def delay_me_options_job_options(self): return { "identity_key": "my_job_identity", } def delay_me_options(self): return "ok" def delay_me_context_key(self): return "ok" def _register_hook(self): self._patch_method("delay_me", self._patch_job_auto_delay("delay_me")) self._patch_method( "delay_me_options", self._patch_job_auto_delay("delay_me_options") ) self._patch_method( "delay_me_context_key", self._patch_job_auto_delay( "delay_me_context_key", context_key="auto_delay_delay_me_context_key" ), ) return super()._register_hook() def _job_store_values(self, job): value = "JUST_TESTING" if job.state == "failed": value += "_BUT_FAILED" return {"additional_info": value} def button_that_uses_with_delay(self): self.with_delay( channel="root.test", description="Test", eta=15, identity_key=identity_exact, max_retries=1, priority=15, ).testing_method(1, foo=2) def button_that_uses_delayable_chain(self): delayables = chain( self.delayable( channel="root.test", description="Test", eta=15, identity_key=identity_exact, max_retries=1, priority=15, ).testing_method(1, foo=2), self.delayable().testing_method("x", foo="y"), self.delayable().no_description(), ) delayables.delay() class ModelTestQueueChannel(models.Model): _name = "test.queue.channel" _description = "Test model for queue.channel" def job_a(self): return def job_b(self): return def job_sub_channel(self): return class ModelTestRelatedAction(models.Model): _name = "test.related.action" _description = "Test model for related actions" def testing_related_action__no(self): return def testing_related_action__return_none(self): return def testing_related_action__kwargs(self): return def testing_related_action__store(self): return
26.742857
4,680
842
py
PYTHON
15.0
# Copyright 2019 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Base Export Async", "summary": "Asynchronous export with job queue", "version": "15.0.1.0.0", "license": "AGPL-3", "author": "ACSONE SA/NV, Odoo Community Association (OCA)", "website": "https://github.com/OCA/queue", "depends": ["web", "queue_job"], "data": [ "security/ir.model.access.csv", "security/ir_rule.xml", "data/config_parameter.xml", "data/cron.xml", "data/mail_template.xml", ], "demo": [], "assets": { "web.assets_qweb": [ "base_export_async/static/src/xml/base.xml", ], "web.assets_backend": [ "base_export_async/static/src/js/data_export.js", ], }, "installable": True, }
29.034483
842
3,866
py
PYTHON
15.0
# Copyright 2019 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import json from unittest import mock import freezegun from dateutil.relativedelta import relativedelta import odoo.tests.common as common from odoo import fields from odoo.http import _request_stack data_csv = { "data": """{"format": "csv", "model": "res.partner", "fields": [{"name": "id", "label": "External ID"}, {"name": "display_name", "label": "Display Name"}, {"name": "email", "label": "Email"}, {"name": "phone", "label": "Phone"}], "ids": false, "domain": [], "context": {"lang": "en_US", "tz": "Europe/Brussels", "uid": 2}, "import_compat": false, "user_ids": [2] }""" } data_xls = { "data": """{"format": "xls", "model": "res.partner", "fields": [{"name": "id", "label": "External ID"}, {"name": "display_name", "label": "Display Name"}, {"name": "email", "label": "Email"}, {"name": "phone", "label": "Phone"}], "ids": false, "domain": [], "context": {"lang": "en_US", "tz": "Europe/Brussels", "uid": 2}, "import_compat": false, "user_ids": [2] }""" } class TestBaseExportAsync(common.TransactionCase): def setUp(self): super(TestBaseExportAsync, self).setUp() self.delay_export_obj = self.env["delay.export"] self.job_obj = self.env["queue.job"] _request_stack.push( mock.Mock( env=self.env, ) ) self.addCleanup(_request_stack.pop) def test_delay_export(self): """Check that the call create a new JOB""" nbr_job = len(self.job_obj.search([])) self.delay_export_obj.delay_export(data_csv) new_nbr_job = len(self.job_obj.search([])) self.assertEqual(new_nbr_job, nbr_job + 1) def test_export_csv(self): """Check that the export generate an attachment and email""" params = json.loads(data_csv.get("data")) mails = self.env["mail.mail"].search([]) attachments = self.env["ir.attachment"].search([]) self.delay_export_obj.export(params) new_mail = self.env["mail.mail"].search([]) - mails new_attachment = self.env["ir.attachment"].search([]) - attachments self.assertEqual(len(new_mail), 1) self.assertEqual(new_attachment.name, "res.partner.csv") def test_export_xls(self): """Check that the export generate an attachment and email""" params = json.loads(data_xls.get("data")) mails = self.env["mail.mail"].search([]) attachments = self.env["ir.attachment"].search([]) self.delay_export_obj.export(params) new_mail = self.env["mail.mail"].search([]) - mails new_attachment = self.env["ir.attachment"].search([]) - attachments self.assertEqual(len(new_mail), 1) self.assertEqual(new_attachment.name, "res.partner.xls") def test_cron_delete(self): """Check that cron delete attachment after TTL""" params = json.loads(data_csv.get("data")) attachments = self.env["ir.attachment"].search([]) self.delay_export_obj.export(params) new_attachment = self.env["ir.attachment"].search([]) - attachments time_to_live = ( self.env["ir.config_parameter"].sudo().get_param("attachment.ttl", 7) ) date_today = fields.Datetime.now() date_past_ttl = date_today + relativedelta(days=int(time_to_live)) with freezegun.freeze_time(date_past_ttl): self.delay_export_obj.cron_delete() # The attachment must be deleted self.assertFalse(new_attachment.exists())
39.050505
3,866
4,955
py
PYTHON
15.0
# Copyright 2019 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import base64 import json import operator from dateutil.relativedelta import relativedelta from odoo import _, api, fields, models from odoo.exceptions import UserError from odoo.addons.web.controllers.main import CSVExport, ExcelExport class DelayExport(models.Model): _name = "delay.export" _description = "Asynchronous Export" user_ids = fields.Many2many("res.users", string="Users", index=True) model_description = fields.Char() url = fields.Char() expiration_date = fields.Date() @api.model def delay_export(self, data): """Delay the export, called from js""" params = json.loads(data.get("data")) if not self.env.user.email: raise UserError(_("You must set an email address to your user.")) self.with_delay().export(params) @api.model def _get_file_content(self, params): export_format = params.get("format") items = operator.itemgetter( "model", "fields", "ids", "domain", "import_compat", "context", "user_ids" )(params) (model_name, fields_name, ids, domain, import_compat, context, user_ids) = items model = self.env[model_name].with_context( import_compat=import_compat, **context ) records = model.browse(ids) or model.search( domain, offset=0, limit=False, order=False ) if not model._is_an_ordinary_table(): fields_name = [field for field in fields_name if field["name"] != "id"] field_names = [f["name"] for f in fields_name] import_data = records.export_data(field_names).get("datas", []) if import_compat: columns_headers = field_names else: columns_headers = [val["label"].strip() for val in fields_name] if export_format == "csv": csv = CSVExport() return csv.from_data(columns_headers, import_data) else: xls = ExcelExport() return xls.from_data(columns_headers, import_data) @api.model def export(self, params): """Delayed export of a file sent by email The ``params`` is a dict of parameters, contains: * format: csv/excel * model: model to export * fields: list of fields to export, a list of dict: [{'label': '', 'name': ''}] * ids: list of ids to export * domain: domain for the export * context: context for the export (language, ...) * import_compat: if the export is export/import compatible (boolean) * user_ids: optional list of user ids who receive the file """ content = self._get_file_content(params) items = operator.itemgetter("model", "context", "format", "user_ids")(params) model_name, context, export_format, user_ids = items users = self.env["res.users"].browse(user_ids) export_record = self.sudo().create({"user_ids": [(6, 0, users.ids)]}) name = "{}.{}".format(model_name, export_format) attachment = self.env["ir.attachment"].create( { "name": name, "datas": base64.b64encode(content), "type": "binary", "res_model": self._name, "res_id": export_record.id, } ) url = "{}/web/content/ir.attachment/{}/datas/{}?download=true".format( self.env["ir.config_parameter"].sudo().get_param("web.base.url"), attachment.id, attachment.name, ) time_to_live = ( self.env["ir.config_parameter"].sudo().get_param("attachment.ttl", 7) ) date_today = fields.Date.today() expiration_date = fields.Date.to_string( date_today + relativedelta(days=+int(time_to_live)) ) odoo_bot = self.sudo().env.ref("base.partner_root") email_from = odoo_bot.email model_description = self.env[model_name]._description export_record.write( { "url": url, "expiration_date": expiration_date, "model_description": model_description, } ) self.env.ref("base_export_async.delay_export_mail_template").send_mail( export_record.id, email_values={ "email_from": email_from, "reply_to": email_from, "recipient_ids": [(6, 0, users.mapped("partner_id").ids)], }, ) @api.model def cron_delete(self): time_to_live = ( self.env["ir.config_parameter"].sudo().get_param("attachment.ttl", 7) ) date_today = fields.Date.today() date_to_delete = date_today + relativedelta(days=-int(time_to_live)) self.search([("create_date", "<=", date_to_delete)]).unlink()
34.409722
4,955
557
py
PYTHON
15.0
# Copyright 2019 ForgeFlow S.L. (https://www.forgeflow.com) # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl). { "name": "MRP BoM Tracking", "version": "15.0.1.1.0", "author": "ForgeFlow, Odoo Community Association (OCA)", "summary": "Logs any change to a BoM in the chatter", "website": "https://github.com/OCA/manufacture", "category": "Manufacturing", "depends": ["mrp"], "data": ["views/bom_template.xml"], "license": "LGPL-3", "installable": True, "development_status": "Production/Stable", }
34.8125
557
1,754
py
PYTHON
15.0
# Copyright 2019 ForgeFlow S.L. (https://www.forgeflow.com) # - Lois Rilo <[email protected]> # License LGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo.tests.common import TransactionCase class TestBomTracking(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.product_obj = cls.env["product.product"] cls.bom_obj = cls.env["mrp.bom"] cls.bom_line_obj = cls.env["mrp.bom.line"] # Create products: cls.product_1 = cls.product_obj.create({"name": "TEST 01", "type": "product"}) cls.component_1 = cls.product_obj.create({"name": "RM 01", "type": "product"}) cls.component_2 = cls.product_obj.create({"name": "RM 02", "type": "product"}) cls.component_2_alt = cls.product_obj.create( {"name": "RM 02-B", "type": "product"} ) # Create Bills of Materials: cls.bom = cls.bom_obj.create( {"product_tmpl_id": cls.product_1.product_tmpl_id.id} ) cls.line_1 = cls.bom_line_obj.create( {"product_id": cls.component_1.id, "bom_id": cls.bom.id, "product_qty": 2.0} ) cls.line_2 = cls.bom_line_obj.create( {"product_id": cls.component_2.id, "bom_id": cls.bom.id, "product_qty": 5.0} ) def test_01_change_bom_line_qty(self): before = self.bom.message_ids self.line_1.product_qty = 3.0 after = self.bom.message_ids self.assertEqual(len(after - before), 1) def test_02_change_bom_line_product(self): before = self.bom.message_ids self.line_2.product_id = self.component_2_alt after = self.bom.message_ids self.assertEqual(len(after - before), 1)
38.130435
1,754
3,563
py
PYTHON
15.0
# Copyright 2019 ForgeFlow S.L. (https://www.forgeflow.com) # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl). from odoo import fields, models class MrpBom(models.Model): _inherit = "mrp.bom" code = fields.Char(tracking=True) product_id = fields.Many2one(tracking=True) product_tmpl_id = fields.Many2one(tracking=True) product_qty = fields.Float(tracking=True) picking_type_id = fields.Many2one(tracking=True) type = fields.Selection(tracking=True) def write(self, values): bom_line_ids = {} if "bom_line_ids" in values: for bom in self: del_lines = [] for line in values["bom_line_ids"]: if line[0] == 2: del_lines.append(line[1]) if del_lines: bom.message_post_with_view( "mrp_bom_tracking.track_bom_template", values={ "lines": self.env["mrp.bom.line"].browse(del_lines), "mode": "Removed", }, subtype_id=self.env.ref("mail.mt_note").id, ) bom_line_ids[bom.id] = bom.bom_line_ids res = super(MrpBom, self).write(values) if "bom_line_ids" in values: for bom in self: new_lines = bom.bom_line_ids - bom_line_ids[bom.id] if new_lines: bom.message_post_with_view( "mrp_bom_tracking.track_bom_template", values={"lines": new_lines, "mode": "New"}, subtype_id=self.env.ref("mail.mt_note").id, ) return res class MrpBomLine(models.Model): _inherit = "mrp.bom.line" def write(self, values): if "product_id" in values: for bom in self.mapped("bom_id"): lines = self.filtered(lambda l: l.bom_id == bom) product_id = values.get("product_id") if product_id: product_id = self.env["product.product"].browse(product_id) product_id = product_id or lines.product_id if lines: bom.message_post_with_view( "mrp_bom_tracking.track_bom_template_2", values={"lines": lines, "product_id": product_id}, subtype_id=self.env.ref("mail.mt_note").id, ) elif "product_qty" in values or "product_uom_id" in values: for bom in self.mapped("bom_id"): lines = self.filtered(lambda l: l.bom_id == bom) if lines: product_qty = values.get("product_qty") or lines.product_qty product_uom_id = values.get("product_uom_id") if product_uom_id: product_uom_id = self.env["uom.uom"].browse(product_uom_id) product_uom_id = product_uom_id or lines.product_uom_id bom.message_post_with_view( "mrp_bom_tracking.track_bom_line_template", values={ "lines": lines, "product_qty": product_qty, "product_uom_id": product_uom_id, }, subtype_id=self.env.ref("mail.mt_note").id, ) return super(MrpBomLine, self).write(values)
42.927711
3,563
590
py
PYTHON
15.0
# Copyright 2022 ForgeFlow S.L. (https://www.forgeflow.com) # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl). { "name": "MRP Finished Backorder Product", "version": "15.0.1.0.0", "author": "ForgeFlow, Odoo Community Association (OCA)", "summary": "Be able to see the summary of the finished manufactured orders ", "website": "https://github.com/OCA/manufacture", "category": "Manufacturing", "depends": ["mrp"], "data": ["views/mrp_production_views.xml"], "license": "LGPL-3", "installable": True, "development_status": "Beta", }
36.875
590
932
py
PYTHON
15.0
# Copyright 2022 ForgeFlow S.L. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, fields, models class MrpProduction(models.Model): _inherit = "mrp.production" finished_move_from_backorder_ids = fields.One2many( "stock.move.line", compute="_compute_finished_backorders", string="Finished Backorders", ) @api.depends("move_finished_ids.move_line_ids") def _compute_finished_backorders(self): for production in self: production.finished_move_from_backorder_ids = self.env["stock.move.line"] backorders = production.procurement_group_id.mrp_production_ids for backorder in backorders: backorder.mapped("finished_move_line_ids").production_id = backorder production.finished_move_from_backorder_ids |= ( backorder.finished_move_line_ids )
37.28
932
637
py
PYTHON
15.0
# Copyright 2021 ForgeFlow S.L. (http://www.forgeflow.com) # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html { "name": "MRP Production Serial Matrix", "version": "15.0.0.1.0", "category": "Manufacturing", "license": "AGPL-3", "author": "ForgeFlow, Odoo Community Association (OCA)", "website": "https://github.com/OCA/manufacture", "depends": [ "mrp", "web_widget_x2many_2d_matrix", ], "data": [ "security/ir.model.access.csv", "wizards/mrp_production_serial_matrix_view.xml", "views/mrp_production_views.xml", ], "installable": True, }
30.333333
637
11,287
py
PYTHON
15.0
# Copyright 2021 ForgeFlow S.L. (http://www.forgeflow.com) # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html from odoo.exceptions import UserError from odoo.tests import Form from odoo.tests.common import TransactionCase class TestMrpProductionSerialMatrix(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.mo_obj = cls.env["mrp.production"] cls.product_obj = cls.env["product.product"] cls.lot_obj = cls.env["stock.production.lot"] cls.quant_obj = cls.env["stock.quant"] cls.bom_obj = cls.env["mrp.bom"] cls.bom_line_obj = cls.env["mrp.bom.line"] cls.move_line_obj = cls.env["stock.move.line"] cls.wiz_obj = cls.env["mrp.production.serial.matrix"] cls.company = cls.env.ref("base.main_company") cls.stock_loc = cls.env.ref("stock.stock_location_stock") # Products and lots: cls.final_product = cls.product_obj.create( { "name": "Finished Product tracked by Serial Numbers", "type": "product", "tracking": "serial", } ) cls.component_1_serial = cls.product_obj.create( { "name": "Component 1 tracked by Serial Numbers", "type": "product", "tracking": "serial", } ) cls.serial_1_001 = cls._create_serial_number(cls.component_1_serial, "1-001") cls.serial_1_002 = cls._create_serial_number(cls.component_1_serial, "1-002") cls.serial_1_003 = cls._create_serial_number(cls.component_1_serial, "1-003") cls.component_2_serial = cls.product_obj.create( { "name": "Component 2 tracked by Serial Numbers", "type": "product", "tracking": "serial", } ) cls.serial_2_001 = cls._create_serial_number(cls.component_2_serial, "2-001") cls.serial_2_002 = cls._create_serial_number(cls.component_2_serial, "2-002") cls.serial_2_003 = cls._create_serial_number(cls.component_2_serial, "2-003") cls.serial_2_004 = cls._create_serial_number(cls.component_2_serial, "2-004") cls.serial_2_005 = cls._create_serial_number(cls.component_2_serial, "2-005") cls.serial_2_006 = cls._create_serial_number(cls.component_2_serial, "2-006") cls.component_3_lot = cls.product_obj.create( { "name": "Component 3 tracked by Lots", "type": "product", "tracking": "lot", } ) cls.lot_3_001 = cls._create_serial_number( cls.component_3_lot, "3-001", qty=10.0 ) cls.lot_3_002 = cls._create_serial_number(cls.component_3_lot, "3-002", qty=8.0) cls.lot_3_003 = cls._create_serial_number( cls.component_3_lot, "3-003", qty=12.0 ) cls.component_4_no_track = cls.product_obj.create( { "name": "Component 4 Not tracked", "type": "product", "tracking": "none", } ) cls.quant_obj.create( { "product_id": cls.component_4_no_track.id, "location_id": cls.stock_loc.id, "quantity": 20.0, } ) # BoM cls.bom_1 = cls.bom_obj.create( { "product_tmpl_id": cls.final_product.product_tmpl_id.id, "product_id": cls.final_product.id, "product_qty": 1.0, } ) cls.bom_line_obj.create( { "bom_id": cls.bom_1.id, "product_id": cls.component_1_serial.id, "product_qty": 1.0, } ) cls.bom_line_obj.create( { "bom_id": cls.bom_1.id, "product_id": cls.component_2_serial.id, "product_qty": 2.0, } ) cls.bom_line_obj.create( { "bom_id": cls.bom_1.id, "product_id": cls.component_3_lot.id, "product_qty": 4.0, } ) cls.bom_line_obj.create( { "bom_id": cls.bom_1.id, "product_id": cls.component_4_no_track.id, "product_qty": 1.0, } ) @classmethod def _create_serial_number(cls, product, name, qty=1.0): lot = cls.lot_obj.create( { "product_id": product.id, "name": name, "company_id": cls.company.id, } ) if qty > 0: cls.quant_obj.create( { "product_id": product.id, "location_id": cls.stock_loc.id, "quantity": qty, "lot_id": lot.id, } ) return lot @classmethod def _create_mo(cls, qty): production_form = Form(cls.mo_obj) production_form.product_id = cls.final_product production_form.bom_id = cls.bom_1 production_form.product_qty = qty production_form.product_uom_id = cls.final_product.uom_id production_1 = production_form.save() production_1.action_confirm() production_1.action_assign() return production_1 @classmethod def _find_move_lines(cls, mo, component): return cls.move_line_obj.search( [ ("move_id.raw_material_production_id", "=", mo.id), ("product_id", "=", component.id), ] ) def test_01_process_mo_with_matrix(self): """Extensive test including all the possibilities for components: - 1 tracked by serials. - 1 tracked by serials and needing more than one unit. - 1 tracked by lots. - 1 untracked. """ production_1 = self._create_mo(3.0) self.assertEqual(production_1.state, "confirmed") # Start matrix: wizard_form = Form( self.wiz_obj.with_context( active_id=production_1.id, active_model="mrp.production" ) ) expected = 3 * 3 # Only SN products (1 + 2 per finish unit) self.assertEqual(len(wizard_form.line_ids), expected) wizard_form.include_lots = True expected = 3 * 4 self.assertEqual(len(wizard_form.line_ids), expected) self.assertEqual(wizard_form.lot_selection_warning_count, 0) serial_fp_1 = self._create_serial_number(self.final_product, "ABC101", qty=0) serial_fp_2 = self._create_serial_number(self.final_product, "ABC102", qty=0) wizard_form.finished_lot_ids.add(serial_fp_1) self.assertEqual(wizard_form.lot_selection_warning_count, 1) wizard_form.finished_lot_ids.add(serial_fp_2) self.assertEqual(wizard_form.lot_selection_warning_count, 2) wizard = wizard_form.save() lines = wizard.line_ids # Fill first row: cell_1_1 = lines.filtered( lambda l: l.finished_lot_id == serial_fp_1 and l.component_id == self.component_1_serial ) cell_1_1.component_lot_id = self.serial_1_001 cell_1_2and3 = lines.filtered( lambda l: l.finished_lot_id == serial_fp_1 and l.component_id == self.component_2_serial ) self.assertEqual(len(cell_1_2and3), 2) for n, cell in enumerate(cell_1_2and3): if n == 0: cell.component_lot_id = self.serial_2_001 elif n == 1: cell.component_lot_id = self.serial_2_002 cell_1_4 = lines.filtered( lambda l: l.finished_lot_id == serial_fp_1 and l.component_id == self.component_3_lot ) cell_1_4.component_lot_id = self.lot_3_003 # Fill second row: cell_2_1 = lines.filtered( lambda l: l.finished_lot_id == serial_fp_2 and l.component_id == self.component_1_serial ) # Simulate a mistake and select the same lot than before: cell_2_1.component_lot_id = self.serial_1_001 cell_2_2and3 = lines.filtered( lambda l: l.finished_lot_id == serial_fp_2 and l.component_id == self.component_2_serial ) self.assertEqual(len(cell_2_2and3), 2) for n, cell in enumerate(cell_2_2and3): if n == 0: cell.component_lot_id = self.serial_2_005 elif n == 1: cell.component_lot_id = self.serial_2_004 cell_2_4 = lines.filtered( lambda l: l.finished_lot_id == serial_fp_2 and l.component_id == self.component_3_lot ) cell_2_4.component_lot_id = self.lot_3_002 # There should be an error: self.assertEqual(wizard.lot_selection_warning_count, 1) with self.assertRaises(UserError): wizard.button_validate() # Fix error: cell_2_1.component_lot_id = self.serial_1_003 # Validate and check result: wizard.button_validate() mos = production_1.procurement_group_id.mrp_production_ids self.assertEqual(len(mos), 3) mo_1 = mos.filtered(lambda mo: mo.lot_producing_id == serial_fp_1) self.assertEqual(mo_1.state, "done") ml_c1 = self._find_move_lines(mo_1, self.component_1_serial) self.assertEqual(ml_c1.qty_done, 1.0) self.assertEqual(ml_c1.lot_id, self.serial_1_001) ml_c2 = self._find_move_lines(mo_1, self.component_2_serial) self.assertEqual(len(ml_c2), 2) for ml in ml_c2: self.assertEqual(ml.qty_done, 1.0) self.assertEqual(ml_c2.mapped("lot_id"), self.serial_2_001 + self.serial_2_002) ml_c3 = self._find_move_lines(mo_1, self.component_3_lot) self.assertEqual(ml_c3.qty_done, 4.0) self.assertEqual(ml_c3.lot_id, self.lot_3_003) ml_c4 = self._find_move_lines(mo_1, self.component_4_no_track) self.assertEqual(ml_c4.qty_done, 1.0) self.assertFalse(ml_c4.lot_id) mo_2 = mos.filtered(lambda mo: mo.lot_producing_id == serial_fp_2) self.assertEqual(mo_2.state, "done") ml_c1 = self._find_move_lines(mo_2, self.component_1_serial) self.assertEqual(ml_c1.qty_done, 1.0) self.assertEqual(ml_c1.lot_id, self.serial_1_003) ml_c2 = self._find_move_lines(mo_2, self.component_2_serial) self.assertEqual(len(ml_c2), 2) for ml in ml_c2: self.assertEqual(ml.qty_done, 1.0) self.assertEqual(ml_c2.mapped("lot_id"), self.serial_2_005 + self.serial_2_004) ml_c3 = self._find_move_lines(mo_2, self.component_3_lot) self.assertEqual(ml_c3.qty_done, 4.0) self.assertEqual(ml_c3.lot_id, self.lot_3_002) ml_c4 = self._find_move_lines(mo_2, self.component_4_no_track) self.assertEqual(ml_c4.qty_done, 1.0) self.assertFalse(ml_c4.lot_id) # MO holding the remaining qty mo_3 = mos.filtered(lambda mo: not mo.lot_producing_id) self.assertEqual(mo_3.state, "confirmed") self.assertEqual(mo_3.product_qty, 1.0)
39.465035
11,287
448
py
PYTHON
15.0
# Copyright 2021 ForgeFlow S.L. (http://www.forgeflow.com) # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html from odoo import fields, models class MrpProduction(models.Model): _inherit = "mrp.production" show_serial_matrix = fields.Boolean(compute="_compute_show_serial_matrix") def _compute_show_serial_matrix(self): for rec in self: rec.show_serial_matrix = rec.product_id.tracking == "serial"
32
448
2,227
py
PYTHON
15.0
# Copyright 2019 ForgeFlow S.L. (https://www.forgeflow.com) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import fields, models class MrpProductionSerialMatrix(models.TransientModel): _name = "mrp.production.serial.matrix.line" _description = "Mrp Production Serial Matrix Line" wizard_id = fields.Many2one( comodel_name="mrp.production.serial.matrix", ) production_id = fields.Many2one(related="wizard_id.production_id") component_id = fields.Many2one(comodel_name="product.product") component_column_name = fields.Char() finished_lot_id = fields.Many2one(comodel_name="stock.production.lot") finished_lot_name = fields.Char() component_lot_id = fields.Many2one( comodel_name="stock.production.lot", domain="[('id', 'in', allowed_component_lot_ids)]", ) allowed_component_lot_ids = fields.Many2many( comodel_name="stock.production.lot", compute="_compute_allowed_component_lot_ids", ) lot_qty = fields.Float(digits="Product Unit of Measure") def _compute_allowed_component_lot_ids(self): for rec in self: available_quants = self.env["stock.quant"].search( [ ("location_id", "child_of", rec.production_id.location_src_id.id), ("product_id", "=", rec.component_id.id), ("quantity", ">", 0), ] ) rec.allowed_component_lot_ids = available_quants.mapped("lot_id") def _get_available_and_reserved_quantities(self): self.ensure_one() available_quantity = self.env["stock.quant"]._get_available_quantity( self.component_id, self.production_id.location_src_id, lot_id=self.component_lot_id, ) move_lines = self.production_id.move_raw_ids.mapped("move_line_ids").filtered( lambda l: l.product_id == self.component_id and l.lot_id == self.component_lot_id and l.state not in ["done", "cancel"] ) specifically_reserved_quantity = sum(move_lines.mapped("product_uom_qty")) return available_quantity, specifically_reserved_quantity
42.018868
2,227
14,896
py
PYTHON
15.0
# Copyright 2021 ForgeFlow S.L. (https://www.forgeflow.com) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import _, api, fields, models from odoo.exceptions import UserError, ValidationError from odoo.tools.float_utils import float_compare, float_is_zero class MrpProductionSerialMatrix(models.TransientModel): _name = "mrp.production.serial.matrix" _description = "Mrp Production Serial Matrix" production_id = fields.Many2one( comodel_name="mrp.production", string="Manufacturing Order", readonly=True, ) product_id = fields.Many2one( related="production_id.product_id", readonly=True, ) company_id = fields.Many2one( related="production_id.company_id", readonly=True, ) finished_lot_ids = fields.Many2many( string="Finished Product Serial Numbers", comodel_name="stock.production.lot", domain="[('product_id', '=', product_id)]", ) line_ids = fields.One2many( string="Matrix Cell", comodel_name="mrp.production.serial.matrix.line", inverse_name="wizard_id", ) lot_selection_warning_msg = fields.Char(compute="_compute_lot_selection_warning") lot_selection_warning_ids = fields.Many2many( comodel_name="stock.production.lot", compute="_compute_lot_selection_warning" ) lot_selection_warning_count = fields.Integer( compute="_compute_lot_selection_warning" ) include_lots = fields.Boolean( string="Include Lots?", help="Include products tracked by Lots in matrix. Product tracket by " "serial numbers are always included.", ) @api.depends("line_ids", "line_ids.component_lot_id") def _compute_lot_selection_warning(self): for rec in self: warning_lots = self.env["stock.production.lot"] warning_msgs = [] # Serials: serial_lines = rec.line_ids.filtered( lambda l: l.component_id.tracking == "serial" ) serial_counter = {} for sl in serial_lines: if not sl.component_lot_id: continue serial_counter.setdefault(sl.component_lot_id, 0) serial_counter[sl.component_lot_id] += 1 for lot, counter in serial_counter.items(): if counter > 1: warning_lots += lot warning_msgs.append( "Serial number %s selected several times" % lot.name ) # Lots lot_lines = rec.line_ids.filtered( lambda l: l.component_id.tracking == "lot" ) lot_consumption = {} for ll in lot_lines: if not ll.component_lot_id: continue lot_consumption.setdefault(ll.component_lot_id, 0) free_qty, reserved_qty = ll._get_available_and_reserved_quantities() available_quantity = free_qty + reserved_qty if ( available_quantity - lot_consumption[ll.component_lot_id] < ll.lot_qty ): warning_lots += ll.component_lot_id warning_msgs.append( "Lot %s not available at the needed qty (%s/%s)" % (ll.component_lot_id.name, available_quantity, ll.lot_qty) ) lot_consumption[ll.component_lot_id] += ll.lot_qty not_filled_lines = rec.line_ids.filtered( lambda l: l.finished_lot_id and not l.component_lot_id ) if not_filled_lines: not_filled_finshed_lots = not_filled_lines.mapped("finished_lot_id") warning_lots += not_filled_finshed_lots warning_msgs.append( "Some cells are not filled for some finished serial number (%s)" % ", ".join(not_filled_finshed_lots.mapped("name")) ) rec.lot_selection_warning_msg = ", ".join(warning_msgs) rec.lot_selection_warning_ids = warning_lots rec.lot_selection_warning_count = len(warning_lots) @api.model def default_get(self, fields): res = super().default_get(fields) production_id = self.env.context["active_id"] active_model = self.env.context["active_model"] if not production_id: return res assert active_model == "mrp.production", "Bad context propagation" production = self.env["mrp.production"].browse(production_id) if not production.show_serial_matrix: raise UserError( _("The finished product of this MO is not tracked by serial numbers.") ) finished_lots = self.env["stock.production.lot"] if production.lot_producing_id: finished_lots = production.lot_producing_id matrix_lines = self._get_matrix_lines(production, finished_lots) res.update( { "line_ids": [(0, 0, x) for x in matrix_lines], "production_id": production_id, "finished_lot_ids": [(4, lot_id, 0) for lot_id in finished_lots.ids], } ) return res def _get_matrix_lines(self, production, finished_lots): tracked_components = [] for move in production.move_raw_ids: rounding = move.product_id.uom_id.rounding if float_is_zero(move.product_qty, precision_rounding=rounding): # Component moves cannot be deleted in in-progress MO's; however, # they can be set to 0 units to consume. In such case, we ignore # the move. continue boml = move.bom_line_id # TODO: UoM (MO/BoM using different UoMs than product's defaults). if boml: qty_per_finished_unit = boml.product_qty / boml.bom_id.product_qty else: # The product could have been added for the specific MO but not # be part of the BoM. qty_per_finished_unit = move.product_qty / production.product_qty if move.product_id.tracking == "serial": for i in range(1, int(qty_per_finished_unit) + 1): tracked_components.append((move.product_id, i, 1)) elif move.product_id.tracking == "lot" and self.include_lots: tracked_components.append((move.product_id, 0, qty_per_finished_unit)) matrix_lines = [] current_lot = False new_lot_number = 0 for _i in range(int(production.product_qty)): if finished_lots: current_lot = finished_lots[0] else: new_lot_number += 1 for component_tuple in tracked_components: line = self._prepare_matrix_line( component_tuple, finished_lot=current_lot, number=new_lot_number ) matrix_lines.append(line) if current_lot: finished_lots -= current_lot current_lot = False return matrix_lines def _prepare_matrix_line(self, component_tuple, finished_lot=None, number=None): component, lot_no, lot_qty = component_tuple column_name = component.display_name if lot_no > 0: column_name += " (%s)" % lot_no res = { "component_id": component.id, "component_column_name": column_name, "lot_qty": lot_qty, } if finished_lot: if isinstance(finished_lot.id, models.NewId): # NewId instances are not handled correctly later, this is a # small workaround. In future versions it might not be needed. lot_id = finished_lot.id.origin else: lot_id = finished_lot.id res.update( { "finished_lot_id": lot_id, "finished_lot_name": finished_lot.name, } ) elif isinstance(number, int): res.update( { "finished_lot_name": _("(New Lot %s)") % number, } ) return res @api.onchange("finished_lot_ids", "include_lots") def _onchange_finished_lot_ids(self): for rec in self: matrix_lines = self._get_matrix_lines( rec.production_id, rec.finished_lot_ids, ) rec.line_ids = False rec.write({"line_ids": [(0, 0, x) for x in matrix_lines]}) def button_validate(self): self.ensure_one() if self.lot_selection_warning_count > 0: raise UserError( _("Some issues has been detected in your selection: %s") % self.lot_selection_warning_msg ) mos = self.env["mrp.production"] current_mo = self.production_id for fp_lot in self.finished_lot_ids: # Apply selected lots in matrix and set the qty producing current_mo.lot_producing_id = fp_lot current_mo.qty_producing = 1.0 current_mo._set_qty_producing() for move in current_mo.move_raw_ids: rounding = move.product_id.uom_id.rounding if float_is_zero(move.product_qty, precision_rounding=rounding): # Component moves cannot be deleted in in-progress MO's; however, # they can be set to 0 units to consume. In such case, we ignore # the move. continue if move.product_id.tracking in ["serial", "lot"]: # We filter using the lot nane because the ORM sometimes # is not storing correctly the finished_lot_id in the lines # after passing through the `_onchange_finished_lot_ids` # method. matrix_lines = self.line_ids.filtered( lambda l: ( l.finished_lot_id == fp_lot or l.finished_lot_name == fp_lot.name ) and l.component_id == move.product_id ) if matrix_lines: self._amend_reservations(move, matrix_lines) self._consume_selected_lots(move, matrix_lines) # Complete MO and create backorder if needed. mos += current_mo res = current_mo.button_mark_done() backorder_wizard = self.env["mrp.production.backorder"] if isinstance(res, dict) and res.get("res_model") == backorder_wizard._name: # create backorders... lines = res.get("context", {}).get( "default_mrp_production_backorder_line_ids" ) wizard = backorder_wizard.create( { "mrp_production_ids": current_mo.ids, "mrp_production_backorder_line_ids": lines, } ) wizard.action_backorder() backorder_ids = ( current_mo.procurement_group_id.mrp_production_ids.filtered( lambda mo: mo.state not in ["done", "cancel"] ) ) current_mo = backorder_ids[0] if backorder_ids else False if not current_mo: break else: break # TODO: not specified lots: auto create lots? if not mos: mos = self.production_id res = { "domain": [("id", "in", mos.ids)], "name": _("Manufacturing Orders"), "src_model": "mrp.production.serial.matrix", "view_type": "form", "view_mode": "tree,form", "view_id": False, "views": False, "res_model": "mrp.production", "type": "ir.actions.act_window", } return res def _amend_reservations(self, move, matrix_lines): lots_to_consume = matrix_lines.mapped("component_lot_id") lots_in_move = move.move_line_ids.mapped("lot_id") lots_to_reserve = lots_to_consume - lots_in_move if lots_to_reserve: to_unreserve_lots = lots_in_move - lots_to_consume move.move_line_ids.filtered( lambda l: l.lot_id in to_unreserve_lots ).unlink() for lot in lots_to_reserve: if move.product_id.tracking == "lot": qty = sum( matrix_lines.filtered( lambda l: l.component_lot_id == lot ).mapped("lot_qty") ) qty = qty else: qty = 1.0 self._reserve_lot_in_move(move, lot, qty=qty) return True def _consume_selected_lots(self, move, matrix_lines): lots_to_consume = matrix_lines.mapped("component_lot_id") precision_digits = self.env["decimal.precision"].precision_get( "Product Unit of Measure" ) for ml in move.move_line_ids: if ml.lot_id in lots_to_consume: if move.product_id.tracking == "lot": qty = sum( matrix_lines.filtered( lambda l: l.component_lot_id == ml.lot_id ).mapped("lot_qty") ) ml.qty_done = qty else: ml.qty_done = ml.product_qty elif float_is_zero(ml.product_qty, precision_digits=precision_digits): ml.unlink() else: ml.qty_done = 0.0 def _reserve_lot_in_move(self, move, lot, qty): precision_digits = self.env["decimal.precision"].precision_get( "Product Unit of Measure" ) available_quantity = self.env["stock.quant"]._get_available_quantity( move.product_id, move.location_id, lot_id=lot, ) if ( float_compare(available_quantity, 0.0, precision_digits=precision_digits) <= 0 ): raise ValidationError( _("Serial/Lot number '%s' not available at source location.") % lot.name ) move._update_reserved_quantity( qty, available_quantity, move.location_id, lot_id=lot, strict=True, )
40.923077
14,896
598
py
PYTHON
15.0
# Copyright 2019 Kitti U. - Ecosoft <[email protected]> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Stock Picking Product Kit Helper", "summary": "Set quanity in picking line based on product kit quantity", "version": "15.0.0.1.0", "category": "Stock", "website": "https://github.com/OCA/manufacture", "author": "Ecosoft, Odoo Community Association (OCA)", "license": "AGPL-3", "installable": True, "depends": ["sale_mrp"], "data": ["security/ir.model.access.csv", "views/stock_view.xml"], "maintainers": ["kittiu"], }
39.866667
598
2,930
py
PYTHON
15.0
# Copyright 2019 Kitti U. - Ecosoft <[email protected]> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo.exceptions import ValidationError from odoo.tests import Form, common class TestStockPickingProductKitHelper(common.TransactionCase): def setUp(self): super(TestStockPickingProductKitHelper, self).setUp() self.partner = self.env.ref("base.res_partner_2") self.table_kit = self.env.ref("mrp.product_product_table_kit") def test_00_sale_product_kit_helper(self): """Test sale order with product kit, I expect, - Product is exploded on picking - Use helper, will assign quantity to stock.move correctly - After picking is done, do not allow to use helper """ # Create sales order of 10 table kit order_form = Form(self.env["sale.order"]) order_form.partner_id = self.partner with order_form.order_line.new() as line: line.product_id = self.table_kit line.product_uom_qty = 10 order = order_form.save() order.action_confirm() # In the picking, product line is exploded. picking = order.mapped("picking_ids") self.assertEqual(len(picking), 1) stock_moves = picking.move_lines # 1 SO line exploded to 2 moves moves = [ {"product": x.product_id.name, "qty": x.product_uom_qty} for x in stock_moves ] self.assertEqual( moves, [{"product": "Wood Panel", "qty": 10.0}, {"product": "Bolt", "qty": 40.0}], ) self.assertTrue(picking.has_product_kit) self.assertFalse(picking.product_kit_helper_ids) # Not show yet picking.show_product_kit() self.assertEqual(len(picking.product_kit_helper_ids), 1) # Assign product set 4 qty and test that it apply to stock.move picking.product_kit_helper_ids[0].write({"product_uom_qty": 4.0}) picking.action_product_kit_helper() moves = [ {"product": x.product_id.name, "qty": x.quantity_done} for x in stock_moves ] self.assertEqual( moves, [{"product": "Wood Panel", "qty": 4.0}, {"product": "Bolt", "qty": 16.0}], ) # Assign again to 10 qty picking.product_kit_helper_ids[0].write({"product_uom_qty": 10.0}) picking.action_product_kit_helper() moves = [ {"product": x.product_id.name, "qty": x.quantity_done} for x in stock_moves ] self.assertEqual( moves, [{"product": "Wood Panel", "qty": 10.0}, {"product": "Bolt", "qty": 40.0}], ) # Validate Picking picking.button_validate() self.assertEqual(picking.state, "done") # After done state, block the helper with self.assertRaises(ValidationError): picking.action_product_kit_helper()
41.857143
2,930
5,518
py
PYTHON
15.0
# Copyright 2019 Kitti U. - Ecosoft <[email protected]> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import _, api, fields, models from odoo.exceptions import ValidationError class StockPicking(models.Model): _inherit = "stock.picking" product_kit_helper_ids = fields.One2many( comodel_name="stock.picking.product.kit.helper", string="Product Kit Helper Lines", inverse_name="picking_id", readonly=False, states={"done": [("readonly", True)], "cancel": [("readonly", True)]}, ) has_product_kit = fields.Boolean( compute="_compute_has_product_kit", help="True if there is at least 1 product kit in the sales order", ) @api.model def _is_product_kit(self, product, company): BOM = self.env["mrp.bom"].sudo() bom = BOM._bom_find(products=product, company_id=company.id) return bom and bom.get(product).type == "phantom" def _compute_has_product_kit(self): for picking in self: if any( self._is_product_kit(line.product_id, line.company_id) for line in picking.move_lines.mapped("sale_line_id") ): picking.has_product_kit = True else: picking.has_product_kit = False def show_product_kit(self): """Find move_lines with product kit to create helper line.""" self.ensure_one() BOM = self.env["mrp.bom"].sudo() helpers = [] for sale_line in self.move_lines.mapped("sale_line_id"): bom = BOM._bom_find( products=sale_line.product_id, company_id=sale_line.company_id.id ) if bom and bom.get(sale_line.product_id).type == "phantom": helpers.append( ( 0, 0, { "sale_line_id": sale_line.id, "product_id": sale_line.product_id.id, "product_uom_qty": 0.0, }, ) ) self.product_kit_helper_ids.unlink() self.write({"product_kit_helper_ids": helpers}) def action_product_kit_helper(self): """Assign product kit's quantity to stock move.""" self.ensure_one() if self.state in ("done", "cancel"): raise ValidationError( _("Product Kit Helper is not allowed on current state") ) for helper in self.product_kit_helper_ids: helper.action_explode_helper() class StockPickingProductKitHelper(models.Model): _name = "stock.picking.product.kit.helper" _description = """ Product Kit Helper, allow user to specify quantity of product kit, to explode as product quantity in operations tab """ picking_id = fields.Many2one( comodel_name="stock.picking", string="Picking", required=True, index=True, ondelete="cascade", ) sale_line_id = fields.Many2one( comodel_name="sale.order.line", string="Sales Order Line", required=True ) product_id = fields.Many2one( comodel_name="product.product", string="Product", required=True, readonly=True ) product_uom_qty = fields.Float(string="Quantity") product_uom = fields.Many2one( comodel_name="uom.uom", string="Unit of Measure", related="sale_line_id.product_uom", readonly=True, ) def action_explode_helper(self): """Explodes product kit quantity to detailed product in stock move.""" self.ensure_one() # Mock stock.move, in order to resue stock.move's action_explode StockMove = self.env["stock.move"] mock_loc = self.env["stock.location"].sudo().search([], limit=1) mock_pt = self.env["stock.picking.type"].sudo().search([], limit=1) mock_stock_move = StockMove.sudo().create( { "name": "/", "product_id": self.product_id.id, "product_uom": self.product_uom.id, "product_uom_qty": self.product_uom_qty, "picking_type_id": mock_pt.id, "location_id": mock_loc.id, "location_dest_id": mock_loc.id, } ) # Reuse explode function and assign quantity_done in stock.move mock_processed_moves = mock_stock_move.action_explode() for mock_move in mock_processed_moves: stock_move = StockMove.search( [ ("picking_id", "=", self.picking_id.id), ("sale_line_id", "=", self.sale_line_id.id), ("product_id", "=", mock_move.product_id.id), ] ) if not stock_move: continue if len(stock_move) != 1: raise ValidationError( _( "No matching detailed product %(move_display_name)s for" " product kit %(product_display_name)s" ) % { "move_display_name": mock_move.product_id.display_name, "product_display_name": self.product_id.display_name, } ) stock_move.write({"quantity_done": mock_move.product_uom_qty}) mock_processed_moves.sudo().unlink()
38.319444
5,518
665
py
PYTHON
15.0
# Copyright 2022 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl) { "name": "MRP Subcontracting (no negative components)", "version": "15.0.0.1.0", "development_status": "Alpha", "license": "AGPL-3", "author": "Camptocamp, Odoo Community Association (OCA)", "maintainers": ["sebalix"], "summary": "Disallow negative stock levels in subcontractor locations.", "website": "https://github.com/OCA/manufacture", "category": "Manufacturing", "depends": [ # core "mrp_subcontracting", ], "data": [], "installable": True, "auto_install": True, "application": False, }
31.666667
665
1,506
py
PYTHON
15.0
# Copyright 2022 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl) from odoo.exceptions import UserError from .common import Common class TestMrpSubcontracting(Common): @classmethod def setUpClass(cls): super().setUpClass() cls.subcontracted_bom = cls._get_subcontracted_bom() cls.vendor = cls.env.ref("base.res_partner_12") def test_no_subcontractor_stock(self): picking = self._create_subcontractor_receipt( self.vendor, self.subcontracted_bom ) self.assertEqual(picking.state, "assigned") # No component in the subcontractor location with self.assertRaisesRegex(UserError, "Unable to reserve"): picking.action_record_components() # Try again once the subcontractor received the components self._update_stock_component_qty( bom=self.subcontracted_bom, location=self.vendor.property_stock_subcontractor, ) picking.action_record_components() def test_with_subcontractor_stock(self): # Subcontractor has components before we create the receipt self._update_stock_component_qty( bom=self.subcontracted_bom, location=self.vendor.property_stock_subcontractor, ) picking = self._create_subcontractor_receipt( self.vendor, self.subcontracted_bom ) self.assertEqual(picking.state, "assigned") picking.action_record_components()
36.731707
1,506
3,008
py
PYTHON
15.0
# Copyright 2022 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl) import random import string from odoo.tests import common class Common(common.TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.env = cls.env(context=dict(cls.env.context, tracking_disable=True)) def _create_subcontractor_receipt(self, vendor, bom): with common.Form(self.env["stock.picking"]) as form: form.picking_type_id = self.env.ref("stock.picking_type_in") form.partner_id = vendor with form.move_ids_without_package.new() as move: variant = bom.product_tmpl_id.product_variant_ids move.product_id = variant move.product_uom_qty = 1 picking = form.save() picking.action_confirm() return picking @classmethod def _get_subcontracted_bom(cls): bom = cls.env.ref("mrp_subcontracting.mrp_bom_subcontract") bom.bom_line_ids.unlink() component = cls.env.ref("mrp.product_product_computer_desk_head") component.tracking = "none" bom.bom_line_ids.create( { "bom_id": bom.id, "product_id": component.id, "product_qty": 1, } ) return bom @classmethod def _update_qty_in_location( cls, location, product, quantity, package=None, lot=None, in_date=None ): quants = cls.env["stock.quant"]._gather( product, location, lot_id=lot, package_id=package, strict=True ) # this method adds the quantity to the current quantity, so remove it quantity -= sum(quants.mapped("quantity")) cls.env["stock.quant"]._update_available_quantity( product, location, quantity, package_id=package, lot_id=lot, in_date=in_date, ) @classmethod def _update_stock_component_qty(cls, order=None, bom=None, location=None): if not order and not bom: return if order: bom = order.bom_id if not location: location = cls.env.ref("stock.stock_location_stock") for line in bom.bom_line_ids: if line.product_id.type != "product": continue lot = None if line.product_id.tracking != "none": lot_name = "".join( random.choice(string.ascii_lowercase) for i in range(10) ) vals = { "product_id": line.product_id.id, "company_id": line.company_id.id, "name": lot_name, } lot = cls.env["stock.production.lot"].create(vals) cls._update_qty_in_location( location, line.product_id, line.product_qty, lot=lot, )
34.181818
3,008
1,019
py
PYTHON
15.0
# Copyright 2022 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl) from odoo import _, exceptions, models class StockPicking(models.Model): _inherit = "stock.picking" def action_record_components(self): self.ensure_one() if self._is_subcontract(): # Try to reserve the components for production in self._get_subcontract_production(): if production.reservation_state != "assigned": production.action_assign() # Block the reception if components could not be reserved # NOTE: this also avoids the creation of negative quants if production.reservation_state != "assigned": raise exceptions.UserError( _("Unable to reserve components in the location %s.") % (production.location_src_id.name) ) return super().action_record_components()
42.458333
1,019
547
py
PYTHON
15.0
# Copyright 2018 Tecnativa - David Vidal # Copyright 2018 Tecnativa - Pedro M. Baeza # Copyright 2019 Rubén Bravo <[email protected]> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Production Grouped By Product", "version": "15.0.1.0.0", "category": "MRP", "author": "Tecnativa, " "Odoo Community Association (OCA)", "website": "https://github.com/OCA/manufacture", "license": "AGPL-3", "depends": ["mrp"], "data": ["views/stock_picking_type_views.xml"], "installable": True, }
34.125
546
8,080
py
PYTHON
15.0
# Copyright 2018 Tecnativa - David Vidal # Copyright 2018 Tecnativa - Pedro M. Baeza # Copyright 2019 Rubén Bravo <[email protected]> # Copyright 2021 ForgeFlow S.L. (http://www.forgeflow.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import exceptions from odoo.tests import common class TestProductionGroupedByProduct(common.TransactionCase): at_install = False post_install = True @classmethod def setUpClass(cls): super(TestProductionGroupedByProduct, cls).setUpClass() cls.ProcurementGroup = cls.env["procurement.group"] cls.MrpProduction = cls.env["mrp.production"] cls.env.user.company_id.manufacturing_lead = 0 cls.env.user.tz = False # Make sure there's no timezone in user cls.picking_type = cls.env["stock.picking.type"].search( [ ("code", "=", "mrp_operation"), ("sequence_id.company_id", "=", cls.env.user.company_id.id), ], limit=1, ) cls.product1 = cls.env["product.product"].create( { "name": "TEST Muffin", "route_ids": [ (6, 0, [cls.env.ref("mrp.route_warehouse0_manufacture").id]) ], "type": "product", "produce_delay": 0, } ) cls.product2 = cls.env["product.product"].create( {"name": "TEST Paper muffin cup", "type": "product"} ) cls.product3 = cls.env["product.product"].create( {"name": "TEST Muffin paset", "type": "product"} ) cls.bom = cls.env["mrp.bom"].create( { "product_id": cls.product1.id, "product_tmpl_id": cls.product1.product_tmpl_id.id, "type": "normal", "bom_line_ids": [ (0, 0, {"product_id": cls.product2.id, "product_qty": 1}), (0, 0, {"product_id": cls.product3.id, "product_qty": 0.2}), ], } ) cls.stock_picking_type = cls.env.ref("stock.picking_type_out") cls.mo = cls.MrpProduction.create( { "bom_id": cls.bom.id, "product_id": cls.product1.id, "product_qty": 2, "product_uom_id": cls.product1.uom_id.id, "date_deadline": "2018-06-01 15:00:00", "date_planned_start": "2018-06-01 15:00:00", } ) cls.mo._onchange_move_raw() cls.mo._onchange_move_finished() cls.warehouse = cls.env["stock.warehouse"].search( [("company_id", "=", cls.env.user.company_id.id)], limit=1 ) # Add an MTO move cls.move = cls.env["stock.move"].create( { "name": cls.product1.name, "product_id": cls.product1.id, "product_uom_qty": 10, "product_uom": cls.product1.uom_id.id, "location_id": cls.warehouse.lot_stock_id.id, "location_dest_id": (cls.env.ref("stock.stock_location_customers").id), "procure_method": "make_to_order", "warehouse_id": cls.warehouse.id, "date": "2018-06-01 18:00:00", } ) cls.move_2 = cls.env["stock.move"].create( { "name": cls.product1.name, "product_id": cls.product1.id, "product_uom_qty": 5, "product_uom": cls.product1.uom_id.id, "location_id": cls.warehouse.lot_stock_id.id, "location_dest_id": (cls.env.ref("stock.stock_location_customers").id), "procure_method": "make_to_order", "warehouse_id": cls.warehouse.id, "date": "2018-06-01 18:00:00", } ) def test_01_group_mo_by_product(self): """Test functionality using grouping in a previous manually-created MO.""" self.assertEqual(self.mo.state, "draft") self.assertEqual(len(self.mo.move_finished_ids), 1) self.move.with_context(test_group_mo=True)._action_confirm(merge=False) self.ProcurementGroup.with_context(test_group_mo=True).run_scheduler() mo = self.MrpProduction.search([("product_id", "=", self.product1.id)]) self.assertEqual(len(mo), 1) move_finished = mo.move_finished_ids self.assertEqual(len(mo.move_finished_ids), 1) self.assertEqual(mo.product_qty, 12) self.assertEqual(move_finished.product_qty, 12) mto_prod = mo.move_raw_ids.search([("product_id", "=", self.product2.id)]) self.assertEqual(len(mto_prod), 1) self.assertEqual(mto_prod[0].product_qty, 12) # Run again the scheduler to see if quantities are altered self.ProcurementGroup.with_context(test_group_mo=True).run_scheduler() mo = self.MrpProduction.search([("product_id", "=", self.product1.id)]) self.assertEqual(len(mo), 1) self.assertEqual(mo.product_qty, 12) def test_02_group_mo_by_product_double_procurement(self): """Test functionality using groping in a previous procurement-created MO.""" # Cancelling the manual MO. self.mo.action_cancel() self.assertEqual(self.mo.state, "cancel") mo = self.MrpProduction.search( [("product_id", "=", self.product1.id), ("state", "!=", "cancel")] ) self.assertFalse(mo) # First procurement self.move.with_context(test_group_mo=True)._action_confirm(merge=False) self.ProcurementGroup.with_context(test_group_mo=True).run_scheduler() mo = self.MrpProduction.search( [("product_id", "=", self.product1.id), ("state", "!=", "cancel")] ) self.assertEqual(len(mo), 1) self.assertEqual(mo.state, "confirmed") move_finished = mo.move_finished_ids self.assertEqual(len(move_finished), 1) self.assertEqual(mo.product_qty, 10) self.assertEqual(move_finished.product_qty, 10) mto_prod = mo.move_raw_ids.search( [("product_id", "=", self.product2.id), ("state", "!=", "cancel")] ) self.assertEqual(len(mto_prod), 1) self.assertEqual(mto_prod[0].product_qty, 10) # Do a second procurement self.move_2.with_context(test_group_mo=True)._action_confirm(merge=False) self.ProcurementGroup.with_context(test_group_mo=True).run_scheduler() mo = self.MrpProduction.search( [("product_id", "=", self.product1.id), ("state", "!=", "cancel")] ) self.assertEqual(len(mo), 1) self.assertEqual(mo.state, "confirmed") move_finished = mo.move_finished_ids self.assertEqual(len(move_finished), 1) self.assertEqual(mo.product_qty, 15) self.assertEqual(move_finished.product_qty, 15) mto_prod = mo.move_raw_ids.search( [("product_id", "=", self.product2.id), ("state", "!=", "cancel")] ) self.assertEqual(len(mto_prod), 1) self.assertEqual(mto_prod[0].product_qty, 15) def test_mo_other_date(self): self.move.write({"date": "2018-06-01 20:01:00"}) self.move.with_context(test_group_mo=True)._action_confirm(merge=False) self.ProcurementGroup.with_context(test_group_mo=True).run_scheduler() mo = self.MrpProduction.search([("product_id", "=", self.product1.id)]) self.assertEqual(len(mo), 2) def test_check_mo_grouping_max_hour(self): if self.picking_type: with self.assertRaises(exceptions.ValidationError): self.picking_type.mo_grouping_max_hour = 25 with self.assertRaises(exceptions.ValidationError): self.picking_type.mo_grouping_max_hour = -1 def test_check_mo_grouping_interval(self): if self.picking_type: with self.assertRaises(exceptions.ValidationError): self.picking_type.mo_grouping_interval = -1
44.147541
8,079
1,368
py
PYTHON
15.0
# Copyright 2018 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, api, exceptions, fields, models class StockPickingType(models.Model): _inherit = "stock.picking.type" mo_grouping_max_hour = fields.Integer( string="MO grouping max. hour (UTC)", help="The maximum hour (between 0 and 23) for considering new " "manufacturing orders inside the same interval period, and thus " "being grouped on the same MO. IMPORTANT: The hour should be " "expressed in UTC.", default=19, ) mo_grouping_interval = fields.Integer( string="MO grouping interval (days)", help="The number of days for grouping together on the same " "manufacturing order.", default=1, ) @api.constrains("mo_grouping_max_hour") def _check_mo_grouping_max_hour(self): if self.mo_grouping_max_hour < 0 or self.mo_grouping_max_hour > 23: raise exceptions.ValidationError( _("You have to enter a valid hour between 0 and 23.") ) @api.constrains("mo_grouping_interval") def _check_mo_grouping_interval(self): if self.mo_grouping_interval < 0: raise exceptions.ValidationError( _("You have to enter a positive value for interval.") )
36.972973
1,368
942
py
PYTHON
15.0
# Copyright 2018 Tecnativa - David Vidal # Copyright 2018 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, models class StockMove(models.Model): _inherit = "stock.move" @api.model_create_multi def create(self, vals_list): new_vals_list = [] for val in vals_list: if ( self.env.context.get("group_mo_by_product", False) and "raw_material_production_id" in val ): mo = self.env["mrp.production"].browse( val["raw_material_production_id"] ) # MO already has raw materials if mo.move_raw_ids: continue else: new_vals_list.append(val) else: new_vals_list.append(val) return super(StockMove, self).create(new_vals_list)
32.482759
942
412
py
PYTHON
15.0
# Copyright 2018 Tecnativa - David Vidal # Copyright 2018 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import models class StockRule(models.Model): _inherit = "stock.rule" def _run_manufacture(self, procurements): return super( StockRule, self.with_context(group_mo_by_product=True) )._run_manufacture(procurements)
29.428571
412
5,462
py
PYTHON
15.0
# Copyright 2018 Tecnativa - David Vidal # Copyright 2018 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from dateutil.relativedelta import relativedelta from odoo import api, fields, models from odoo.tools import config class MrpProduction(models.Model): _inherit = "mrp.production" def _post_mo_merging_adjustments(self, vals): """Called when a new MO is merged onto existing one for adjusting the needed values according this merging. :param self: Single record of the target record where merging. :param vals: Dictionary with the new record values. """ self.ensure_one() new_vals = {"origin": (self.origin or "") + ",%s" % vals["origin"]} if vals.get("move_dest_ids"): new_vals["move_dest_ids"] = vals["move_dest_ids"] self.move_finished_ids.move_dest_ids = vals["move_dest_ids"] self.write(new_vals) def _get_grouping_target_vals(self): self.ensure_one() return { "product_id": self.product_id.id, "picking_type_id": self.picking_type_id.id, "bom_id": self.bom_id.id, "company_id": self.company_id.id, "state": self.state, "date_deadline": self.date_deadline, } # NOTE: when extending this logic, remember to also adapt # `_get_grouping_target_vals` accordingly. def _get_grouping_target_domain(self, vals): """Get the domain for searching manufacturing orders that can match with the criteria we want to use. :param vals: Values dictionary of the MO to be created. :return: Odoo domain. """ bom_has_routing = bool(self.env["mrp.bom"].browse(vals["bom_id"]).operation_ids) domain = [ ("product_id", "=", vals["product_id"]), ("picking_type_id", "=", vals["picking_type_id"]), ("bom_id", "=", vals.get("bom_id", False)), ("company_id", "=", vals.get("company_id", False)), ("state", "in", ["draft", "confirmed"]), ] if bom_has_routing: domain.append(("workorder_ids", "!=", False)) else: domain.append(("workorder_ids", "=", False)) if not vals.get("date_deadline"): return domain date = fields.Datetime.from_string(vals["date_deadline"]) pt = self.env["stock.picking.type"].browse(vals["picking_type_id"]) if date.hour < pt.mo_grouping_max_hour: date_end = date.replace(hour=pt.mo_grouping_max_hour, minute=0, second=0) else: date_end = date.replace( day=date.day + 1, hour=pt.mo_grouping_max_hour, minute=0, second=0 ) date_start = date_end - relativedelta(days=pt.mo_grouping_interval) domain += [ ("date_deadline", ">", fields.Datetime.to_string(date_start)), ("date_deadline", "<=", fields.Datetime.to_string(date_end)), ] return domain def _find_grouping_target(self, vals): """Return the matching order for grouping. :param vals: Values dictionary of the MO to be created. :return: Target manufacturing order record (or empty record). """ return self.env["mrp.production"].search( self._get_grouping_target_domain(vals), limit=1 ) @api.model def create(self, vals): context = self.env.context if context.get("group_mo_by_product") and ( not config["test_enable"] or context.get("test_group_mo") ): mo = self._find_grouping_target(vals) if mo: self.env["change.production.qty"].create( { "mo_id": mo.id, "product_qty": mo.product_qty + vals["product_qty"], } ).change_prod_qty() mo._post_mo_merging_adjustments(vals) return mo return super(MrpProduction, self).create(vals) def _create_workorder(self): # We need to skip the creation of workorders during `_run_manufacture`. # It is not possible to pass a context from the `_post_mo_merging_adjustments` # because the create is called with sudo in `_run_manufacture` and that # creates a new context that does not reach `_create_workorder` call. context = self.env.context to_create_wos = self if context.get("group_mo_by_product") and ( not config["test_enable"] or context.get("test_group_mo") ): for rec in self: vals = rec._get_grouping_target_vals() mo = self._find_grouping_target(vals) if mo: to_create_wos -= rec return super(MrpProduction, to_create_wos)._create_workorder() def _get_moves_finished_values(self): # We need to skip the creation of more finished moves during `_run_manufacture`. new_self = self if self.env.context.get("group_mo_by_product"): for rec in self: if not rec.move_finished_ids: continue vals = rec._get_grouping_target_vals() mo = self._find_grouping_target(vals) if mo: new_self -= rec return super(MrpProduction, new_self)._get_moves_finished_values()
40.459259
5,462
716
py
PYTHON
15.0
# Copyright 2022 Camptocamp SA # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl) { "name": "Mrp Lot On Hand First", "summary": "Allows to display lots on hand first in M2o fields", "version": "15.0.1.0.0", "development_status": "Alpha", "category": "Manufacturing/Manufacturing", "website": "https://github.com/OCA/manufacture", "author": "Camptocamp, Odoo Community Association (OCA)", "maintainers": ["grindtildeath"], "license": "AGPL-3", "installable": True, "auto_install": True, "depends": [ "mrp", "stock_lot_on_hand_first", ], "data": [ "views/mrp_production.xml", "views/stock_picking_type.xml", ], }
31.130435
716
313
py
PYTHON
15.0
# Copyright 2022 Camptocamp SA # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl) from odoo import fields, models class MrpProduction(models.Model): _inherit = "mrp.production" display_lots_on_hand_first = fields.Boolean( related="picking_type_id.display_lots_on_hand_first" )
28.454545
313
1,714
py
PYTHON
15.0
# Copyright 2016 Ucamco - Wim Audenaert <[email protected]> # Copyright 2016-21 ForgeFlow S.L. (https://www.forgeflow.com) # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). { "name": "MRP Multi Level", "version": "15.0.1.10.0", "development_status": "Production/Stable", "license": "LGPL-3", "author": "Ucamco, ForgeFlow, Odoo Community Association (OCA)", "maintainers": ["JordiBForgeFlow", "LoisRForgeFlow", "ChrisOForgeFlow"], "summary": "Adds an MRP Scheduler", "website": "https://github.com/OCA/manufacture", "category": "Manufacturing", "depends": ["mrp", "purchase_stock", "mrp_warehouse_calendar"], "data": [ "security/mrp_multi_level_security.xml", "security/ir.model.access.csv", "data/system_parameter.xml", "views/mrp_area_views.xml", "views/product_product_views.xml", "views/product_template_views.xml", "views/product_mrp_area_views.xml", "views/stock_location_views.xml", "wizards/mrp_inventory_procure_views.xml", "views/mrp_inventory_views.xml", "views/mrp_planned_order_views.xml", "wizards/mrp_multi_level_views.xml", "views/mrp_move_views.xml", "views/mrp_menuitem.xml", "data/mrp_multi_level_cron.xml", "data/mrp_area_data.xml", ], "demo": [ "demo/product_category_demo.xml", "demo/product_product_demo.xml", "demo/res_partner_demo.xml", "demo/product_supplierinfo_demo.xml", "demo/product_mrp_area_demo.xml", "demo/mrp_bom_demo.xml", "demo/initial_on_hand_demo.xml", ], "installable": True, "application": True, }
38.088889
1,714
19,105
py
PYTHON
15.0
# Copyright 2018-19 ForgeFlow S.L. (https://www.forgeflow.com) # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from datetime import date, datetime from odoo import fields from .common import TestMrpMultiLevelCommon class TestMrpMultiLevel(TestMrpMultiLevelCommon): def test_01_mrp_levels(self): """Tests computation of MRP levels.""" self.assertEqual(self.fp_1.llc, 0) self.assertEqual(self.fp_2.llc, 0) self.assertEqual(self.sf_1.llc, 1) self.assertEqual(self.sf_2.llc, 1) self.assertEqual(self.pp_1.llc, 2) self.assertEqual(self.pp_2.llc, 2) def test_02_product_mrp_area(self): """Tests that mrp products are generated correctly.""" product_mrp_area = self.product_mrp_area_obj.search( [("product_id", "=", self.pp_1.id)] ) self.assertEqual(product_mrp_area.supply_method, "buy") self.assertEqual(product_mrp_area.main_supplier_id, self.vendor) self.assertEqual(product_mrp_area.qty_available, 10.0) product_mrp_area = self.product_mrp_area_obj.search( [("product_id", "=", self.sf_1.id)] ) self.assertEqual(product_mrp_area.supply_method, "manufacture") self.assertFalse(product_mrp_area.main_supplier_id) self.assertFalse(product_mrp_area.main_supplierinfo_id) # Archiving the product should archive parameters: self.assertTrue(product_mrp_area.active) self.sf_1.active = False self.assertFalse(product_mrp_area.active) def test_03_mrp_moves(self): """Tests for mrp moves generated.""" moves = self.mrp_move_obj.search([("product_id", "=", self.pp_1.id)]) self.assertEqual(len(moves), 3) self.assertNotIn("s", moves.mapped("mrp_type")) for move in moves: self.assertTrue(move.planned_order_up_ids) if move.planned_order_up_ids.product_mrp_area_id.product_id == self.fp_1: # Demand coming from FP-1 self.assertEqual(move.planned_order_up_ids.mrp_action, "manufacture") self.assertEqual(move.mrp_qty, -200.0) elif move.planned_order_up_ids.product_mrp_area_id.product_id == self.sf_1: # Demand coming from FP-2 -> SF-1 self.assertEqual(move.planned_order_up_ids.mrp_action, "manufacture") if move.mrp_date == self.date_5: self.assertEqual(move.mrp_qty, -90.0) elif move.mrp_date == self.date_8: self.assertEqual(move.mrp_qty, -72.0) # Check actions: planned_orders = self.planned_order_obj.search( [("product_id", "=", self.pp_1.id)] ) self.assertEqual(len(planned_orders), 3) for plan in planned_orders: self.assertEqual(plan.mrp_action, "buy") # Check PP-2 PO being accounted: po_move = self.mrp_move_obj.search( [("product_id", "=", self.pp_2.id), ("mrp_type", "=", "s")] ) self.assertEqual(len(po_move), 1) self.assertEqual(po_move.purchase_order_id, self.po) self.assertEqual(po_move.purchase_line_id, self.po.order_line) def test_04_mrp_multi_level(self): """Tests MRP inventories created.""" # FP-1 fp_1_inventory_lines = self.mrp_inventory_obj.search( [("product_mrp_area_id.product_id", "=", self.fp_1.id)] ) self.assertEqual(len(fp_1_inventory_lines), 1) self.assertEqual(fp_1_inventory_lines.date, self.date_7) self.assertEqual(fp_1_inventory_lines.demand_qty, 100.0) self.assertEqual(fp_1_inventory_lines.to_procure, 100.0) # FP-2 fp_2_line_1 = self.mrp_inventory_obj.search( [ ("product_mrp_area_id.product_id", "=", self.fp_2.id), ("date", "=", self.date_7), ] ) self.assertEqual(len(fp_2_line_1), 1) self.assertEqual(fp_2_line_1.demand_qty, 15.0) self.assertEqual(fp_2_line_1.to_procure, 15.0) fp_2_line_2 = self.mrp_inventory_obj.search( [ ("product_mrp_area_id.product_id", "=", self.fp_2.id), ("date", "=", self.date_10), ] ) self.assertEqual(len(fp_2_line_2), 1) self.assertEqual(fp_2_line_2.demand_qty, 0.0) self.assertEqual(fp_2_line_2.to_procure, 0.0) self.assertEqual(fp_2_line_2.supply_qty, 12.0) # SF-1 sf_1_line_1 = self.mrp_inventory_obj.search( [ ("product_mrp_area_id.product_id", "=", self.sf_1.id), ("date", "=", self.date_6), ] ) self.assertEqual(len(sf_1_line_1), 1) self.assertEqual(sf_1_line_1.demand_qty, 30.0) self.assertEqual(sf_1_line_1.to_procure, 30.0) sf_1_line_2 = self.mrp_inventory_obj.search( [ ("product_mrp_area_id.product_id", "=", self.sf_1.id), ("date", "=", self.date_9), ] ) self.assertEqual(len(sf_1_line_2), 1) self.assertEqual(sf_1_line_2.demand_qty, 24.0) self.assertEqual(sf_1_line_2.to_procure, 24.0) # SF-2 sf_2_line_1 = self.mrp_inventory_obj.search( [ ("product_mrp_area_id.product_id", "=", self.sf_2.id), ("date", "=", self.date_6), ] ) self.assertEqual(len(sf_2_line_1), 1) self.assertEqual(sf_2_line_1.demand_qty, 45.0) self.assertEqual(sf_2_line_1.to_procure, 30.0) sf_2_line_2 = self.mrp_inventory_obj.search( [ ("product_mrp_area_id.product_id", "=", self.sf_2.id), ("date", "=", self.date_9), ] ) self.assertEqual(len(sf_2_line_2), 1) self.assertEqual(sf_2_line_2.demand_qty, 36.0) self.assertEqual(sf_2_line_2.to_procure, 36.0) # PP-1 pp_1_line_1 = self.mrp_inventory_obj.search( [ ("product_mrp_area_id.product_id", "=", self.pp_1.id), ("date", "=", self.date_5), ] ) self.assertEqual(len(pp_1_line_1), 1) self.assertEqual(pp_1_line_1.demand_qty, 290.0) self.assertEqual(pp_1_line_1.to_procure, 280.0) pp_1_line_2 = self.mrp_inventory_obj.search( [ ("product_mrp_area_id.product_id", "=", self.pp_1.id), ("date", "=", self.date_8), ] ) self.assertEqual(len(pp_1_line_2), 1) self.assertEqual(pp_1_line_2.demand_qty, 72.0) self.assertEqual(pp_1_line_2.to_procure, 72.0) # PP-2 pp_2_line_1 = self.mrp_inventory_obj.search( [ ("product_mrp_area_id.product_id", "=", self.pp_2.id), ("date", "=", self.date_3), ] ) self.assertEqual(len(pp_2_line_1), 1) self.assertEqual(pp_2_line_1.demand_qty, 90.0) # 90.0 demand - 20.0 on hand - 5.0 on PO = 65.0 self.assertEqual(pp_2_line_1.to_procure, 65.0) pp_2_line_2 = self.mrp_inventory_obj.search( [ ("product_mrp_area_id.product_id", "=", self.pp_2.id), ("date", "=", self.date_5), ] ) self.assertEqual(len(pp_2_line_2), 1) self.assertEqual(pp_2_line_2.demand_qty, 360.0) self.assertEqual(pp_2_line_2.to_procure, 360.0) pp_2_line_3 = self.mrp_inventory_obj.search( [ ("product_mrp_area_id.product_id", "=", self.pp_2.id), ("date", "=", self.date_6), ] ) self.assertEqual(len(pp_2_line_3), 1) self.assertEqual(pp_2_line_3.demand_qty, 108.0) self.assertEqual(pp_2_line_3.to_procure, 108.0) pp_2_line_4 = self.mrp_inventory_obj.search( [ ("product_mrp_area_id.product_id", "=", self.pp_2.id), ("date", "=", self.date_8), ] ) self.assertEqual(len(pp_2_line_4), 1) self.assertEqual(pp_2_line_4.demand_qty, 48.0) self.assertEqual(pp_2_line_4.to_procure, 48.0) def test_05_planned_availability(self): """Test planned availability computation.""" # Running availability for PP-1: invs = self.mrp_inventory_obj.search( [("product_id", "=", self.pp_1.id)], order="date" ) self.assertEqual(len(invs), 2) expected = [0.0, 0.0] # No grouping, lot size nor safety stock. self.assertEqual(invs.mapped("running_availability"), expected) def test_06_procure_mo(self): """Test procurement wizard with MOs.""" mos = self.mo_obj.search([("product_id", "=", self.fp_1.id)]) self.assertFalse(mos) mrp_inv = self.mrp_inventory_obj.search( [("product_mrp_area_id.product_id", "=", self.fp_1.id)] ) self.mrp_inventory_procure_wiz.with_context( active_model="mrp.inventory", active_ids=mrp_inv.ids, active_id=mrp_inv.id, ).create({}).make_procurement() mos = self.mo_obj.search([("product_id", "=", self.fp_1.id)]) self.assertTrue(mos) self.assertEqual(mos.product_qty, 100.0) mo_date_start = fields.Date.to_date(mos.date_planned_start) self.assertEqual(mo_date_start, self.date_5) def test_07_adjust_qty_to_order(self): """Test the adjustments made to the qty to procure when minimum, maximum order quantities and quantity multiple are set.""" # minimum order quantity: mrp_inv_min = self.mrp_inventory_obj.search( [("product_mrp_area_id.product_id", "=", self.prod_min.id)] ) self.assertEqual(mrp_inv_min.to_procure, 50.0) # maximum order quantity: mrp_inv_max = self.mrp_inventory_obj.search( [("product_mrp_area_id.product_id", "=", self.prod_max.id)] ) self.assertEqual(mrp_inv_max.to_procure, 150) plans = self.planned_order_obj.search([("product_id", "=", self.prod_max.id)]) self.assertEqual(len(plans), 2) self.assertIn(100.0, plans.mapped("mrp_qty")) self.assertIn(50.0, plans.mapped("mrp_qty")) # quantity multiple: mrp_inv_multiple = self.mrp_inventory_obj.search( [("product_mrp_area_id.product_id", "=", self.prod_multiple.id)] ) self.assertEqual(mrp_inv_multiple.to_procure, 125) def test_08_group_demand(self): """Test demand grouping functionality, `nbr_days`.""" pickings = self.stock_picking_obj.search( [ ("product_id", "=", self.prod_test.id), ("location_id", "=", self.sec_loc.id), ] ) self.assertEqual(len(pickings), 5) moves = self.mrp_move_obj.search( [ ("product_id", "=", self.prod_test.id), ("mrp_area_id", "=", self.secondary_area.id), ] ) supply_plans = self.planned_order_obj.search( [ ("product_id", "=", self.prod_test.id), ("mrp_area_id", "=", self.secondary_area.id), ] ) moves_demand = moves.filtered(lambda m: m.mrp_type == "d") self.assertEqual(len(moves_demand), 5) # two groups expected: # 1. days 8, 9 and 10. # 2. days 20, and 22. self.assertEqual(len(supply_plans), 2) quantities = supply_plans.mapped("mrp_qty") week_1_expected = sum(moves_demand[0:3].mapped("mrp_qty")) self.assertIn(abs(week_1_expected), quantities) week_2_expected = sum(moves_demand[3:].mapped("mrp_qty")) self.assertIn(abs(week_2_expected), quantities) def test_09_isolated_mrp_area_run(self): """Test running MRP for just one area.""" self.mrp_multi_level_wiz.with_user(self.mrp_manager).create( {"mrp_area_ids": [(6, 0, self.secondary_area.ids)]} ).run_mrp_multi_level() this = self.mrp_inventory_obj.search( [("mrp_area_id", "=", self.secondary_area.id)], limit=1 ) self.assertTrue(this) # Only recently exectued areas should have been created by test user: self.assertEqual(this.create_uid, self.mrp_manager) prev = self.mrp_inventory_obj.search( [("mrp_area_id", "!=", self.secondary_area.id)], limit=1 ) self.assertNotEqual(this.create_uid, prev.create_uid) def test_11_special_scenario_1(self): """When grouping demand supply and demand are in the same day but supply goes first.""" moves = self.mrp_move_obj.search( [("product_id", "=", self.product_scenario_1.id)] ) self.assertEqual(len(moves), 4) mrp_invs = self.mrp_inventory_obj.search( [("product_id", "=", self.product_scenario_1.id)] ) self.assertEqual(len(mrp_invs), 2) # Net needs = 124 + 90 - 87 = 127 -> 130 (because of qty multiple) self.assertEqual(mrp_invs[0].to_procure, 130) # Net needs = 18, available on-hand = 3 -> 15 self.assertEqual(mrp_invs[1].to_procure, 15) def test_12_bom_line_attribute_value_skip(self): """Check for the correct demand on components of a product with multiple variants""" product_4b_demand = self.mrp_inventory_obj.search( [("product_mrp_area_id.product_id", "=", self.product_4b.id)] ) self.assertTrue(product_4b_demand) self.assertTrue(product_4b_demand.to_procure) # No demand or supply for AV-12 or AV-21 av_12_supply = self.mrp_inventory_obj.search( [("product_mrp_area_id.product_id", "=", self.av_12.id)] ) self.assertFalse(av_12_supply) av_21_supply = self.mrp_inventory_obj.search( [("product_mrp_area_id.product_id", "=", self.av_21.id)] ) self.assertFalse(av_21_supply) # Supply for AV-11 and AV-22 av_11_supply = self.mrp_inventory_obj.search( [("product_mrp_area_id.product_id", "=", self.av_11.id)] ) self.assertTrue(av_11_supply) av_22_supply = self.mrp_inventory_obj.search( [("product_mrp_area_id.product_id", "=", self.av_22.id)] ) self.assertTrue(av_22_supply) def test_13_timezone_handling(self): self.calendar.tz = "Australia/Sydney" # Oct-Apr/Apr-Oct: UTC+11/UTC+10 date_move = datetime(2090, 4, 19, 20, 00) # Apr 20 6/7 am in Sidney sidney_date = date(2090, 4, 20) self._create_picking_in( self.product_tz, 10.0, date_move, location=self.cases_loc ) self.mrp_multi_level_wiz.create( {"mrp_area_ids": [(6, 0, self.cases_area.ids)]} ).run_mrp_multi_level() inventory = self.mrp_inventory_obj.search( [ ("mrp_area_id", "=", self.cases_area.id), ("product_id", "=", self.product_tz.id), ] ) self.assertEqual(len(inventory), 1) self.assertEqual(inventory.date, sidney_date) def test_14_timezone_not_set(self): self.wh.calendar_id = False date_move = datetime(2090, 4, 19, 20, 00) self._create_picking_in( self.product_tz, 10.0, date_move, location=self.cases_loc ) self.mrp_multi_level_wiz.create( {"mrp_area_ids": [(6, 0, self.cases_area.ids)]} ).run_mrp_multi_level() inventory = self.mrp_inventory_obj.search( [ ("mrp_area_id", "=", self.cases_area.id), ("product_id", "=", self.product_tz.id), ] ) self.assertEqual(len(inventory), 1) self.assertEqual(inventory.date, date_move.date()) def test_15_units_case(self): """When a product has a different purchase unit of measure than the general unit of measure and the supply is coming from an RFQ""" prod_uom_test_inventory_lines = self.mrp_inventory_obj.search( [("product_mrp_area_id.product_id", "=", self.prod_uom_test.id)] ) self.assertEqual(len(prod_uom_test_inventory_lines), 1) self.assertEqual(prod_uom_test_inventory_lines.supply_qty, 12.0) # Supply qty has to be 12 has a dozen of units are in a RFQ. def test_16_phantom_comp_planning(self): """ Phantom components will not appear in MRP Inventory or Planned Orders. MRP Parameter will have 'phantom' supply method. """ # SF-3 sf_3_line_1 = self.mrp_inventory_obj.search( [("product_mrp_area_id.product_id", "=", self.sf_3.id)] ) self.assertEqual(len(sf_3_line_1), 0) sf_3_planned_order_1 = self.planned_order_obj.search( [("product_mrp_area_id.product_id", "=", self.sf_3.id)] ) self.assertEqual(len(sf_3_planned_order_1), 0) sf_3_mrp_parameter = self.product_mrp_area_obj.search( [("product_id", "=", self.sf_3.id)] ) self.assertEqual(sf_3_mrp_parameter.supply_method, "phantom") # PP-3 pp_3_line_1 = self.mrp_inventory_obj.search( [("product_mrp_area_id.product_id", "=", self.pp_3.id)] ) self.assertEqual(len(pp_3_line_1), 1) self.assertEqual(pp_3_line_1.demand_qty, 20.0) pp_3_planned_orders = self.planned_order_obj.search( [("product_mrp_area_id.product_id", "=", self.pp_3.id)] ) self.assertEqual(len(pp_3_planned_orders), 2) # PP-4 pp_4_line_1 = self.mrp_inventory_obj.search( [("product_mrp_area_id.product_id", "=", self.pp_4.id)] ) self.assertEqual(len(pp_4_line_1), 1) self.assertEqual(pp_4_line_1.demand_qty, 30.0) pp_4_planned_orders = self.planned_order_obj.search( [("product_mrp_area_id.product_id", "=", self.pp_4.id)] ) self.assertEqual(len(pp_4_planned_orders), 1) def test_17_supply_method(self): """Test supply method computation.""" self.fp_4.route_ids = [(5, 0, 0)] product_mrp_area = self.product_mrp_area_obj.search( [("product_id", "=", self.fp_4.id)] ) self.assertEqual(product_mrp_area.supply_method, "none") self.fp_4.route_ids = [(4, self.env.ref("stock.route_warehouse0_mto").id)] product_mrp_area._compute_supply_method() self.assertEqual(product_mrp_area.supply_method, "pull") self.fp_4.route_ids = [(4, self.env.ref("mrp.route_warehouse0_manufacture").id)] product_mrp_area._compute_supply_method() self.assertEqual(product_mrp_area.supply_method, "manufacture") self.fp_4.route_ids = [ (4, self.env.ref("purchase_stock.route_warehouse0_buy").id) ] product_mrp_area._compute_supply_method() self.assertEqual(product_mrp_area.supply_method, "buy")
42.740492
19,105
22,873
py
PYTHON
15.0
# Copyright 2018-19 ForgeFlow S.L. (https://www.forgeflow.com) # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from datetime import datetime, timedelta from odoo.tests import Form from odoo.tests.common import TransactionCase class TestMrpMultiLevelCommon(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.mo_obj = cls.env["mrp.production"] cls.po_obj = cls.env["purchase.order"] cls.product_obj = cls.env["product.product"] cls.loc_obj = cls.env["stock.location"] cls.mrp_area_obj = cls.env["mrp.area"] cls.product_mrp_area_obj = cls.env["product.mrp.area"] cls.partner_obj = cls.env["res.partner"] cls.res_users = cls.env["res.users"] cls.stock_picking_obj = cls.env["stock.picking"] cls.mrp_multi_level_wiz = cls.env["mrp.multi.level"] cls.mrp_inventory_procure_wiz = cls.env["mrp.inventory.procure"] cls.mrp_inventory_obj = cls.env["mrp.inventory"] cls.mrp_move_obj = cls.env["mrp.move"] cls.planned_order_obj = cls.env["mrp.planned.order"] cls.fp_1 = cls.env.ref("mrp_multi_level.product_product_fp_1") cls.fp_2 = cls.env.ref("mrp_multi_level.product_product_fp_2") cls.fp_3 = cls.env.ref("mrp_multi_level.product_product_fp_3") cls.fp_4 = cls.env.ref("mrp_multi_level.product_product_fp_4") cls.sf_1 = cls.env.ref("mrp_multi_level.product_product_sf_1") cls.sf_2 = cls.env.ref("mrp_multi_level.product_product_sf_2") cls.sf_3 = cls.env.ref("mrp_multi_level.product_product_sf_3") cls.pp_1 = cls.env.ref("mrp_multi_level.product_product_pp_1") cls.pp_2 = cls.env.ref("mrp_multi_level.product_product_pp_2") cls.pp_3 = cls.env.ref("mrp_multi_level.product_product_pp_3") cls.pp_4 = cls.env.ref("mrp_multi_level.product_product_pp_4") cls.product_4b = cls.env.ref("product.product_product_4b") cls.av_11 = cls.env.ref("mrp_multi_level.product_product_av_11") cls.av_12 = cls.env.ref("mrp_multi_level.product_product_av_12") cls.av_21 = cls.env.ref("mrp_multi_level.product_product_av_21") cls.av_22 = cls.env.ref("mrp_multi_level.product_product_av_22") cls.company = cls.env.ref("base.main_company") cls.mrp_area = cls.env.ref("mrp_multi_level.mrp_area_stock_wh0") cls.vendor = cls.env.ref("mrp_multi_level.res_partner_lazer_tech") cls.wh = cls.env.ref("stock.warehouse0") cls.stock_location = cls.wh.lot_stock_id cls.customer_location = cls.env.ref("stock.stock_location_customers") cls.supplier_location = cls.env.ref("stock.stock_location_suppliers") cls.calendar = cls.env.ref("resource.resource_calendar_std") # Add calendar to WH: cls.wh.calendar_id = cls.calendar # Partner: vendor1 = cls.partner_obj.create({"name": "Vendor 1"}) # Create user: group_mrp_manager = cls.env.ref("mrp.group_mrp_manager") group_user = cls.env.ref("base.group_user") group_stock_manager = cls.env.ref("stock.group_stock_manager") cls.mrp_manager = cls._create_user( "Test User", [group_mrp_manager, group_user, group_stock_manager], cls.company, ) # Create secondary location and MRP Area: cls.sec_loc = cls.loc_obj.create( { "name": "Test location", "usage": "internal", "location_id": cls.wh.view_location_id.id, } ) cls.secondary_area = cls.mrp_area_obj.create( {"name": "Test", "warehouse_id": cls.wh.id, "location_id": cls.sec_loc.id} ) # Create an area for design special cases and test them, different # cases will be expected to not share products, this way each case # can be isolated. cls.cases_loc = cls.loc_obj.create( { "name": "Special Cases location", "usage": "internal", "location_id": cls.wh.view_location_id.id, } ) cls.cases_area = cls.mrp_area_obj.create( { "name": "Special Cases Tests", "warehouse_id": cls.wh.id, "location_id": cls.cases_loc.id, } ) # Create products: route_buy = cls.env.ref("purchase_stock.route_warehouse0_buy").id cls.prod_test = cls.product_obj.create( { "name": "Test Top Seller", "type": "product", "list_price": 150.0, "produce_delay": 5.0, "route_ids": [(6, 0, [route_buy])], "seller_ids": [(0, 0, {"name": vendor1.id, "price": 20.0})], } ) cls.product_mrp_area_obj.create( {"product_id": cls.prod_test.id, "mrp_area_id": cls.mrp_area.id} ) # Parameters in secondary area with nbr_days set. cls.product_mrp_area_obj.create( { "product_id": cls.prod_test.id, "mrp_area_id": cls.secondary_area.id, "mrp_nbr_days": 7, } ) cls.prod_min = cls.product_obj.create( { "name": "Product with minimum order qty", "type": "product", "list_price": 50.0, "route_ids": [(6, 0, [route_buy])], "seller_ids": [(0, 0, {"name": vendor1.id, "price": 10.0})], } ) cls.product_mrp_area_obj.create( { "product_id": cls.prod_min.id, "mrp_area_id": cls.mrp_area.id, "mrp_minimum_order_qty": 50.0, "mrp_maximum_order_qty": 0.0, "mrp_qty_multiple": 1.0, } ) cls.prod_max = cls.product_obj.create( { "name": "Product with maximum order qty", "type": "product", "list_price": 50.0, "route_ids": [(6, 0, [route_buy])], "seller_ids": [(0, 0, {"name": vendor1.id, "price": 10.0})], } ) cls.product_mrp_area_obj.create( { "product_id": cls.prod_max.id, "mrp_area_id": cls.mrp_area.id, "mrp_minimum_order_qty": 50.0, "mrp_maximum_order_qty": 100.0, "mrp_qty_multiple": 1.0, } ) cls.prod_multiple = cls.product_obj.create( { "name": "Product with qty multiple", "type": "product", "list_price": 50.0, "route_ids": [(6, 0, [route_buy])], "seller_ids": [(0, 0, {"name": vendor1.id, "price": 10.0})], } ) cls.product_mrp_area_obj.create( { "product_id": cls.prod_multiple.id, "mrp_area_id": cls.mrp_area.id, "mrp_minimum_order_qty": 50.0, "mrp_maximum_order_qty": 500.0, "mrp_qty_multiple": 25.0, } ) # Create more products to test special corner case scenarios: cls.product_scenario_1 = cls.product_obj.create( { "name": "Product Special Scenario 1", "type": "product", "list_price": 100.0, "route_ids": [(6, 0, [route_buy])], "seller_ids": [(0, 0, {"name": vendor1.id, "price": 20.0})], } ) cls.product_mrp_area_obj.create( { "product_id": cls.product_scenario_1.id, "mrp_area_id": cls.cases_area.id, "mrp_nbr_days": 7, "mrp_qty_multiple": 5.0, } ) # Another product: cls.product_tz = cls.product_obj.create( { "name": "Product Timezone", "type": "product", "list_price": 100.0, "route_ids": [(6, 0, [route_buy])], "seller_ids": [(0, 0, {"name": vendor1.id, "price": 20.0})], } ) cls.product_mrp_area_obj.create( {"product_id": cls.product_tz.id, "mrp_area_id": cls.cases_area.id} ) # Product to test special case with Purchase Uom: cls.prod_uom_test = cls.product_obj.create( { "name": "Product Uom Test", "type": "product", "uom_id": cls.env.ref("uom.product_uom_unit").id, "uom_po_id": cls.env.ref("uom.product_uom_dozen").id, "list_price": 150.0, "produce_delay": 5.0, "route_ids": [(6, 0, [route_buy])], "seller_ids": [(0, 0, {"name": vendor1.id, "price": 20.0})], } ) cls.product_mrp_area_obj.create( {"product_id": cls.prod_uom_test.id, "mrp_area_id": cls.mrp_area.id} ) # Product MRP Parameter to test supply method computation cls.env.ref("stock.route_warehouse0_mto").active = True cls.env["stock.rule"].create( { "name": "WH2: Main Area → Secondary Area (MTO)", "action": "pull", "picking_type_id": cls.env.ref("stock.picking_type_in").id, "location_src_id": cls.env.ref("stock.stock_location_stock").id, "location_id": cls.sec_loc.id, "route_id": cls.env.ref("stock.route_warehouse0_mto").id, "procure_method": "mts_else_mto", } ) cls.product_mrp_area_obj.create( {"product_id": cls.fp_4.id, "mrp_area_id": cls.secondary_area.id} ) # Create pickings for Scenario 1: dt_base = cls.calendar.plan_days(3 + 1, datetime.today()) cls._create_picking_in( cls.product_scenario_1, 87, dt_base, location=cls.cases_loc ) dt_bit_later = dt_base + timedelta(hours=1) cls._create_picking_out( cls.product_scenario_1, 124, dt_bit_later, location=cls.cases_loc ) dt_base_2 = cls.calendar.plan_days(3 + 1, datetime.today()) cls._create_picking_out( cls.product_scenario_1, 90, dt_base_2, location=cls.cases_loc ) dt_next_group = cls.calendar.plan_days(10 + 1, datetime.today()) cls._create_picking_out( cls.product_scenario_1, 18, dt_next_group, location=cls.cases_loc ) # Create test picking for FP-1, FP-2 and Desk(steel, black): res = cls.calendar.plan_days(7 + 1, datetime.today().replace(hour=0)) date_move = res.date() cls.picking_1 = cls.stock_picking_obj.create( { "picking_type_id": cls.env.ref("stock.picking_type_out").id, "location_id": cls.stock_location.id, "location_dest_id": cls.customer_location.id, "scheduled_date": date_move, "move_lines": [ ( 0, 0, { "name": "Test move fp-1", "product_id": cls.fp_1.id, "date": date_move, "product_uom": cls.fp_1.uom_id.id, "product_uom_qty": 100, "location_id": cls.stock_location.id, "location_dest_id": cls.customer_location.id, }, ), ( 0, 0, { "name": "Test move fp-2", "product_id": cls.fp_2.id, "date": date_move, "product_uom": cls.fp_2.uom_id.id, "product_uom_qty": 15, "location_id": cls.stock_location.id, "location_dest_id": cls.customer_location.id, }, ), ( 0, 0, { "name": "Test move fp-3", "product_id": cls.fp_3.id, "date": date_move, "product_uom": cls.fp_3.uom_id.id, "product_uom_qty": 5, "location_id": cls.stock_location.id, "location_dest_id": cls.customer_location.id, }, ), ( 0, 0, { "name": "Test move product-4b", "product_id": cls.product_4b.id, "date": date_move, "product_uom": cls.product_4b.uom_id.id, "product_uom_qty": 150, "location_id": cls.stock_location.id, "location_dest_id": cls.customer_location.id, }, ), ], } ) cls.picking_1.action_confirm() # Create test picking for procure qty adjustment tests: cls.picking_2 = cls.stock_picking_obj.create( { "picking_type_id": cls.env.ref("stock.picking_type_out").id, "location_id": cls.stock_location.id, "location_dest_id": cls.customer_location.id, "scheduled_date": date_move, "move_lines": [ ( 0, 0, { "name": "Test move prod_min", "product_id": cls.prod_min.id, "date": date_move, "product_uom": cls.prod_min.uom_id.id, "product_uom_qty": 16, "location_id": cls.stock_location.id, "location_dest_id": cls.customer_location.id, }, ), ( 0, 0, { "name": "Test move prod_max", "product_id": cls.prod_max.id, "date": date_move, "product_uom": cls.prod_max.uom_id.id, "product_uom_qty": 140, "location_id": cls.stock_location.id, "location_dest_id": cls.customer_location.id, }, ), ( 0, 0, { "name": "Test move prod_multiple", "product_id": cls.prod_multiple.id, "date": date_move, "product_uom": cls.prod_multiple.uom_id.id, "product_uom_qty": 112, "location_id": cls.stock_location.id, "location_dest_id": cls.customer_location.id, }, ), ], } ) cls.picking_2.action_confirm() # Create Test PO: date_po = cls.calendar.plan_days(1 + 1, datetime.today().replace(hour=0)).date() cls.po = cls.po_obj.create( { "name": "Test PO-001", "partner_id": cls.vendor.id, "order_line": [ ( 0, 0, { "name": "Test PP-2 line", "product_id": cls.pp_2.id, "date_planned": date_po, "product_qty": 5.0, "product_uom": cls.pp_2.uom_id.id, "price_unit": 25.0, }, ) ], } ) # Create Test PO for special case Puchase uom: # Remember that prod_uom_test had a UoM of units but it is purchased in dozens. # For this reason buying 1 quantity of it, means to have 12 units in stock. date_po = cls.calendar.plan_days(1 + 1, datetime.today().replace(hour=0)).date() cls.po_uom = cls.po_obj.create( { "name": "Test PO-002", "partner_id": cls.vendor.id, "order_line": [ ( 0, 0, { "name": "Product Uom Test line", "product_id": cls.prod_uom_test.id, "date_planned": date_po, "product_qty": 1.0, "product_uom": cls.prod_uom_test.uom_po_id.id, "price_unit": 25.0, }, ) ], } ) # Create test MO: date_mo = cls.calendar.plan_days(9 + 1, datetime.today().replace(hour=0)).date() bom_fp_2 = cls.env.ref("mrp_multi_level.mrp_bom_fp_2") cls.mo = cls._create_mo(cls.fp_2, bom_fp_2, date_mo, qty=12.0) # Dates: today = datetime.today().replace(hour=0) cls.date_3 = cls.calendar.plan_days(3 + 1, today).date() cls.date_5 = cls.calendar.plan_days(5 + 1, today).date() cls.date_6 = cls.calendar.plan_days(6 + 1, today).date() cls.date_7 = cls.calendar.plan_days(7 + 1, today).date() cls.date_8 = cls.calendar.plan_days(8 + 1, today).date() cls.date_9 = cls.calendar.plan_days(9 + 1, today).date() cls.date_10 = cls.calendar.plan_days(10 + 1, today).date() cls.date_20 = cls.calendar.plan_days(20 + 1, today).date() cls.date_22 = cls.calendar.plan_days(22 + 1, today).date() # Create movements in secondary area: cls.create_demand_sec_loc(cls.date_8, 80.0) cls.create_demand_sec_loc(cls.date_9, 50.0) cls.create_demand_sec_loc(cls.date_10, 70.0) cls.create_demand_sec_loc(cls.date_20, 46.0) cls.create_demand_sec_loc(cls.date_22, 33.0) cls.mrp_multi_level_wiz.create({}).run_mrp_multi_level() @classmethod def create_demand_sec_loc(cls, date_move, qty): return cls.stock_picking_obj.create( { "picking_type_id": cls.env.ref("stock.picking_type_out").id, "location_id": cls.sec_loc.id, "location_dest_id": cls.customer_location.id, "scheduled_date": date_move, "move_lines": [ ( 0, 0, { "name": "Test move", "product_id": cls.prod_test.id, "date": date_move, "product_uom": cls.prod_test.uom_id.id, "product_uom_qty": qty, "location_id": cls.sec_loc.id, "location_dest_id": cls.customer_location.id, }, ) ], } ) @classmethod def _create_user(cls, login, groups, company): user = cls.res_users.create( { "name": login, "login": login, "password": "demo", "email": "[email protected]", "company_id": company.id, "groups_id": [(6, 0, [group.id for group in groups])], } ) return user @classmethod def _create_picking_in(cls, product, qty, date_move, location=None): if not location: location = cls.stock_location picking = cls.stock_picking_obj.create( { "picking_type_id": cls.env.ref("stock.picking_type_in").id, "location_id": cls.supplier_location.id, "location_dest_id": location.id, "scheduled_date": date_move, "move_lines": [ ( 0, 0, { "name": "Test Move", "product_id": product.id, "date": date_move, "product_uom": product.uom_id.id, "product_uom_qty": qty, "location_id": cls.supplier_location.id, "location_dest_id": location.id, }, ) ], } ) picking.action_confirm() return picking @classmethod def _create_picking_out(cls, product, qty, date_move, location=None): if not location: location = cls.stock_location picking = cls.stock_picking_obj.create( { "picking_type_id": cls.env.ref("stock.picking_type_out").id, "location_id": location.id, "location_dest_id": cls.customer_location.id, "scheduled_date": date_move, "move_lines": [ ( 0, 0, { "name": "Test Move", "product_id": product.id, "date": date_move, "product_uom": product.uom_id.id, "product_uom_qty": qty, "location_id": location.id, "location_dest_id": cls.customer_location.id, }, ) ], } ) picking.action_confirm() return picking @classmethod def _create_mo(cls, product, bom, date, qty=10.0): mo_form = Form(cls.mo_obj) mo_form.product_id = product mo_form.bom_id = bom mo_form.product_qty = qty mo_form.date_planned_start = date mo = mo_form.save() # Confirm the MO to generate stock moves: mo.action_confirm() return mo
40.768271
22,871
579
py
PYTHON
15.0
# © 2016 Ucamco - Wim Audenaert <[email protected]> # Copyright 2016-19 ForgeFlow S.L. (https://www.forgeflow.com) # - Jordi Ballester Alomar <[email protected]> # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import fields, models class StockLocation(models.Model): _inherit = "stock.location" mrp_area_id = fields.Many2one( comodel_name="mrp.area", string="MRP Area", help="Requirements for a particular MRP area are combined for the " "purposes of procurement by the MRP.", )
34
578
3,067
py
PYTHON
15.0
# © 2016 Ucamco - Wim Audenaert <[email protected]> # Copyright 2016-19 ForgeFlow S.L. (https://www.forgeflow.com) # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import fields, models class MrpMove(models.Model): _name = "mrp.move" _description = "MRP Move" _order = "product_mrp_area_id, mrp_date, mrp_type desc, id" # TODO: too many indexes... product_mrp_area_id = fields.Many2one( comodel_name="product.mrp.area", string="Product MRP Area", index=True, required=True, ondelete="cascade", ) mrp_area_id = fields.Many2one( comodel_name="mrp.area", related="product_mrp_area_id.mrp_area_id", string="MRP Area", store=True, index=True, ) company_id = fields.Many2one( comodel_name="res.company", related="product_mrp_area_id.mrp_area_id.warehouse_id.company_id", store=True, ) product_id = fields.Many2one( comodel_name="product.product", related="product_mrp_area_id.product_id", store=True, ) current_date = fields.Date() current_qty = fields.Float() mrp_date = fields.Date(string="MRP Date") planned_order_up_ids = fields.Many2many( comodel_name="mrp.planned.order", relation="mrp_move_planned_order_rel", column1="move_down_id", column2="order_id", string="Planned Orders UP", ) mrp_order_number = fields.Char(string="Order Number") mrp_origin = fields.Selection( selection=[ ("mo", "Manufacturing Order"), ("po", "Purchase Order"), ("mv", "Move"), ("fc", "Forecast"), ("mrp", "MRP"), ], string="Origin", ) mrp_qty = fields.Float(string="MRP Quantity") mrp_type = fields.Selection( selection=[("s", "Supply"), ("d", "Demand")], string="Type" ) name = fields.Char(string="Description") origin = fields.Char(string="Source Document") parent_product_id = fields.Many2one( comodel_name="product.product", string="Parent Product", index=True ) production_id = fields.Many2one( comodel_name="mrp.production", string="Manufacturing Order", index=True ) purchase_line_id = fields.Many2one( comodel_name="purchase.order.line", string="Purchase Order Line", index=True ) purchase_order_id = fields.Many2one( comodel_name="purchase.order", string="Purchase Order", index=True ) state = fields.Selection( selection=[ ("draft", "Draft"), ("assigned", "Assigned"), ("confirmed", "Confirmed"), ("waiting", "Waiting"), ("partially_available", "Partially Available"), ("ready", "Ready"), ("sent", "Sent"), ("to approve", "To Approve"), ("approved", "Approved"), ], ) stock_move_id = fields.Many2one( comodel_name="stock.move", string="Stock Move", index=True )
32.617021
3,066
1,555
py
PYTHON
15.0
# © 2016 Ucamco - Wim Audenaert <[email protected]> # Copyright 2016-21 ForgeFlow S.L. (https://www.forgeflow.com) # - Jordi Ballester Alomar <[email protected]> # - Lois Rilo Antelo <[email protected]> # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import api, fields, models class MrpArea(models.Model): _name = "mrp.area" _description = "MRP Area" name = fields.Char(required=True) warehouse_id = fields.Many2one( comodel_name="stock.warehouse", string="Warehouse", required=True ) company_id = fields.Many2one( comodel_name="res.company", related="warehouse_id.company_id", store=True ) location_id = fields.Many2one( comodel_name="stock.location", string="Location", required=True ) active = fields.Boolean(default=True) calendar_id = fields.Many2one( comodel_name="resource.calendar", string="Working Hours", related="warehouse_id.calendar_id", ) @api.model def _datetime_to_date_tz(self, dt_to_convert=None): """Coverts a datetime to date considering the timezone of MRP Area. If no datetime is provided, it returns today's date in the timezone.""" return fields.Date.context_today( self.with_context(tz=self.calendar_id.tz), timestamp=dt_to_convert, ) def _get_locations(self): self.ensure_one() return self.env["stock.location"].search( [("id", "child_of", self.location_id.id)] )
35.318182
1,554
4,837
py
PYTHON
15.0
# © 2016 Ucamco - Wim Audenaert <[email protected]> # Copyright 2016-21 ForgeFlow S.L. (https://www.forgeflow.com) # - Jordi Ballester Alomar <[email protected]> # - Lois Rilo Antelo <[email protected]> # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from datetime import date, timedelta from odoo import _, api, fields, models class MrpInventory(models.Model): _name = "mrp.inventory" _order = "product_mrp_area_id, date" _description = "MRP inventory projections" _rec_name = "product_mrp_area_id" # TODO: name to pass to procurements? # TODO: compute procurement_date to pass to the wizard? not needed for # PO at least. Check for MO and moves mrp_area_id = fields.Many2one( comodel_name="mrp.area", string="MRP Area", related="product_mrp_area_id.mrp_area_id", store=True, ) product_mrp_area_id = fields.Many2one( comodel_name="product.mrp.area", string="Product Parameters", index=True, required=True, ondelete="cascade", ) company_id = fields.Many2one( comodel_name="res.company", related="product_mrp_area_id.mrp_area_id.warehouse_id.company_id", store=True, ) product_id = fields.Many2one( comodel_name="product.product", related="product_mrp_area_id.product_id", store=True, ) uom_id = fields.Many2one( comodel_name="uom.uom", string="Product UoM", compute="_compute_uom_id" ) date = fields.Date() demand_qty = fields.Float(string="Demand") supply_qty = fields.Float(string="Supply") initial_on_hand_qty = fields.Float( string="Starting Inventory", group_operator="avg" ) final_on_hand_qty = fields.Float( string="Forecasted Inventory", group_operator="avg" ) to_procure = fields.Float(compute="_compute_to_procure", store=True) running_availability = fields.Float( string="Planned Availability", group_operator="avg", help="Theoretical inventory level if all planned orders were released.", ) order_release_date = fields.Date(compute="_compute_order_release_date", store=True) planned_order_ids = fields.One2many( comodel_name="mrp.planned.order", inverse_name="mrp_inventory_id", readonly=True ) supply_method = fields.Selection( string="Supply Method", related="product_mrp_area_id.supply_method", readonly=True, store=True, ) main_supplier_id = fields.Many2one( string="Main Supplier", related="product_mrp_area_id.main_supplier_id", readonly=True, store=True, ) mrp_planner_id = fields.Many2one( related="product_mrp_area_id.mrp_planner_id", readonly=True, store=True, ) def _compute_uom_id(self): for rec in self: rec.uom_id = rec.product_mrp_area_id.product_id.uom_id @api.depends("planned_order_ids", "planned_order_ids.qty_released") def _compute_to_procure(self): for rec in self: rec.to_procure = sum(rec.planned_order_ids.mapped("mrp_qty")) - sum( rec.planned_order_ids.mapped("qty_released") ) @api.depends( "product_mrp_area_id", "product_mrp_area_id.main_supplierinfo_id", "product_mrp_area_id.mrp_lead_time", "product_mrp_area_id.mrp_area_id.calendar_id", ) def _compute_order_release_date(self): today = date.today() for rec in self.filtered(lambda r: r.date): delay = rec.product_mrp_area_id.mrp_lead_time if delay and rec.mrp_area_id.calendar_id: dt_date = fields.Datetime.to_datetime(rec.date) # dt_date is at the beginning of the day (00:00), # so we can subtract the delay straight forward. order_release_date = rec.mrp_area_id.calendar_id.plan_days( -delay, dt_date ).date() elif delay: order_release_date = fields.Date.from_string(rec.date) - timedelta( days=delay ) else: order_release_date = rec.date if order_release_date < today: order_release_date = today rec.order_release_date = order_release_date def action_open_planned_orders(self): planned_order_ids = [] for rec in self: planned_order_ids += rec.planned_order_ids.ids domain = [("id", "in", planned_order_ids)] return { "name": _("Planned Orders"), "type": "ir.actions.act_window", "res_model": "mrp.planned.order", "view_mode": "tree,form", "domain": domain, }
35.558824
4,836
1,728
py
PYTHON
15.0
# Copyright 2018-19 ForgeFlow S.L. (https://www.forgeflow.com) # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). import ast from odoo import fields, models class ProductTemplate(models.Model): _inherit = "product.template" mrp_area_ids = fields.One2many( comodel_name="product.mrp.area", inverse_name="product_tmpl_id", string="MRP Area parameters", ) mrp_area_count = fields.Integer( string="MRP Area Parameter Count", readonly=True, compute="_compute_mrp_area_count", ) def _compute_mrp_area_count(self): for rec in self: rec.mrp_area_count = len(rec.mrp_area_ids) def action_view_mrp_area_parameters(self): self.ensure_one() action = self.env.ref("mrp_multi_level.product_mrp_area_action") result = action.read()[0] ctx = ast.literal_eval(result.get("context")) mrp_areas = self.env["mrp.area"].search([]) if "context" not in result: result["context"] = {} if len(mrp_areas) == 1: ctx.update({"default_mrp_area_id": mrp_areas[0].id}) mrp_area_ids = self.with_context(active_test=False).mrp_area_ids.ids if len(self.product_variant_ids) == 1: variant = self.product_variant_ids[0] ctx.update({"default_product_id": variant.id}) if len(mrp_area_ids) != 1: result["domain"] = [("id", "in", mrp_area_ids)] else: res = self.env.ref("mrp_multi_level.product_mrp_area_form", False) result["views"] = [(res and res.id or False, "form")] result["res_id"] = mrp_area_ids[0] result["context"] = ctx return result
36
1,728
2,395
py
PYTHON
15.0
# Copyright 2016 Ucamco - Wim Audenaert <[email protected]> # Copyright 2016-19 ForgeFlow S.L. (https://www.forgeflow.com) # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). import ast from odoo import fields, models class Product(models.Model): _inherit = "product.product" llc = fields.Integer(string="Low Level Code", default=0, index=True) manufacturing_order_ids = fields.One2many( comodel_name="mrp.production", inverse_name="product_id", string="Manufacturing Orders", domain=[("state", "=", "draft")], ) purchase_order_line_ids = fields.One2many( comodel_name="purchase.order.line", inverse_name="product_id", string="Purchase Orders", ) mrp_area_ids = fields.One2many( comodel_name="product.mrp.area", inverse_name="product_id", string="MRP Area parameters", ) mrp_area_count = fields.Integer( string="MRP Area Parameter Count", readonly=True, compute="_compute_mrp_area_count", ) def _compute_mrp_area_count(self): for rec in self: rec.mrp_area_count = len(rec.mrp_area_ids) def write(self, values): res = super().write(values) if values.get("active") is False: parameters = ( self.env["product.mrp.area"] .sudo() .search([("product_id", "in", self.ids)]) ) parameters.write({"active": False}) return res def action_view_mrp_area_parameters(self): self.ensure_one() action = self.env.ref("mrp_multi_level.product_mrp_area_action") result = action.read()[0] ctx = ast.literal_eval(result.get("context")) if not ctx: ctx = {} mrp_areas = self.env["mrp.area"].search([]) if len(mrp_areas) == 1: ctx.update({"default_mrp_area_id": mrp_areas[0].id}) area_ids = self.mrp_area_ids.ids ctx.update({"default_product_id": self.id}) if self.mrp_area_count != 1: result["domain"] = [("id", "in", area_ids)] else: res = self.env.ref("mrp_multi_level.product_mrp_area_form", False) result["views"] = [(res and res.id or False, "form")] result["res_id"] = area_ids[0] result["context"] = ctx return result
34.214286
2,395
11,285
py
PYTHON
15.0
# Copyright 2016 Ucamco - Wim Audenaert <[email protected]> # Copyright 2016-19 ForgeFlow S.L. (https://www.forgeflow.com) # - Jordi Ballester Alomar <[email protected]> # - Lois Rilo Antelo <[email protected]> # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from math import ceil from odoo import _, api, fields, models from odoo.exceptions import ValidationError from odoo.osv import expression class ProductMRPArea(models.Model): _name = "product.mrp.area" _description = "Product MRP Area" active = fields.Boolean(default=True) mrp_area_id = fields.Many2one(comodel_name="mrp.area", required=True) company_id = fields.Many2one( comodel_name="res.company", related="mrp_area_id.warehouse_id.company_id", store=True, ) product_id = fields.Many2one( comodel_name="product.product", required=True, string="Product" ) product_tmpl_id = fields.Many2one( comodel_name="product.template", readonly=True, related="product_id.product_tmpl_id", store=True, ) location_id = fields.Many2one(related="mrp_area_id.location_id") location_proc_id = fields.Many2one( string="Procure Location", comodel_name="stock.location", domain="[('location_id', 'child_of', location_id)]", help="Set this if you need to procure from a different location" "than area's location.", ) # TODO: applicable and exclude... redundant?? mrp_applicable = fields.Boolean(string="MRP Applicable") mrp_exclude = fields.Boolean(string="Exclude from MRP") mrp_inspection_delay = fields.Integer(string="Inspection Delay") mrp_maximum_order_qty = fields.Float(string="Maximum Order Qty", default=0.0) mrp_minimum_order_qty = fields.Float(string="Minimum Order Qty", default=0.0) mrp_minimum_stock = fields.Float(string="Safety Stock") mrp_nbr_days = fields.Integer( string="Nbr. Days", default=0, help="Number of days to group demand for this product during the " "MRP run, in order to determine the quantity to order.", ) mrp_qty_multiple = fields.Float(string="Qty Multiple", default=1.00) mrp_transit_delay = fields.Integer(string="Transit Delay", default=0) mrp_verified = fields.Boolean( string="Verified for MRP", help="Identifies that this product has been verified " "to be valid for the MRP.", ) mrp_lead_time = fields.Float(string="Lead Time", compute="_compute_mrp_lead_time") distribution_lead_time = fields.Float() main_supplier_id = fields.Many2one( comodel_name="res.partner", string="Main Supplier", compute="_compute_main_supplier", store=True, index=True, ) main_supplierinfo_id = fields.Many2one( comodel_name="product.supplierinfo", string="Supplier Info", compute="_compute_main_supplier", store=True, ) supply_method = fields.Selection( selection=[ ("buy", "Buy"), ("none", "Undefined"), ("manufacture", "Produce"), ("phantom", "Kit"), ("pull", "Pull From"), ("push", "Push To"), ("pull_push", "Pull & Push"), ], compute="_compute_supply_method", ) qty_available = fields.Float( string="Quantity Available", compute="_compute_qty_available" ) mrp_move_ids = fields.One2many( comodel_name="mrp.move", inverse_name="product_mrp_area_id", readonly=True ) planned_order_ids = fields.One2many( comodel_name="mrp.planned.order", inverse_name="product_mrp_area_id", readonly=True, ) mrp_planner_id = fields.Many2one("res.users") _sql_constraints = [ ( "product_mrp_area_uniq", "unique(product_id, mrp_area_id)", "The product/MRP Area parameters combination must be unique.", ) ] @api.constrains( "mrp_minimum_order_qty", "mrp_maximum_order_qty", "mrp_qty_multiple", "mrp_minimum_stock", "mrp_nbr_days", ) def _check_negatives(self): values = self.read( [ "mrp_minimum_order_qty", "mrp_maximum_order_qty", "mrp_qty_multiple", "mrp_minimum_stock", "mrp_nbr_days", ] ) for rec in values: if any(v < 0 for v in rec.values()): raise ValidationError(_("You cannot use a negative number.")) def name_get(self): return [ ( area.id, "[{}] {}".format(area.mrp_area_id.name, area.product_id.display_name), ) for area in self ] @api.model def _name_search( self, name, args=None, operator="ilike", limit=100, name_get_uid=None ): if operator in ("ilike", "like", "=", "=like", "=ilike"): args = expression.AND( [ args or [], [ "|", "|", ("product_id.name", operator, name), ("product_id.default_code", operator, name), ("mrp_area_id.name", operator, name), ], ] ) return super(ProductMRPArea, self)._name_search( name, args=args, operator=operator, limit=limit, name_get_uid=name_get_uid ) def _compute_mrp_lead_time(self): produced = self.filtered(lambda r: r.supply_method == "manufacture") purchased = self.filtered(lambda r: r.supply_method == "buy") distributed = self.filtered( lambda r: r.supply_method in ("pull", "push", "pull_push") ) for rec in produced: rec.mrp_lead_time = rec.product_id.produce_delay for rec in purchased: rec.mrp_lead_time = rec.main_supplierinfo_id.delay for rec in distributed: rec.mrp_lead_time = rec.distribution_lead_time for rec in self - produced - purchased - distributed: rec.mrp_lead_time = 0 def _compute_qty_available(self): for rec in self: rec.qty_available = rec.product_id.with_context( location=rec.mrp_area_id.location_id.id ).qty_available def _compute_supply_method(self): group_obj = self.env["procurement.group"] for rec in self: proc_loc = rec.location_proc_id or rec.mrp_area_id.location_id values = { "warehouse_id": rec.mrp_area_id.warehouse_id, "company_id": rec.mrp_area_id.company_id, } rule = group_obj._get_rule(rec.product_id, proc_loc, values) if not rule: rec.supply_method = "none" continue # Keep getting the rule for the product and the source location until the # action is "buy" or "manufacture". Or until the action is "Pull From" or # "Pull & Push" and the supply method is "Take from Stock". while rule.action not in ("buy", "manufacture") and rule.procure_method in ( "make_to_order", "mts_else_mto", ): new_rule = group_obj._get_rule( rec.product_id, rule.location_src_id, values ) if not new_rule: break rule = new_rule # Determine the supply method based on the final rule. boms = rec.product_id.product_tmpl_id.bom_ids.filtered( lambda x: x.type in ["normal", "phantom"] ) rec.supply_method = ( "phantom" if rule.action == "manufacture" and boms and boms[0].type == "phantom" else rule.action ) @api.depends( "mrp_area_id", "supply_method", "product_id.route_ids", "product_id.seller_ids" ) def _compute_main_supplier(self): """Simplified and similar to procurement.rule logic.""" for rec in self.filtered(lambda r: r.supply_method == "buy"): suppliers = rec.product_id.seller_ids.filtered( lambda r: (not r.product_id or r.product_id == rec.product_id) and (not r.company_id or r.company_id == rec.company_id) ) if not suppliers: rec.main_supplierinfo_id = False rec.main_supplier_id = False continue rec.main_supplierinfo_id = suppliers[0] rec.main_supplier_id = suppliers[0].name for rec in self.filtered(lambda r: r.supply_method != "buy"): rec.main_supplierinfo_id = False rec.main_supplier_id = False def _adjust_qty_to_order(self, qty_to_order): self.ensure_one() if ( not self.mrp_maximum_order_qty and not self.mrp_minimum_order_qty and self.mrp_qty_multiple == 1.0 ): return qty_to_order if qty_to_order < self.mrp_minimum_order_qty: return self.mrp_minimum_order_qty if self.mrp_qty_multiple: multiplier = ceil(qty_to_order / self.mrp_qty_multiple) qty_to_order = multiplier * self.mrp_qty_multiple if self.mrp_maximum_order_qty and qty_to_order > self.mrp_maximum_order_qty: return self.mrp_maximum_order_qty return qty_to_order def update_min_qty_from_main_supplier(self): for rec in self.filtered( lambda r: r.main_supplierinfo_id and r.supply_method == "buy" ): rec.mrp_minimum_order_qty = rec.main_supplierinfo_id.min_qty def _in_stock_moves_domain(self): self.ensure_one() locations = self.mrp_area_id._get_locations() return [ ("product_id", "=", self.product_id.id), ("state", "not in", ["done", "cancel"]), ("product_qty", ">", 0.00), ("location_id", "not in", locations.ids), ("location_dest_id", "in", locations.ids), ] def _out_stock_moves_domain(self): self.ensure_one() locations = self.mrp_area_id._get_locations() return [ ("product_id", "=", self.product_id.id), ("state", "not in", ["done", "cancel"]), ("product_qty", ">", 0.00), ("location_id", "in", locations.ids), ("location_dest_id", "not in", locations.ids), ] def action_view_stock_moves(self, domain): self.ensure_one() action = self.env.ref("stock.stock_move_action").read()[0] action["domain"] = domain action["context"] = {} return action def action_view_incoming_stock_moves(self): return self.action_view_stock_moves(self._in_stock_moves_domain()) def action_view_outgoing_stock_moves(self): return self.action_view_stock_moves(self._out_stock_moves_domain()) def _to_be_exploded(self): self.ensure_one() return self.supply_method in ["manufacture", "phantom"]
37.996633
11,285
3,871
py
PYTHON
15.0
# Copyright 2019 ForgeFlow S.L. (https://www.forgeflow.com) # - Lois Rilo Antelo <[email protected]> # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from datetime import timedelta from odoo import api, fields, models class MrpPlannedOrder(models.Model): _name = "mrp.planned.order" _description = "Planned Order" _order = "due_date, id" name = fields.Char(string="Description") origin = fields.Char(string="Source Document") product_mrp_area_id = fields.Many2one( comodel_name="product.mrp.area", string="Product MRP Area", index=True, required=True, ondelete="cascade", ) mrp_area_id = fields.Many2one( comodel_name="mrp.area", related="product_mrp_area_id.mrp_area_id", string="MRP Area", store=True, index=True, readonly=True, ) company_id = fields.Many2one( comodel_name="res.company", related="product_mrp_area_id.mrp_area_id.warehouse_id.company_id", store=True, ) product_id = fields.Many2one( comodel_name="product.product", related="product_mrp_area_id.product_id", store=True, readonly=True, ) order_release_date = fields.Date( string="Release Date", help="Order release date planned by MRP.", required=True ) due_date = fields.Date( help="Date in which the supply must have been completed.", required=True, ) qty_released = fields.Float(readonly=True) fixed = fields.Boolean(default=True) mrp_qty = fields.Float(string="Quantity") mrp_move_down_ids = fields.Many2many( comodel_name="mrp.move", relation="mrp_move_planned_order_rel", column1="order_id", column2="move_down_id", string="MRP Move DOWN", ) mrp_action = fields.Selection( selection=[ ("manufacture", "Manufacturing Order"), ("buy", "Purchase Order"), ("pull", "Pull From"), ("push", "Push To"), ("pull_push", "Pull & Push"), ("none", "None"), ], string="Action", ) mrp_inventory_id = fields.Many2one( string="Associated MRP Inventory", comodel_name="mrp.inventory", ondelete="set null", ) mrp_production_ids = fields.One2many( "mrp.production", "planned_order_id", string="Manufacturing Orders" ) mo_count = fields.Integer(compute="_compute_mrp_production_count") mrp_planner_id = fields.Many2one( related="product_mrp_area_id.mrp_planner_id", readonly=True, store=True, ) def _compute_mrp_production_count(self): for rec in self: rec.mo_count = len(rec.mrp_production_ids) @api.onchange("due_date") def _onchange_due_date(self): if self.due_date: if self.product_mrp_area_id.mrp_lead_time: calendar = self.mrp_area_id.calendar_id if calendar: dt = fields.Datetime.from_string(self.due_date) res = calendar.plan_days( -1 * (self.product_mrp_area_id.mrp_lead_time + 1), dt ) self.order_release_date = res.date() else: self.order_release_date = fields.Date.from_string( self.due_date ) - timedelta(days=self.product_mrp_area_id.mrp_lead_time) def action_toggle_fixed(self): for rec in self: rec.fixed = not rec.fixed def action_open_linked_mrp_production(self): action = self.env.ref("mrp.mrp_production_action") result = action.read()[0] result["context"] = {} result["domain"] = "[('id','in',%s)]" % self.mrp_production_ids.ids return result
33.95614
3,871
855
py
PYTHON
15.0
# Copyright 2020 ForgeFlow S.L. (https://www.forgeflow.com) # - Héctor Villarreal <[email protected]> # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import models class StockRule(models.Model): _inherit = "stock.rule" def _prepare_mo_vals( self, product_id, product_qty, product_uom, location_id, name, origin, company_id, values, bom, ): res = super()._prepare_mo_vals( product_id, product_qty, product_uom, location_id, name, origin, company_id, values, bom, ) if "planned_order_id" in values: res["planned_order_id"] = values["planned_order_id"] return res
24.4
854
394
py
PYTHON
15.0
# Copyright 2020 ForgeFlow S.L. (https://www.forgeflow.com) # - Héctor Villarreal <[email protected]> # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import fields, models class MrpProduction(models.Model): """Manufacturing Orders""" _inherit = "mrp.production" planned_order_id = fields.Many2one(comodel_name="mrp.planned.order")
32.75
393
5,908
py
PYTHON
15.0
# Copyright 2018-21 ForgeFlow S.L. (https://www.forgeflow.com) # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import _, api, fields, models from odoo.exceptions import UserError, ValidationError class MrpInventoryProcure(models.TransientModel): _name = "mrp.inventory.procure" _description = "Make Procurements from MRP inventory projections" item_ids = fields.One2many( comodel_name="mrp.inventory.procure.item", inverse_name="wiz_id", string="Items" ) @api.model def _prepare_item(self, planned_order): return { "planned_order_id": planned_order.id, "qty": planned_order.mrp_qty - planned_order.qty_released, "uom_id": planned_order.mrp_inventory_id.uom_id.id, "date_planned": planned_order.due_date, "mrp_inventory_id": planned_order.mrp_inventory_id.id, "product_id": planned_order.product_id.id, "warehouse_id": planned_order.mrp_area_id.warehouse_id.id, "location_id": planned_order.product_mrp_area_id.location_proc_id.id or planned_order.mrp_area_id.location_id.id, "supply_method": planned_order.product_mrp_area_id.supply_method, } @api.model def fields_view_get( self, view_id=None, view_type="form", toolbar=False, submenu=False ): if self.user_has_groups("mrp_multi_level.group_change_mrp_procure_qty"): view_id = self.env.ref( "mrp_multi_level.view_mrp_inventory_procure_wizard" ).id else: view_id = self.env.ref( "mrp_multi_level.view_mrp_inventory_procure_without_security" ).id return super(MrpInventoryProcure, self).fields_view_get( view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=submenu ) @api.model def default_get(self, fields): res = super(MrpInventoryProcure, self).default_get(fields) active_ids = self.env.context["active_ids"] or [] active_model = self.env.context["active_model"] if not active_ids or "item_ids" not in fields: return res items = item_obj = self.env["mrp.inventory.procure.item"] if active_model == "mrp.inventory": mrp_inventory_obj = self.env[active_model] for line in mrp_inventory_obj.browse(active_ids).mapped( "planned_order_ids" ): if line.qty_released < line.mrp_qty: items += item_obj.create(self._prepare_item(line)) elif active_model == "mrp.planned.order": mrp_planned_order_obj = self.env[active_model] for line in mrp_planned_order_obj.browse(active_ids): if line.qty_released < line.mrp_qty: items += item_obj.create(self._prepare_item(line)) if items: res["item_ids"] = [(6, 0, items.ids)] return res def make_procurement(self): self.ensure_one() errors = [] pg = self.env["procurement.group"] procurements = [] for item in self.item_ids: if not item.qty: raise ValidationError(_("Quantity must be positive.")) values = item._prepare_procurement_values() procurements.append( pg.Procurement( item.product_id, item.qty, item.uom_id, item.location_id, "MRP: " + (item.planned_order_id.name or self.env.user.login), "MRP: " + (item.planned_order_id.origin or self.env.user.login), item.mrp_inventory_id.company_id, values, ) ) # Run procurements try: pg.run(procurements) for item in self.item_ids: item.planned_order_id.qty_released += item.qty except UserError as error: errors.append(error.name) if errors: raise UserError("\n".join(errors)) return {"type": "ir.actions.act_window_close"} class MrpInventoryProcureItem(models.TransientModel): _name = "mrp.inventory.procure.item" _description = "MRP Inventory procure item" wiz_id = fields.Many2one( comodel_name="mrp.inventory.procure", string="Wizard", ondelete="cascade", readonly=True, ) qty = fields.Float(string="Quantity") uom_id = fields.Many2one(string="Unit of Measure", comodel_name="uom.uom") date_planned = fields.Date(string="Planned Date", required=True) mrp_inventory_id = fields.Many2one( string="Mrp Inventory", comodel_name="mrp.inventory" ) planned_order_id = fields.Many2one(comodel_name="mrp.planned.order") product_id = fields.Many2one(string="Product", comodel_name="product.product") warehouse_id = fields.Many2one(string="Warehouse", comodel_name="stock.warehouse") location_id = fields.Many2one(string="Location", comodel_name="stock.location") supply_method = fields.Selection( selection=[ ("buy", "Buy"), ("none", "Undefined"), ("manufacture", "Produce"), ("pull", "Pull From"), ("push", "Push To"), ("pull_push", "Pull & Push"), ], readonly=True, ) def _prepare_procurement_values(self, group=False): return { "date_planned": self.date_planned, "warehouse_id": self.warehouse_id, "group_id": group, "planned_order_id": self.planned_order_id.id, } @api.onchange("uom_id") def onchange_uom_id(self): for rec in self: rec.qty = rec.mrp_inventory_id.uom_id._compute_quantity( rec.mrp_inventory_id.to_procure, rec.uom_id )
39.651007
5,908
33,279
py
PYTHON
15.0
# Copyright 2016 Ucamco - Wim Audenaert <[email protected]> # Copyright 2016-19 ForgeFlow S.L. (https://www.forgeflow.com) # - Jordi Ballester Alomar <[email protected]> # - Lois Rilo <[email protected]> # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). import logging from datetime import date, timedelta from odoo import _, api, exceptions, fields, models from odoo.tools import float_is_zero logger = logging.getLogger(__name__) class MultiLevelMrp(models.TransientModel): _name = "mrp.multi.level" _description = "Multi Level MRP" mrp_area_ids = fields.Many2many( comodel_name="mrp.area", string="MRP Areas to run", help="If empty, all areas will be computed.", ) @api.model def _prepare_product_mrp_area_data(self, product_mrp_area): qty_available = 0.0 product_obj = self.env["product.product"] location_ids = product_mrp_area.mrp_area_id._get_locations() for location in location_ids: product_l = product_obj.with_context(location=location.id).browse( product_mrp_area.product_id.id ) qty_available += product_l.qty_available return { "product_mrp_area_id": product_mrp_area.id, "mrp_qty_available": qty_available, "mrp_llc": product_mrp_area.product_id.llc, } @api.model def _prepare_mrp_move_data_from_stock_move( self, product_mrp_area, move, direction="in" ): area = product_mrp_area.mrp_area_id if direction == "out": mrp_type = "d" product_qty = -move.product_qty else: mrp_type = "s" product_qty = move.product_qty po = po_line = None mo = origin = order_number = order_origin = parent_product_id = None if move.purchase_line_id: po = move.purchase_line_id.order_id order_number = po.name order_origin = po.origin origin = "po" po = move.purchase_line_id.order_id.id po_line = move.purchase_line_id.id elif move.production_id or move.raw_material_production_id: production = move.production_id or move.raw_material_production_id order_number = production.name order_origin = production.origin origin = "mo" mo = production.id elif move.move_dest_ids: for move_dest_id in move.move_dest_ids.filtered("production_id"): production = move_dest_id.production_id order_number = production.name order_origin = production.origin origin = "mo" mo = move_dest_id.production_id.id parent_product_id = ( move_dest_id.production_id.product_id or move_dest_id.product_id ).id if not order_number: source = (move.picking_id or move).origin order_number = source or (move.picking_id or move).name origin = "mv" # The date to display is based on the timezone of the warehouse. today_tz = area._datetime_to_date_tz() move_date_tz = area._datetime_to_date_tz(move.date) if move_date_tz > today_tz: mrp_date = move_date_tz else: mrp_date = today_tz return { "product_id": move.product_id.id, "product_mrp_area_id": product_mrp_area.id, "production_id": mo, "purchase_order_id": po, "purchase_line_id": po_line, "stock_move_id": move.id, "mrp_qty": product_qty, "current_qty": product_qty, "mrp_date": mrp_date, "current_date": move.date, "mrp_type": mrp_type, "mrp_origin": origin or "", "mrp_order_number": order_number, "parent_product_id": parent_product_id, "name": order_number, "origin": order_origin, "state": move.state, } @api.model def _prepare_planned_order_data( self, product_mrp_area, qty, mrp_date_supply, mrp_action_date, name, values ): return { "product_mrp_area_id": product_mrp_area.id, "mrp_qty": qty, "due_date": mrp_date_supply, "order_release_date": mrp_action_date, "mrp_action": product_mrp_area.supply_method, "qty_released": 0.0, "name": "Planned supply for: " + name, "origin": values.get("origin") or name, "fixed": False, } @api.model def _prepare_mrp_move_data_bom_explosion( self, product, bomline, qty, mrp_date_demand_2, bom, name, planned_order, values=None, ): product_mrp_area = self._get_product_mrp_area_from_product_and_area( bomline.product_id, product.mrp_area_id ) if not product_mrp_area: raise exceptions.Warning(_("No MRP product found")) factor = ( product.product_id.uom_id._compute_quantity( qty, bomline.bom_id.product_uom_id ) / bomline.bom_id.product_qty ) line_quantity = factor * bomline.product_qty return { "mrp_area_id": product.mrp_area_id.id, "product_id": bomline.product_id.id, "product_mrp_area_id": product_mrp_area.id, "production_id": None, "purchase_order_id": None, "purchase_line_id": None, "stock_move_id": None, "mrp_qty": -line_quantity, # TODO: review with UoM "current_qty": None, "mrp_date": mrp_date_demand_2, "current_date": None, "mrp_type": "d", "mrp_origin": "mrp", "mrp_order_number": None, "parent_product_id": bom.product_id.id, "name": ( "Demand Bom Explosion: %s" % (name or product.product_id.default_code or product.product_id.name) ).replace( "Demand Bom Explosion: Demand Bom Explosion: ", "Demand Bom Explosion: " ), "origin": planned_order.origin if planned_order else values.get("origin"), } @api.model def _get_action_and_supply_dates(self, product_mrp_area, mrp_date): if not isinstance(mrp_date, date): mrp_date = fields.Date.from_string(mrp_date) if mrp_date < date.today(): mrp_date_supply = date.today() else: mrp_date_supply = mrp_date calendar = product_mrp_area.mrp_area_id.calendar_id if calendar and product_mrp_area.mrp_lead_time: date_str = fields.Date.to_string(mrp_date) dt = fields.Datetime.from_string(date_str) # dt is at the beginning of the day (00:00) res = calendar.plan_days(-1 * product_mrp_area.mrp_lead_time, dt) mrp_action_date = res.date() else: mrp_action_date = mrp_date - timedelta(days=product_mrp_area.mrp_lead_time) return mrp_action_date, mrp_date_supply @api.model def _get_bom_to_explode(self, product_mrp_area_id): boms = self.env["mrp.bom"] if product_mrp_area_id.supply_method in ["manufacture", "phantom"]: boms = product_mrp_area_id.product_id.bom_ids.filtered( lambda x: x.type in ["normal", "phantom"] ) if not boms: return False return boms[0] @api.model def explode_action( self, product_mrp_area_id, mrp_action_date, name, qty, action, values=None ): """Explode requirements.""" mrp_date_demand = mrp_action_date if mrp_date_demand < date.today(): mrp_date_demand = date.today() bom = self._get_bom_to_explode(product_mrp_area_id) if not bom: return False pd = self.env["decimal.precision"].precision_get("Product Unit of Measure") for bomline in bom.bom_line_ids: if ( float_is_zero(bomline.product_qty, precision_digits=pd) or bomline.product_id.type != "product" ): continue if self.with_context(mrp_explosion=True)._exclude_from_mrp( bomline.product_id, product_mrp_area_id.mrp_area_id ): # Stop explosion. continue if bomline._skip_bom_line(product_mrp_area_id.product_id): continue # TODO: review: mrp_transit_delay, mrp_inspection_delay mrp_date_demand_2 = mrp_date_demand - timedelta( days=( product_mrp_area_id.mrp_transit_delay + product_mrp_area_id.mrp_inspection_delay ) ) move_data = self._prepare_mrp_move_data_bom_explosion( product_mrp_area_id, bomline, qty, mrp_date_demand_2, bom, name, action, values, ) mrpmove_id2 = self.env["mrp.move"].create(move_data) if hasattr(action, "mrp_move_down_ids"): action.mrp_move_down_ids = [(4, mrpmove_id2.id)] return True @api.model def create_action(self, product_mrp_area_id, mrp_date, mrp_qty, name, values=None): if not values: values = {} if not isinstance(mrp_date, date): mrp_date = fields.Date.from_string(mrp_date) action_date, date_supply = self._get_action_and_supply_dates( product_mrp_area_id, mrp_date ) return self.create_planned_order( product_mrp_area_id, mrp_qty, name, date_supply, action_date, values=values ) @api.model def create_planned_order( self, product_mrp_area_id, mrp_qty, name, mrp_date_supply, mrp_action_date, values=None, ): self = self.with_context(auditlog_disabled=True) if self._exclude_from_mrp( product_mrp_area_id.product_id, product_mrp_area_id.mrp_area_id ): values["qty_ordered"] = 0.0 return values qty_ordered = values.get("qty_ordered", 0.0) if values else 0.0 qty_to_order = mrp_qty while qty_ordered < mrp_qty: qty = product_mrp_area_id._adjust_qty_to_order(qty_to_order) qty_to_order -= qty order_data = self._prepare_planned_order_data( product_mrp_area_id, qty, mrp_date_supply, mrp_action_date, name, values ) # Do not create planned order for products that are Kits planned_order = False if not product_mrp_area_id.supply_method == "phantom": planned_order = self.env["mrp.planned.order"].create(order_data) qty_ordered = qty_ordered + qty if product_mrp_area_id._to_be_exploded(): self.explode_action( product_mrp_area_id, mrp_action_date, name, qty, planned_order, values, ) values["qty_ordered"] = qty_ordered log_msg = "[{}] {}: qty_ordered = {}".format( product_mrp_area_id.mrp_area_id.name, product_mrp_area_id.product_id.default_code or product_mrp_area_id.product_id.name, qty_ordered, ) logger.debug(log_msg) return values @api.model def _mrp_cleanup(self, mrp_areas): logger.info("Start MRP Cleanup") domain = [] if mrp_areas: domain += [("mrp_area_id", "in", mrp_areas.ids)] self.env["mrp.move"].search(domain).unlink() self.env["mrp.inventory"].search(domain).unlink() domain += [("fixed", "=", False)] self.env["mrp.planned.order"].search(domain).unlink() logger.info("End MRP Cleanup") return True def _domain_bom_lines_by_llc(self, llc, product_templates): return [ ("product_id.llc", "=", llc), ("bom_id.product_tmpl_id", "in", product_templates.ids), ("bom_id.active", "=", True), ] def _get_bom_lines_by_llc(self, llc, product_templates): return self.env["mrp.bom.line"].search( self._domain_bom_lines_by_llc(llc, product_templates) ) @api.model def _low_level_code_calculation(self): logger.info("Start low level code calculation") counter = 999999 llc = 0 llc_recursion_limit = ( int( self.env["ir.config_parameter"] .sudo() .get_param("mrp_multi_level.llc_calculation_recursion_limit") ) or 1000 ) self.env["product.product"].search([]).write({"llc": llc}) products = self.env["product.product"].search([("llc", "=", llc)]) if products: counter = len(products) log_msg = "Low level code 0 finished - Nbr. products: %s" % counter logger.info(log_msg) while counter: llc += 1 products = self.env["product.product"].search([("llc", "=", llc - 1)]) p_templates = products.mapped("product_tmpl_id") bom_lines = self._get_bom_lines_by_llc(llc - 1, p_templates) products = bom_lines.mapped("product_id") products.write({"llc": llc}) counter = self.env["product.product"].search_count([("llc", "=", llc)]) log_msg = "Low level code {} finished - Nbr. products: {}".format( llc, counter ) logger.info(log_msg) if llc > llc_recursion_limit: logger.error("Recursion limit reached during LLC calculation.") break mrp_lowest_llc = llc logger.info("End low level code calculation") return mrp_lowest_llc @api.model def _adjust_mrp_applicable(self, mrp_areas): """This method is meant to modify the products that are applicable to MRP Multi level calculation """ return True @api.model def _calculate_mrp_applicable(self, mrp_areas): logger.info("Start Calculate MRP Applicable") domain = [] if mrp_areas: domain += [("mrp_area_id", "in", mrp_areas.ids)] self.env["product.mrp.area"].search(domain).write({"mrp_applicable": False}) domain += [("product_id.type", "=", "product")] self.env["product.mrp.area"].search(domain).write({"mrp_applicable": True}) self._adjust_mrp_applicable(mrp_areas) count_domain = [("mrp_applicable", "=", True)] if mrp_areas: count_domain += [("mrp_area_id", "in", mrp_areas.ids)] counter = self.env["product.mrp.area"].search(count_domain, count=True) log_msg = "End Calculate MRP Applicable: %s" % counter logger.info(log_msg) return True @api.model def _init_mrp_move_from_forecast(self, product_mrp_area): """This method is meant to be inherited to add a forecast mechanism.""" return True @api.model def _init_mrp_move_from_stock_move(self, product_mrp_area): move_obj = self.env["stock.move"] mrp_move_obj = self.env["mrp.move"] in_domain = product_mrp_area._in_stock_moves_domain() in_moves = move_obj.search(in_domain) out_domain = product_mrp_area._out_stock_moves_domain() out_moves = move_obj.search(out_domain) move_vals = [] if in_moves: for move in in_moves: move_data = self._prepare_mrp_move_data_from_stock_move( product_mrp_area, move, direction="in" ) if move_data: move_vals.append(move_data) if out_moves: for move in out_moves: move_data = self._prepare_mrp_move_data_from_stock_move( product_mrp_area, move, direction="out" ) if move_data: move_vals.append(move_data) mrp_move_obj.create(move_vals) return True @api.model def _prepare_mrp_move_data_from_purchase_order(self, poline, product_mrp_area): mrp_date = date.today() if fields.Date.from_string(poline.date_planned) > date.today(): mrp_date = fields.Date.from_string(poline.date_planned) return { "product_id": poline.product_id.id, "product_mrp_area_id": product_mrp_area.id, "production_id": None, "purchase_order_id": poline.order_id.id, "purchase_line_id": poline.id, "stock_move_id": None, "mrp_qty": poline.product_uom_qty, "current_qty": poline.product_uom_qty, "mrp_date": mrp_date, "current_date": poline.date_planned, "mrp_type": "s", "mrp_origin": "po", "mrp_order_number": poline.order_id.name, "parent_product_id": None, "name": poline.order_id.name, "state": poline.order_id.state, } @api.model def _init_mrp_move_from_purchase_order(self, product_mrp_area): location_ids = product_mrp_area.mrp_area_id._get_locations() picking_types = self.env["stock.picking.type"].search( [("default_location_dest_id", "in", location_ids.ids)] ) picking_type_ids = [ptype.id for ptype in picking_types] orders = self.env["purchase.order"].search( [ ("picking_type_id", "in", picking_type_ids), ("state", "in", ["draft", "sent", "to approve"]), ] ) po_lines = self.env["purchase.order.line"].search( [ ("order_id", "in", orders.ids), ("product_qty", ">", 0.0), ("product_id", "=", product_mrp_area.product_id.id), ] ) mrp_move_vals = [] for line in po_lines: mrp_move_data = self._prepare_mrp_move_data_from_purchase_order( line, product_mrp_area ) mrp_move_vals.append(mrp_move_data) if mrp_move_vals: self.env["mrp.move"].create(mrp_move_vals) @api.model def _get_product_mrp_area_from_product_and_area(self, product, mrp_area): return self.env["product.mrp.area"].search( [("product_id", "=", product.id), ("mrp_area_id", "=", mrp_area.id)], limit=1, ) @api.model def _init_mrp_move(self, product_mrp_area): self._init_mrp_move_from_forecast(product_mrp_area) self._init_mrp_move_from_stock_move(product_mrp_area) self._init_mrp_move_from_purchase_order(product_mrp_area) @api.model def _exclude_from_mrp(self, product, mrp_area): """To extend with various logic where needed.""" product_mrp_area = self.env["product.mrp.area"].search( [("product_id", "=", product.id), ("mrp_area_id", "=", mrp_area.id)], limit=1, ) if not product_mrp_area: return True return product_mrp_area.mrp_exclude @api.model def _mrp_initialisation(self, mrp_areas): logger.info("Start MRP initialisation") if not mrp_areas: mrp_areas = self.env["mrp.area"].search([]) product_mrp_areas = self.env["product.mrp.area"].search( [("mrp_area_id", "in", mrp_areas.ids), ("mrp_applicable", "=", True)] ) init_counter = 0 for mrp_area in mrp_areas: for product_mrp_area in product_mrp_areas.filtered( lambda a: a.mrp_area_id == mrp_area ): if self._exclude_from_mrp(product_mrp_area.product_id, mrp_area): continue init_counter += 1 log_msg = "MRP Init: {} - {} ".format( init_counter, product_mrp_area.display_name ) logger.info(log_msg) self._init_mrp_move(product_mrp_area) logger.info("End MRP initialisation") @api.model def _init_mrp_move_grouped_demand(self, nbr_create, product_mrp_area): last_date = None last_qty = 0.00 onhand = product_mrp_area.qty_available grouping_delta = product_mrp_area.mrp_nbr_days demand_origin = [] for move in product_mrp_area.mrp_move_ids: if self._exclude_move(move): continue if ( last_date and ( fields.Date.from_string(move.mrp_date) >= last_date + timedelta(days=grouping_delta) ) and ( (onhand + last_qty + move.mrp_qty) < product_mrp_area.mrp_minimum_stock or (onhand + last_qty) < product_mrp_area.mrp_minimum_stock ) ): name = _( "Grouped Demand of %(product_name)s for %(delta_days)d Days" ) % dict( product_name=product_mrp_area.product_id.display_name, delta_days=grouping_delta, ) origin = ",".join(list({x for x in demand_origin if x})) qtytoorder = product_mrp_area.mrp_minimum_stock - onhand - last_qty cm = self.create_action( product_mrp_area_id=product_mrp_area, mrp_date=last_date, mrp_qty=qtytoorder, name=name, values=dict(origin=origin), ) qty_ordered = cm.get("qty_ordered", 0.0) onhand = onhand + last_qty + qty_ordered last_date = None last_qty = 0.00 nbr_create += 1 demand_origin = [] if ( onhand + last_qty + move.mrp_qty ) < product_mrp_area.mrp_minimum_stock or ( onhand + last_qty ) < product_mrp_area.mrp_minimum_stock: if not last_date or last_qty == 0.0: last_date = fields.Date.from_string(move.mrp_date) last_qty = move.mrp_qty else: last_qty += move.mrp_qty else: last_date = fields.Date.from_string(move.mrp_date) onhand += move.mrp_qty if move.mrp_type == "d": demand_origin.append(move.origin or move.name) if last_date and last_qty != 0.00: name = _( "Grouped Demand of %(product_name)s for %(delta_days)d Days" ) % dict( product_name=product_mrp_area.product_id.display_name, delta_days=grouping_delta, ) origin = ",".join(list({x for x in demand_origin if x})) qtytoorder = product_mrp_area.mrp_minimum_stock - onhand - last_qty cm = self.create_action( product_mrp_area_id=product_mrp_area, mrp_date=last_date, mrp_qty=qtytoorder, name=name, values=dict(origin=origin), ) qty_ordered = cm.get("qty_ordered", 0.0) onhand += qty_ordered nbr_create += 1 return nbr_create @api.model def _exclude_move(self, move): """Improve extensibility being able to exclude special moves.""" return False @api.model def _mrp_calculation(self, mrp_lowest_llc, mrp_areas): logger.info("Start MRP calculation") product_mrp_area_obj = self.env["product.mrp.area"] counter = 0 if not mrp_areas: mrp_areas = self.env["mrp.area"].search([]) for mrp_area in mrp_areas: llc = 0 while mrp_lowest_llc > llc: product_mrp_areas = product_mrp_area_obj.search( [("product_id.llc", "=", llc), ("mrp_area_id", "=", mrp_area.id)] ) llc += 1 for product_mrp_area in product_mrp_areas: nbr_create = 0 onhand = product_mrp_area.qty_available if product_mrp_area.mrp_nbr_days == 0: for move in product_mrp_area.mrp_move_ids: if self._exclude_move(move): continue qtytoorder = ( product_mrp_area.mrp_minimum_stock - onhand - move.mrp_qty ) if qtytoorder > 0.0: cm = self.create_action( product_mrp_area_id=product_mrp_area, mrp_date=move.mrp_date, mrp_qty=qtytoorder, name=move.name or "", values=dict(origin=move.origin or ""), ) qty_ordered = cm["qty_ordered"] onhand += move.mrp_qty + qty_ordered nbr_create += 1 else: onhand += move.mrp_qty else: nbr_create = self._init_mrp_move_grouped_demand( nbr_create, product_mrp_area ) if onhand < product_mrp_area.mrp_minimum_stock and nbr_create == 0: qtytoorder = product_mrp_area.mrp_minimum_stock - onhand name = _("Safety Stock") cm = self.create_action( product_mrp_area_id=product_mrp_area, mrp_date=date.today(), mrp_qty=qtytoorder, name=name, values=dict(origin=name), ) qty_ordered = cm["qty_ordered"] onhand += qty_ordered counter += 1 log_msg = "MRP Calculation LLC {} Finished - Nbr. products: {}".format( llc - 1, counter ) logger.info(log_msg) logger.info("Enb MRP calculation") @api.model def _get_demand_groups(self, product_mrp_area): query = """ SELECT mrp_date, sum(mrp_qty) FROM mrp_move WHERE product_mrp_area_id = %(mrp_product)s AND mrp_type = 'd' GROUP BY mrp_date """ params = {"mrp_product": product_mrp_area.id} return query, params @api.model def _get_supply_groups(self, product_mrp_area): query = """ SELECT mrp_date, sum(mrp_qty) FROM mrp_move WHERE product_mrp_area_id = %(mrp_product)s AND mrp_type = 's' GROUP BY mrp_date """ params = {"mrp_product": product_mrp_area.id} return query, params @api.model def _get_planned_order_groups(self, product_mrp_area): query = """ SELECT due_date, sum(mrp_qty) FROM mrp_planned_order WHERE product_mrp_area_id = %(mrp_product)s GROUP BY due_date """ params = {"mrp_product": product_mrp_area.id} return query, params @api.model def _prepare_mrp_inventory_data( self, product_mrp_area, mdt, on_hand_qty, running_availability, demand_qty_by_date, supply_qty_by_date, planned_qty_by_date, ): """Return dict to create mrp.inventory records on MRP Multi Level Scheduler""" mrp_inventory_data = {"product_mrp_area_id": product_mrp_area.id, "date": mdt} demand_qty = demand_qty_by_date.get(mdt, 0.0) mrp_inventory_data["demand_qty"] = abs(demand_qty) supply_qty = supply_qty_by_date.get(mdt, 0.0) mrp_inventory_data["supply_qty"] = abs(supply_qty) mrp_inventory_data["initial_on_hand_qty"] = on_hand_qty on_hand_qty += supply_qty + demand_qty mrp_inventory_data["final_on_hand_qty"] = on_hand_qty # Consider that MRP plan is followed exactly: running_availability += ( supply_qty + demand_qty + planned_qty_by_date.get(mdt, 0.0) ) mrp_inventory_data["running_availability"] = running_availability return mrp_inventory_data, running_availability, on_hand_qty @api.model def _init_mrp_inventory(self, product_mrp_area): mrp_move_obj = self.env["mrp.move"] planned_order_obj = self.env["mrp.planned.order"] # Read Demand demand_qty_by_date = {} query, params = self._get_demand_groups(product_mrp_area) self.env.cr.execute(query, params) for mrp_date, qty in self.env.cr.fetchall(): demand_qty_by_date[mrp_date] = qty # Read Supply supply_qty_by_date = {} query, params = self._get_supply_groups(product_mrp_area) self.env.cr.execute(query, params) for mrp_date, qty in self.env.cr.fetchall(): supply_qty_by_date[mrp_date] = qty # Read planned orders: planned_qty_by_date = {} query, params = self._get_planned_order_groups(product_mrp_area) self.env.cr.execute(query, params) for mrp_date, qty in self.env.cr.fetchall(): planned_qty_by_date[mrp_date] = qty # Dates moves_dates = mrp_move_obj.search( [("product_mrp_area_id", "=", product_mrp_area.id)], order="mrp_date" ).mapped("mrp_date") action_dates = planned_order_obj.search( [("product_mrp_area_id", "=", product_mrp_area.id)], order="due_date" ).mapped("due_date") mrp_dates = set(moves_dates + action_dates) on_hand_qty = product_mrp_area.product_id.with_context( location=product_mrp_area.mrp_area_id.location_id.id )._compute_quantities_dict(False, False, False)[product_mrp_area.product_id.id][ "qty_available" ] running_availability = on_hand_qty mrp_inventory_vals = [] for mdt in sorted(mrp_dates): ( mrp_inventory_data, running_availability, on_hand_qty, ) = self._prepare_mrp_inventory_data( product_mrp_area, mdt, on_hand_qty, running_availability, demand_qty_by_date, supply_qty_by_date, planned_qty_by_date, ) mrp_inventory_vals.append(mrp_inventory_data) if mrp_inventory_vals: mrp_invs = self.env["mrp.inventory"].create(mrp_inventory_vals) planned_orders = planned_order_obj.search( [("product_mrp_area_id", "=", product_mrp_area.id)] ) # attach planned orders to inventory for po in planned_orders: invs = mrp_invs.filtered(lambda i: i.date == po.due_date) if invs: po.mrp_inventory_id = invs[0] @api.model def _mrp_final_process(self, mrp_areas): logger.info("Start MRP final process") domain = [("product_id.llc", "<", 9999)] if mrp_areas: domain += [("mrp_area_id", "in", mrp_areas.ids)] product_mrp_area_ids = self.env["product.mrp.area"].search(domain) for product_mrp_area in product_mrp_area_ids: # Build the time-phased inventory if ( self._exclude_from_mrp( product_mrp_area.product_id, product_mrp_area.mrp_area_id ) or product_mrp_area.supply_method == "phantom" ): continue self._init_mrp_inventory(product_mrp_area) logger.info("End MRP final process") def run_mrp_multi_level(self): self._mrp_cleanup(self.mrp_area_ids) mrp_lowest_llc = self._low_level_code_calculation() self._calculate_mrp_applicable(self.mrp_area_ids) self._mrp_initialisation(self.mrp_area_ids) self._mrp_calculation(mrp_lowest_llc, self.mrp_area_ids) self._mrp_final_process(self.mrp_area_ids) # Open MRP inventory screen to show result if manually run: # Done as sudo to allow non-admin users to read the action. action = self.env.ref("mrp_multi_level.mrp_inventory_action") result = action.sudo().read()[0] return result
39.290437
33,279
737
py
PYTHON
15.0
# Copyright 2023 Camptocamp SA (https://www.camptocamp.com). # @author Iván Todorovich <[email protected]> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "MRP Production Split", "summary": "Split Manufacturing Orders into smaller ones", "version": "15.0.1.0.0", "author": "Camptocamp, Odoo Community Association (OCA)", "maintainers": ["ivantodorovich"], "website": "https://github.com/OCA/manufacture", "license": "AGPL-3", "category": "Manufacturing", "depends": ["mrp"], "data": [ "security/ir.model.access.csv", "templates/messages.xml", "views/mrp_production.xml", "wizards/mrp_production_split_wizard.xml", ], }
35.047619
736
6,250
py
PYTHON
15.0
# Copyright 2023 Camptocamp SA (https://www.camptocamp.com). # @author Iván Todorovich <[email protected]> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from datetime import datetime, timedelta from odoo.exceptions import UserError from .common import CommonCase class TestMrpProductionSplit(CommonCase): def test_mrp_production_split_draft(self): with self.assertRaisesRegex(UserError, r"Cannot split.*"): self._mrp_production_split(self.production) def test_mrp_production_split_done(self): self.production.action_confirm() self.production.action_generate_serial() self._mrp_production_set_quantity_done(self.production) self.production.button_mark_done() with self.assertRaisesRegex(UserError, r"Cannot split.*"): self._mrp_production_split(self.production) def test_mrp_production_split_cancel(self): self.production.action_cancel() with self.assertRaisesRegex(UserError, r"Cannot split.*"): self._mrp_production_split(self.production) def test_mrp_production_split_lot_simple(self): self.production.action_confirm() self.production.action_generate_serial() mos = self._mrp_production_split(self.production, split_qty=2.0) self.assertRecordValues(mos, [dict(product_qty=3.0), dict(product_qty=2.0)]) def test_mrp_production_split_lot_simple_copy_date_planned(self): dt_start = datetime.now() + timedelta(days=5) dt_finished = dt_start + timedelta(hours=1) self.production.date_planned_start = dt_start self.production.date_planned_finished = dt_finished self.production.action_confirm() self.production.action_generate_serial() mos = self._mrp_production_split(self.production, split_qty=2.0) self.assertRecordValues( mos, [ dict( product_qty=3.0, date_planned_start=dt_start, date_planned_finished=dt_finished, ), dict( product_qty=2.0, date_planned_start=dt_start, date_planned_finished=dt_finished, ), ], ) def test_mrp_production_split_lot_simple_zero_qty(self): self.production.action_confirm() self.production.action_generate_serial() with self.assertRaisesRegex(UserError, r"Nothing to split.*"): self._mrp_production_split(self.production, split_qty=0.0) def test_mrp_production_split_lot_simple_with_qty_producing_exceeded(self): self.production.action_confirm() self.production.action_generate_serial() self.production.qty_producing = 3.0 with self.assertRaisesRegex(UserError, r"You can't split.*"): self._mrp_production_split(self.production, split_qty=4.0) def test_mrp_production_split_lot_equal(self): self.production.action_confirm() self.production.action_generate_serial() mos = self._mrp_production_split( self.production, split_mode="equal", split_qty=4.0, split_equal_qty=2.0, ) self.assertRecordValues( mos, [ dict(product_qty=1.0), dict(product_qty=2.0), dict(product_qty=2.0), ], ) def test_mrp_production_split_lot_custom(self): self.production.action_confirm() self.production.action_generate_serial() mos = self._mrp_production_split( self.production, split_mode="custom", custom_quantities="1 2 1 1", ) self.assertRecordValues( mos, [ dict(product_qty=1.0), dict(product_qty=2.0), dict(product_qty=1.0), dict(product_qty=1.0), ], ) def test_mrp_production_split_lot_custom_incomplete(self): self.production.action_confirm() self.production.action_generate_serial() mos = self._mrp_production_split( self.production, split_mode="custom", custom_quantities="1 2", ) self.assertRecordValues( mos, [ dict(product_qty=2.0), dict(product_qty=1.0), dict(product_qty=2.0), ], ) def test_mrp_production_split_lot_custom_float(self): self.production.action_confirm() self.production.action_generate_serial() mos = self._mrp_production_split( self.production, split_mode="custom", custom_quantities="1.0 2.0 1.0 1.0", ) self.assertRecordValues( mos, [ dict(product_qty=1.0), dict(product_qty=2.0), dict(product_qty=1.0), dict(product_qty=1.0), ], ) def test_mrp_production_split_lot_custom_float_locale(self): lang = self.env["res.lang"]._lang_get(self.env.user.lang) lang.decimal_point = "," lang.thousands_sep = "" self.production.action_confirm() self.production.action_generate_serial() mos = self._mrp_production_split( self.production, split_mode="custom", custom_quantities="1,0 2,0 1,0 1,0", ) self.assertRecordValues( mos, [ dict(product_qty=1.0), dict(product_qty=2.0), dict(product_qty=1.0), dict(product_qty=1.0), ], ) def test_mrp_production_split_serial(self): self.product.tracking = "serial" self.production.action_confirm() mos = self._mrp_production_split(self.production) self.assertRecordValues( mos, [ dict(product_qty=1.0), dict(product_qty=1.0), dict(product_qty=1.0), dict(product_qty=1.0), dict(product_qty=1.0), ], )
35.106742
6,249
3,296
py
PYTHON
15.0
# Copyright 2023 Camptocamp SA (https://www.camptocamp.com). # @author Iván Todorovich <[email protected]> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import Command from odoo.tests import Form, TransactionCase class CommonCase(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.env = cls.env(context=dict(cls.env.context, tracking_disable=True)) # Create bom, product and components cls.component = cls.env["product.product"].create( { "name": "Component", "detailed_type": "product", } ) cls.product = cls.env["product.product"].create( { "name": "Product", "detailed_type": "product", "tracking": "lot", } ) cls.product_bom = cls.env["mrp.bom"].create( { "product_tmpl_id": cls.product.product_tmpl_id.id, "product_qty": 1.0, "product_uom_id": cls.product.uom_id.id, "bom_line_ids": [ Command.create( { "product_id": cls.component.id, "product_qty": 1.0, "product_uom_id": cls.component.uom_id.id, } ) ], } ) # Create some initial stocks cls.location_stock = cls.env.ref("stock.stock_location_stock") cls.env["stock.quant"].create( { "product_id": cls.component.id, "product_uom_id": cls.component.uom_id.id, "location_id": cls.location_stock.id, "quantity": 10.00, } ) # Create the MO cls.production = cls._create_mrp_production( product=cls.product, bom=cls.product_bom, ) @classmethod def _create_mrp_production( cls, product=None, bom=None, quantity=5.0, confirm=False ): if product is None: # pragma: no cover product = cls.product if bom is None: # pragma: no cover bom = cls.product_bom mo_form = Form(cls.env["mrp.production"]) mo_form.product_id = product mo_form.bom_id = bom mo_form.product_qty = quantity mo_form.product_uom_id = product.uom_id mo = mo_form.save() if confirm: # pragma: no cover mo.action_confirm() return mo def _mrp_production_set_quantity_done(self, order): for line in order.move_raw_ids.move_line_ids: line.qty_done = line.product_uom_qty order.move_raw_ids._recompute_state() order.qty_producing = order.product_qty def _mrp_production_split(self, order, **vals): action = order.action_split() Wizard = self.env[action["res_model"]] Wizard = Wizard.with_context(active_model=order._name, active_id=order.id) Wizard = Wizard.with_context(**action["context"]) wizard = Wizard.create(vals) res = wizard.apply() records = self.env[res["res_model"]].search(res["domain"]) return records
35.815217
3,295
1,354
py
PYTHON
15.0
# Copyright 2023 Camptocamp SA (https://www.camptocamp.com). # @author Iván Todorovich <[email protected]> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import _, models from odoo.exceptions import UserError class MrpProduction(models.Model): _inherit = "mrp.production" def copy_data(self, default=None): # OVERRIDE copy the date_planned_start and date_planned_end when splitting # productions, as they are not copied by default (copy=False). [data] = super().copy_data(default=default) data.setdefault("date_planned_start", self.date_planned_start) data.setdefault("date_planned_finished", self.date_planned_finished) return [data] def action_split(self): self.ensure_one() self._check_company() if self.state in ("draft", "done", "to_close", "cancel"): raise UserError( _( "Cannot split a manufacturing order that is in '%s' state.", self._fields["state"].convert_to_export(self.state, self), ) ) action = self.env["ir.actions.actions"]._for_xml_id( "mrp_production_split.action_mrp_production_split_wizard" ) action["context"] = {"default_production_id": self.id} return action
39.794118
1,353
7,064
py
PYTHON
15.0
# Copyright 2023 Camptocamp SA (https://www.camptocamp.com). # @author Iván Todorovich <[email protected]> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from typing import List, Union from odoo import _, api, fields, models from odoo.exceptions import UserError class MrpProductionSplitWizard(models.TransientModel): _name = "mrp.production.split.wizard" production_id = fields.Many2one( "mrp.production", "Production", required=True, ondelete="cascade", ) split_mode = fields.Selection( [ ("simple", "Extract a quantity from the original MO"), ("equal", "Extract a quantity into several MOs with equal quantities"), ("custom", "Custom"), ], required=True, default="simple", ) split_qty = fields.Float( string="Quantity", digits="Product Unit of Measure", help="Total quantity to extract from the original MO.", ) split_equal_qty = fields.Float( string="Equal Quantity", digits="Product Unit of Measure", help="Used to split the MO into several MOs with equal quantities.", default=1, ) custom_quantities = fields.Char( string="Split Quantities", help="Space separated list of quantities to split:\n" "e.g. '3 2 5' will result in 3 MOs with 3, 2 and 5 units respectively.\n" "If the sum of the quantities is less than the original MO's quantity, the " "remaining quantity will remain in the original MO.", ) product_tracking = fields.Selection(related="production_id.product_id.tracking") product_uom_id = fields.Many2one(related="production_id.product_uom_id") @api.model def default_get(self, fields_list): res = super().default_get(fields_list) active_model = self.env.context.get("active_model") active_id = self.env.context.get("active_id") # Auto-complete production_id from context if "production_id" in fields_list and active_model == "mrp.production": res["production_id"] = active_id # Auto-complete split_mode from production_id if "split_mode" in fields_list and res.get("production_id"): production = self.env["mrp.production"].browse(res["production_id"]) if production.product_tracking == "serial": res["split_mode"] = "equal" # Auto-complete split_qty from production_id if "split_qty" in fields_list and res.get("production_id"): production = self.env["mrp.production"].browse(res["production_id"]) res["split_qty"] = production._get_quantity_to_backorder() return res @api.model def _parse_float(self, value: Union[float, int, str]) -> float: """Parse a float number from a string, with the user's language settings.""" if isinstance(value, (float, int)): # pragma: no cover return float(value) lang = self.env["res.lang"]._lang_get(self.env.user.lang) try: return float( value.replace(lang.thousands_sep, "") .replace(lang.decimal_point, ".") .strip() ) except ValueError as e: # pragma: no cover raise UserError(_("%s is not a number.", value)) from e @api.model def _parse_float_list(self, value: str) -> List[float]: """Parse a list of float numbers from a string.""" return [self._parse_float(v) for v in value.split()] @api.onchange("custom_quantities") def _onchange_custom_quantities_check(self): """Check that the custom quantities are valid.""" if self.custom_quantities: # pragma: no cover try: self._parse_float_list(self.custom_quantities) except UserError: return { "warning": { "title": _("Invalid quantities"), "message": _("Please enter a space separated list of numbers."), } } def _get_split_quantities(self) -> List[float]: """Return the quantities to split, according to the settings.""" production = self.production_id rounding = production.product_uom_id.rounding if self.split_mode == "simple": if ( fields.Float.compare( self.split_qty, production._get_quantity_to_backorder(), rounding ) > 0 ): raise UserError(_("You can't split quantities already in production.")) if fields.Float.is_zero(self.split_qty, precision_rounding=rounding): raise UserError(_("Nothing to split.")) return [production.product_qty - self.split_qty, self.split_qty] elif self.split_mode == "equal": split_total = min(production._get_quantity_to_backorder(), self.split_qty) split_count = int(split_total // self.split_equal_qty) split_rest = production.product_qty - split_total split_rest += split_total % self.split_equal_qty quantities = [self.split_equal_qty] * split_count if not fields.Float.is_zero(split_rest, precision_rounding=rounding): quantities = [split_rest] + quantities return quantities elif self.split_mode == "custom": quantities = self._parse_float_list(self.custom_quantities) split_total = sum(quantities) split_rest = production.product_qty - split_total if not fields.Float.is_zero(split_rest, precision_rounding=rounding): quantities = [split_rest] + quantities return quantities else: # pragma: no cover raise UserError(_("Invalid Split Mode: '%s'", self.split_mode)) def _apply(self): self.ensure_one() records = self.production_id.with_context( copy_date_planned=True )._split_productions( amounts={self.production_id: self._get_split_quantities()}, cancel_remaning_qty=False, set_consumed_qty=False, ) new_records = records - self.production_id for record in new_records: record.message_post_with_view( "mail.message_origin_link", values=dict(self=record, origin=self.production_id), message_log=True, ) if new_records: self.production_id.message_post_with_view( "mrp_production_split.message_order_split", values=dict(self=self.production_id, records=new_records), message_log=True, ) return records def apply(self): records = self._apply() action = self.env["ir.actions.act_window"]._for_xml_id( "mrp.mrp_production_action" ) action["domain"] = [("id", "in", records.ids)] return action
42.293413
7,063
2,209
py
PYTHON
15.0
import setuptools with open('VERSION.txt', 'r') as f: version = f.read().strip() setuptools.setup( name="odoo-addons-oca-manufacture", description="Meta package for oca-manufacture Odoo addons", version=version, install_requires=[ 'odoo-addon-mrp_account_analytic>=15.0dev,<15.1dev', 'odoo-addon-mrp_account_bom_attribute_match>=15.0dev,<15.1dev', 'odoo-addon-mrp_bom_attribute_match>=15.0dev,<15.1dev', 'odoo-addon-mrp_bom_component_menu>=15.0dev,<15.1dev', 'odoo-addon-mrp_bom_hierarchy>=15.0dev,<15.1dev', 'odoo-addon-mrp_bom_location>=15.0dev,<15.1dev', 'odoo-addon-mrp_bom_tracking>=15.0dev,<15.1dev', 'odoo-addon-mrp_finished_backorder_product>=15.0dev,<15.1dev', 'odoo-addon-mrp_lot_number_propagation>=15.0dev,<15.1dev', 'odoo-addon-mrp_lot_on_hand_first>=15.0dev,<15.1dev', 'odoo-addon-mrp_multi_level>=15.0dev,<15.1dev', 'odoo-addon-mrp_multi_level_estimate>=15.0dev,<15.1dev', 'odoo-addon-mrp_planned_order_matrix>=15.0dev,<15.1dev', 'odoo-addon-mrp_production_component_availability_search>=15.0dev,<15.1dev', 'odoo-addon-mrp_production_date_planned_finished>=15.0dev,<15.1dev', 'odoo-addon-mrp_production_grouped_by_product>=15.0dev,<15.1dev', 'odoo-addon-mrp_production_putaway_strategy>=15.0dev,<15.1dev', 'odoo-addon-mrp_production_serial_matrix>=15.0dev,<15.1dev', 'odoo-addon-mrp_production_split>=15.0dev,<15.1dev', 'odoo-addon-mrp_progress_button>=15.0dev,<15.1dev', 'odoo-addon-mrp_sale_info>=15.0dev,<15.1dev', 'odoo-addon-mrp_subcontracting_no_negative>=15.0dev,<15.1dev', 'odoo-addon-mrp_tag>=15.0dev,<15.1dev', 'odoo-addon-mrp_warehouse_calendar>=15.0dev,<15.1dev', 'odoo-addon-mrp_workorder_sequence>=15.0dev,<15.1dev', 'odoo-addon-quality_control_oca>=15.0dev,<15.1dev', 'odoo-addon-stock_picking_product_kit_helper>=15.0dev,<15.1dev', 'odoo-addon-stock_whole_kit_constraint>=15.0dev,<15.1dev', ], classifiers=[ 'Programming Language :: Python', 'Framework :: Odoo', 'Framework :: Odoo :: 15.0', ] )
49.088889
2,209
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
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
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
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
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
757
py
PYTHON
15.0
# Copyright 2019-23 ForgeFlow S.L. (http://www.forgeflow.com) # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). { "name": "MRP Multi Level Estimate", "version": "15.0.1.1.0", "development_status": "Production/Stable", "license": "LGPL-3", "author": "ForgeFlow, Odoo Community Association (OCA)", "maintainers": ["LoisRForgeFlow"], "summary": "Allows to consider demand estimates using MRP multi level.", "website": "https://github.com/OCA/manufacture", "category": "Manufacturing", "depends": ["mrp_multi_level", "stock_demand_estimate"], "data": ["views/product_mrp_area_views.xml", "views/mrp_area_views.xml"], "installable": True, "application": False, "auto_install": True, }
39.842105
757
14,169
py
PYTHON
15.0
# Copyright 2018-22 ForgeFlow S.L. (http://www.forgeflow.com) # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from datetime import datetime, timedelta from odoo.addons.mrp_multi_level.tests.common import TestMrpMultiLevelCommon class TestMrpMultiLevelEstimate(TestMrpMultiLevelCommon): @classmethod def setUpClass(cls): super().setUpClass() cls.estimate_obj = cls.env["stock.demand.estimate"] cls.uom_unit = cls.env.ref("uom.product_uom_unit") # Create new clean area: cls.estimate_loc = cls.loc_obj.create( { "name": "Test location for estimates", "usage": "internal", "location_id": cls.wh.view_location_id.id, } ) cls.estimate_area = cls.mrp_area_obj.create( { "name": "Test", "warehouse_id": cls.wh.id, "location_id": cls.estimate_loc.id, } ) cls.test_mrp_parameter = cls.product_mrp_area_obj.create( { "product_id": cls.prod_test.id, "mrp_area_id": cls.estimate_area.id, "mrp_nbr_days": 7, } ) # Create 3 consecutive estimates of 1 week length each. today = datetime.today().replace(hour=0) date_start_1 = today - timedelta(days=3) date_end_1 = date_start_1 + timedelta(days=6) date_start_2 = date_end_1 + timedelta(days=1) date_end_2 = date_start_2 + timedelta(days=6) date_start_3 = date_end_2 + timedelta(days=1) date_end_3 = date_start_3 + timedelta(days=6) start_dates = [date_start_1, date_start_2, date_start_3] end_dates = [date_end_1, date_end_2, date_end_3] cls.date_within_ranges = today - timedelta(days=2) cls.date_without_ranges = today + timedelta(days=150) qty = 140.0 for sd, ed in zip(start_dates, end_dates): qty += 70.0 cls._create_demand_estimate(cls.prod_test, cls.stock_location, sd, ed, qty) cls._create_demand_estimate(cls.prod_test, cls.estimate_loc, sd, ed, qty) cls.mrp_multi_level_wiz.create({}).run_mrp_multi_level() @classmethod def _create_demand_estimate(cls, product, location, date_from, date_to, qty): cls.estimate_obj.create( { "product_id": product.id, "location_id": location.id, "product_uom": product.uom_id.id, "product_uom_qty": qty, "manual_date_from": date_from, "manual_date_to": date_to, } ) def test_01_demand_estimates(self): """Tests demand estimates integration.""" estimates = self.estimate_obj.search( [ ("product_id", "=", self.prod_test.id), ("location_id", "=", self.stock_location.id), ] ) self.assertEqual(len(estimates), 3) moves = self.mrp_move_obj.search( [ ("product_id", "=", self.prod_test.id), ("mrp_area_id", "=", self.mrp_area.id), ] ) # 3 weeks - 3 days in the past = 18 days of valid estimates: moves_from_estimates = moves.filtered(lambda m: m.mrp_type == "d") self.assertEqual(len(moves_from_estimates), 18) quantities = moves_from_estimates.mapped("mrp_qty") self.assertIn(-30.0, quantities) # 210 a week => 30.0 dayly: self.assertIn(-40.0, quantities) # 280 a week => 40.0 dayly: self.assertIn(-50.0, quantities) # 350 a week => 50.0 dayly: plans = self.planned_order_obj.search( [ ("product_id", "=", self.prod_test.id), ("mrp_area_id", "=", self.mrp_area.id), ] ) action = list(set(plans.mapped("mrp_action"))) self.assertEqual(len(action), 1) self.assertEqual(action[0], "buy") self.assertEqual(len(plans), 18) inventories = self.mrp_inventory_obj.search( [("mrp_area_id", "=", self.estimate_area.id)] ) self.assertEqual(len(inventories), 18) def test_02_demand_estimates_group_plans(self): """Test requirement grouping functionality, `nbr_days`.""" estimates = self.estimate_obj.search( [ ("product_id", "=", self.prod_test.id), ("location_id", "=", self.estimate_loc.id), ] ) self.assertEqual(len(estimates), 3) moves = self.mrp_move_obj.search( [ ("product_id", "=", self.prod_test.id), ("mrp_area_id", "=", self.estimate_area.id), ] ) supply_plans = self.planned_order_obj.search( [ ("product_id", "=", self.prod_test.id), ("mrp_area_id", "=", self.estimate_area.id), ] ) # 3 weeks - 3 days in the past = 18 days of valid estimates: moves_from_estimates = moves.filtered(lambda m: m.mrp_type == "d") self.assertEqual(len(moves_from_estimates), 18) # 18 days of demand / 7 nbr_days = 2.57 => 3 supply moves expected. self.assertEqual(len(supply_plans), 3) quantities = supply_plans.mapped("mrp_qty") week_1_expected = sum(moves_from_estimates[0:7].mapped("mrp_qty")) self.assertIn(abs(week_1_expected), quantities) week_2_expected = sum(moves_from_estimates[7:14].mapped("mrp_qty")) self.assertIn(abs(week_2_expected), quantities) week_3_expected = sum(moves_from_estimates[14:].mapped("mrp_qty")) self.assertIn(abs(week_3_expected), quantities) def test_03_group_demand_estimates(self): """Test demand grouping functionality, `group_estimate_days`.""" self.test_mrp_parameter.group_estimate_days = 7 self.mrp_multi_level_wiz.create( {"mrp_area_ids": [(6, 0, self.estimate_area.ids)]} ).run_mrp_multi_level() estimates = self.estimate_obj.search( [ ("product_id", "=", self.prod_test.id), ("location_id", "=", self.estimate_loc.id), ] ) self.assertEqual(len(estimates), 3) moves = self.mrp_move_obj.search( [ ("product_id", "=", self.prod_test.id), ("mrp_area_id", "=", self.estimate_area.id), ] ) # 3 weekly estimates, demand from estimates grouped in batches of 7 # days = 3 days of estimates mrp moves: moves_from_estimates = moves.filtered(lambda m: m.mrp_type == "d") self.assertEqual(len(moves_from_estimates), 3) # 210 weekly -> 30 daily -> 30 * 4 days not consumed = 120 self.assertEqual(moves_from_estimates[0].mrp_qty, -120) self.assertEqual(moves_from_estimates[1].mrp_qty, -280) self.assertEqual(moves_from_estimates[2].mrp_qty, -350) # Test group_estimate_days greater than date range, it should not # generate greater demand. self.test_mrp_parameter.group_estimate_days = 10 self.mrp_multi_level_wiz.create( {"mrp_area_ids": [(6, 0, self.estimate_area.ids)]} ).run_mrp_multi_level() moves = self.mrp_move_obj.search( [ ("product_id", "=", self.prod_test.id), ("mrp_area_id", "=", self.estimate_area.id), ] ) moves_from_estimates = moves.filtered(lambda m: m.mrp_type == "d") self.assertEqual(len(moves_from_estimates), 3) self.assertEqual(moves_from_estimates[0].mrp_qty, -120) self.assertEqual(moves_from_estimates[1].mrp_qty, -280) self.assertEqual(moves_from_estimates[2].mrp_qty, -350) # Test group_estimate_days smaller than date range, it should not # generate greater demand. self.test_mrp_parameter.group_estimate_days = 5 self.mrp_multi_level_wiz.create( {"mrp_area_ids": [(6, 0, self.estimate_area.ids)]} ).run_mrp_multi_level() moves = self.mrp_move_obj.search( [ ("product_id", "=", self.prod_test.id), ("mrp_area_id", "=", self.estimate_area.id), ] ) moves_from_estimates = moves.filtered(lambda m: m.mrp_type == "d") self.assertEqual(len(moves_from_estimates), 5) # Week 1 partially consumed, so only 4 remaining days considered. # 30 daily x 4 days = 120 self.assertEqual(moves_from_estimates[0].mrp_qty, -120) # Week 2 divided in 2 (40 daily) -> 5 days = 200, 2 days = 80 self.assertEqual(moves_from_estimates[1].mrp_qty, -200) self.assertEqual(moves_from_estimates[2].mrp_qty, -80) # Week 3 divided in 2, (50 daily) -> 5 days = 250, 2 days = 100 self.assertEqual(moves_from_estimates[3].mrp_qty, -250) self.assertEqual(moves_from_estimates[4].mrp_qty, -100) def test_04_group_demand_estimates_rounding(self): """Test demand grouping functionality, `group_estimate_days` and rounding.""" self.test_mrp_parameter.group_estimate_days = 7 self.uom_unit.rounding = 1.00 estimates = self.estimate_obj.search( [ ("product_id", "=", self.prod_test.id), ("location_id", "=", self.estimate_loc.id), ] ) self.assertEqual(len(estimates), 3) # Change qty of estimates to quantities that divided by 7 days return a decimal result qty = 400 for estimate in estimates: estimate.product_uom_qty = qty qty += 100 self.mrp_multi_level_wiz.create( {"mrp_area_ids": [(6, 0, self.estimate_area.ids)]} ).run_mrp_multi_level() moves = self.mrp_move_obj.search( [ ("product_id", "=", self.prod_test.id), ("mrp_area_id", "=", self.estimate_area.id), ] ) # 3 weekly estimates, demand from estimates grouped in batches of 7 # days = 3 days of estimates mrp moves: moves_from_estimates = moves.filtered(lambda m: m.mrp_type == "d") self.assertEqual(len(moves_from_estimates), 3) # Rounding should be done at the end of the calculation, using the daily # quantity already rounded can lead to errors. # 400 weekly -> 57.41 daily -> 57.41 * 4 days not consumed = 228,57 = 229 self.assertEqual(moves_from_estimates[0].mrp_qty, -229) # 500 weekly -> 71.42 daily -> 71,42 * 7 = 500 self.assertEqual(moves_from_estimates[1].mrp_qty, -500) # 600 weekly -> 85.71 daily -> 85.71 * 7 = 600 self.assertEqual(moves_from_estimates[2].mrp_qty, -600) def test_05_estimate_and_other_sources_strat(self): """Tests demand estimates and other sources strategies.""" estimates = self.estimate_obj.search( [ ("product_id", "=", self.prod_test.id), ("location_id", "=", self.estimate_loc.id), ] ) self.assertEqual(len(estimates), 3) self._create_picking_out( self.prod_test, 25, self.date_within_ranges, location=self.estimate_loc ) self._create_picking_out( self.prod_test, 25, self.date_without_ranges, location=self.estimate_loc ) # 1. "all" self.estimate_area.estimate_demand_and_other_sources_strat = "all" self.mrp_multi_level_wiz.create( {"mrp_area_ids": [(6, 0, self.estimate_area.ids)]} ).run_mrp_multi_level() moves = self.mrp_move_obj.search( [ ("product_id", "=", self.prod_test.id), ("mrp_area_id", "=", self.estimate_area.id), ] ) # 3 weeks - 3 days in the past = 18 days of valid estimates: demand_from_estimates = moves.filtered( lambda m: m.mrp_type == "d" and m.mrp_origin == "fc" ) demand_from_other_sources = moves.filtered( lambda m: m.mrp_type == "d" and m.mrp_origin != "fc" ) self.assertEqual(len(demand_from_estimates), 18) self.assertEqual(len(demand_from_other_sources), 2) # 2. "ignore_others_if_estimates" self.estimate_area.estimate_demand_and_other_sources_strat = ( "ignore_others_if_estimates" ) self.mrp_multi_level_wiz.create( {"mrp_area_ids": [(6, 0, self.estimate_area.ids)]} ).run_mrp_multi_level() moves = self.mrp_move_obj.search( [ ("product_id", "=", self.prod_test.id), ("mrp_area_id", "=", self.estimate_area.id), ] ) demand_from_estimates = moves.filtered( lambda m: m.mrp_type == "d" and m.mrp_origin == "fc" ) demand_from_other_sources = moves.filtered( lambda m: m.mrp_type == "d" and m.mrp_origin != "fc" ) self.assertEqual(len(demand_from_estimates), 18) self.assertEqual(len(demand_from_other_sources), 0) # 3. "ignore_overlapping" self.estimate_area.estimate_demand_and_other_sources_strat = ( "ignore_overlapping" ) self.mrp_multi_level_wiz.create( {"mrp_area_ids": [(6, 0, self.estimate_area.ids)]} ).run_mrp_multi_level() moves = self.mrp_move_obj.search( [ ("product_id", "=", self.prod_test.id), ("mrp_area_id", "=", self.estimate_area.id), ] ) demand_from_estimates = moves.filtered( lambda m: m.mrp_type == "d" and m.mrp_origin == "fc" ) demand_from_other_sources = moves.filtered( lambda m: m.mrp_type == "d" and m.mrp_origin != "fc" ) self.assertEqual(len(demand_from_estimates), 18) self.assertEqual(len(demand_from_other_sources), 1) self.assertEqual( demand_from_other_sources.mrp_date, self.date_without_ranges.date() )
42.295522
14,169
1,504
py
PYTHON
15.0
# Copyright 2022 ForgeFlow S.L. (http://www.forgeflow.com) # - Lois Rilo Antelo <[email protected]> # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import fields, models class MRPArea(models.Model): _inherit = "mrp.area" estimate_demand_and_other_sources_strat = fields.Selection( string="Demand Estimates and Other Demand Sources Strategy", selection=[ ("all", "Always consider all sources"), ( "ignore_others_if_estimates", "Ignore other sources for products with estimates", ), ( "ignore_overlapping", "Ignore other sources during periods with estimates", ), ], default="all", help="Define the strategy to follow in MRP multi level when there is a" "coexistence of demand from demand estimates and other sources.\n" "* Always consider all sources: nothing is excluded or ignored.\n" "* Ignore other sources for products with estimates: When there " "are estimates entered for product and they are in a present or " "future period, all other sources of demand are ignored for those " "products.\n" "* Ignore other sources during periods with estimates: When " "you create demand estimates for a period and product, " "other sources of demand will be ignored during that period " "for those products.", )
41.777778
1,504
910
py
PYTHON
15.0
# Copyright 2019-20 ForgeFlow S.L. (http://www.forgeflow.com) # - Lois Rilo Antelo <[email protected]> # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import fields, models class ProductMRPArea(models.Model): _inherit = "product.mrp.area" group_estimate_days = fields.Integer( string="Group Days of Estimates", default=1, help="The days to group your estimates as demand for the MRP." "It can be different from the length of the date ranges you " "use in the estimates but it should not be greater, in that case" "only grouping until the total length of the date range will be done.", ) _sql_constraints = [ ( "group_estimate_days_check", "CHECK( group_estimate_days >= 0 )", "Group Days of Estimates must be greater than or equal to zero.", ), ]
35
910
4,735
py
PYTHON
15.0
# Copyright 2019-22 ForgeFlow S.L. (http://www.forgeflow.com) # - Lois Rilo <[email protected]> # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). import logging from datetime import timedelta from odoo import api, fields, models from odoo.tools.float_utils import float_round logger = logging.getLogger(__name__) class MultiLevelMrp(models.TransientModel): _inherit = "mrp.multi.level" @api.model def _prepare_mrp_move_data_from_estimate(self, estimate, product_mrp_area, date): mrp_type = "d" origin = "fc" daily_qty_unrounded = estimate.daily_qty daily_qty = float_round( estimate.daily_qty, precision_rounding=product_mrp_area.product_id.uom_id.rounding, rounding_method="HALF-UP", ) days_consumed = 0 if product_mrp_area.group_estimate_days > 1: start = estimate.date_from if start < date: days_consumed = (date - start).days group_estimate_days = min( product_mrp_area.group_estimate_days, estimate.duration - days_consumed ) mrp_qty = float_round( daily_qty_unrounded * group_estimate_days, precision_rounding=product_mrp_area.product_id.uom_id.rounding, rounding_method="HALF-UP", ) return { "mrp_area_id": product_mrp_area.mrp_area_id.id, "product_id": product_mrp_area.product_id.id, "product_mrp_area_id": product_mrp_area.id, "production_id": None, "purchase_order_id": None, "purchase_line_id": None, "stock_move_id": None, "mrp_qty": -mrp_qty, "current_qty": -daily_qty, "mrp_date": date, "current_date": date, "mrp_type": mrp_type, "mrp_origin": origin, "mrp_order_number": None, "parent_product_id": None, "name": "Forecast", "state": "confirmed", } @api.model def _estimates_domain(self, product_mrp_area): locations = product_mrp_area.mrp_area_id._get_locations() return [ ("product_id", "=", product_mrp_area.product_id.id), ("location_id", "in", locations.ids), ("date_to", ">=", fields.Date.today()), ] @api.model def _init_mrp_move_from_forecast(self, product_mrp_area): res = super(MultiLevelMrp, self)._init_mrp_move_from_forecast(product_mrp_area) if not product_mrp_area.group_estimate_days: return False today = fields.Date.today() domain = self._estimates_domain(product_mrp_area) estimates = self.env["stock.demand.estimate"].search(domain) for rec in estimates: start = rec.date_from if start < today: start = today mrp_date = fields.Date.from_string(start) date_end = fields.Date.from_string(rec.date_to) delta = timedelta(days=product_mrp_area.group_estimate_days) while mrp_date <= date_end: mrp_move_data = self._prepare_mrp_move_data_from_estimate( rec, product_mrp_area, mrp_date ) self.env["mrp.move"].create(mrp_move_data) mrp_date += delta return res def _exclude_considering_estimate_demand_and_other_sources_strat( self, product_mrp_area, mrp_date ): estimate_strat = ( product_mrp_area.mrp_area_id.estimate_demand_and_other_sources_strat ) if estimate_strat == "all": return False domain = self._estimates_domain(product_mrp_area) estimates = self.env["stock.demand.estimate"].search(domain) if not estimates: return False if estimate_strat == "ignore_others_if_estimates": # Ignore return True if estimate_strat == "ignore_overlapping": for estimate in estimates: if mrp_date >= estimate.date_from and mrp_date <= estimate.date_to: # Ignore return True return False @api.model def _prepare_mrp_move_data_from_stock_move( self, product_mrp_area, move, direction="in" ): res = super()._prepare_mrp_move_data_from_stock_move( product_mrp_area, move, direction=direction ) if direction == "out": mrp_date = res.get("mrp_date") if self._exclude_considering_estimate_demand_and_other_sources_strat( product_mrp_area, mrp_date ): return False return res
36.705426
4,735
390
py
PYTHON
15.0
{ "name": "BOM Attribute Match", "version": "15.0.1.1.0", "category": "Manufacturing", "author": "Ilyas, Ooops, Odoo Community Association (OCA)", "summary": "Dynamic BOM component based on product attribute", "depends": ["mrp"], "license": "AGPL-3", "website": "https://github.com/OCA/manufacture", "data": [ "views/mrp_bom_views.xml", ], }
30
390
7,892
py
PYTHON
15.0
from odoo.exceptions import UserError, ValidationError from odoo.tests import Form from .common import TestMrpBomAttributeMatchBase class TestMrpBomAttributeMatch(TestMrpBomAttributeMatchBase): def test_bom_1(self): mrp_bom_form = Form(self.env["mrp.bom"]) mrp_bom_form.product_tmpl_id = self.product_sword with mrp_bom_form.bom_line_ids.new() as line_form: line_form.product_id = self.product_plastic.product_variant_ids[0] line_form.component_template_id = self.product_plastic self.assertEqual(line_form.product_id.id, False) line_form.component_template_id = self.env["product.template"] self.assertEqual( line_form.product_id, self.product_plastic.product_variant_ids[0] ) line_form.component_template_id = self.product_plastic line_form.product_qty = 1 sword_cyan = self.sword_attrs.product_template_value_ids[0] with self.assertRaisesRegex( ValidationError, r"You cannot use an attribute value for attribute\(s\) .* in the " r"field “Apply on Variants” as it's the same attribute used in the " r"field “Match on Attribute” related to the component .*", ): line_form.bom_product_template_attribute_value_ids.add(sword_cyan) def test_bom_2(self): smell_attribute = self.env["product.attribute"].create( {"name": "Smell", "display_type": "radio", "create_variant": "always"} ) orchid_attribute_value_id = self.env["product.attribute.value"].create( [ {"name": "Orchid", "attribute_id": smell_attribute.id}, ] ) plastic_smells_like_orchid = self.env["product.template.attribute.line"].create( { "attribute_id": smell_attribute.id, "product_tmpl_id": self.product_plastic.id, "value_ids": [(4, orchid_attribute_value_id.id)], } ) with self.assertRaisesRegex( UserError, r"This product template is used as a component in the BOMs for .* and " r"attribute\(s\) .* is not present in all such product\(s\), and this " r"would break the BOM behavior\.", ): vals = { "attribute_id": smell_attribute.id, "product_tmpl_id": self.product_plastic.id, "value_ids": [(4, orchid_attribute_value_id.id)], } self.product_plastic.write({"attribute_line_ids": [(0, 0, vals)]}) mrp_bom_form = Form(self.env["mrp.bom"]) mrp_bom_form.product_tmpl_id = self.product_sword with mrp_bom_form.bom_line_ids.new() as line_form: with self.assertRaisesRegex( UserError, r"Some attributes of the dynamic component are not included into " r"production product attributes\.", ): line_form.component_template_id = self.product_plastic plastic_smells_like_orchid.unlink() def test_manufacturing_order_1(self): sword_cyan = self.product_sword.product_variant_ids[0] plastic_cyan = self.product_plastic.product_variant_ids[0] mo_form = Form(self.env["mrp.production"]) mo_form.product_id = sword_cyan mo_form.bom_id = self.bom_id mo_form.product_qty = 1 self.mo_sword = mo_form.save() self.mo_sword.action_confirm() # Assert correct component variant was selected automatically self.assertEqual( self.mo_sword.move_raw_ids.product_id, plastic_cyan + self.product_9, ) def test_manufacturing_order_2(self): # Delete Cyan value from plastic self.plastic_attrs.value_ids = [(3, self.plastic_attrs.value_ids[0].id, 0)] mo_form = Form(self.env["mrp.production"]) mo_form.product_id = self.product_sword.product_variant_ids.filtered( lambda x: x.display_name == "Plastic Sword (Cyan)" ) mo_form.bom_id = self.bom_id mo_form.product_qty = 1 self.mo_sword = mo_form.save() self.mo_sword.action_confirm() def test_manufacturing_order_3(self): # Delete attribute from sword self.product_sword.attribute_line_ids = [(5, 0, 0)] mo_form = Form(self.env["mrp.production"]) mo_form.product_id = self.product_sword.product_variant_ids[0] # Component skipped mo_form.bom_id = self.bom_id mo_form.product_qty = 1 with self.assertRaisesRegex( ValidationError, r"Some attributes of the dynamic component are not included into .+", ): self.mo_sword = mo_form.save() def test_manufacturing_order_4(self): mo_form = Form(self.env["mrp.production"]) mo_form.product_id = self.product_surf.product_variant_ids[0] mo_form.bom_id = self.surf_bom_id mo_form.product_qty = 1 self.mo_sword = mo_form.save() self.mo_sword.action_confirm() # def test_manufacturing_order_5(self): # mo_form = Form(self.env["mrp.production"]) # mo_form.product_id = self.product_surf.product_variant_ids[0] # mo_form.bom_id = self.surf_wrong_bom_id # mo_form.product_qty = 1 # self.mo_sword = mo_form.save() # self.mo_sword.action_confirm() # def test_manufacturing_order_6(self): # mo_form = Form(self.env["mrp.production"]) # mo_form.product_id = self.p1.product_variant_ids[0] # mo_form.bom_id = self.p1_bom_id # mo_form.product_qty = 1 # self.mo_sword = mo_form.save() # self.mo_sword.action_confirm() def test_bom_recursion(self): test_bom_3 = self.env["mrp.bom"].create( { "product_id": self.product_9.id, "product_tmpl_id": self.product_9.product_tmpl_id.id, "product_uom_id": self.product_9.uom_id.id, "product_qty": 1.0, "consumption": "flexible", "type": "normal", } ) test_bom_4 = self.env["mrp.bom"].create( { "product_id": self.product_10.id, "product_tmpl_id": self.product_10.product_tmpl_id.id, "product_uom_id": self.product_10.uom_id.id, "product_qty": 1.0, "consumption": "flexible", "type": "phantom", } ) self.env["mrp.bom.line"].create( { "bom_id": test_bom_3.id, "product_id": self.product_10.id, "product_qty": 1.0, } ) self.env["mrp.bom.line"].create( { "bom_id": test_bom_4.id, "product_id": self.product_9.id, "product_qty": 1.0, } ) with self.assertRaisesRegex(UserError, r"Recursion error! .+"): test_bom_3.explode(self.product_9, 1) def test_mrp_report_bom_structure(self): sword_cyan = self.product_sword.product_variant_ids[0] BomStructureReport = self.env["report.mrp.report_bom_structure"] res = BomStructureReport._get_report_data(self.bom_id.id) self.assertTrue(res["is_variant_applied"]) self.assertEqual(res["lines"]["product"], sword_cyan) self.assertEqual( res["lines"]["components"][0]["line_id"], self.bom_id.bom_line_ids[0].id, ) self.assertEqual( res["lines"]["components"][1]["line_id"], self.bom_id.bom_line_ids[1].id, ) self.assertEqual( res["lines"]["components"][0]["parent_id"], self.bom_id.id, )
41.714286
7,884