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
552
py
PYTHON
15.0
# Copyright 2017 Camptocamp SA # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) { "name": "Connector Tests", "summary": "Automated tests for Connector, do not install.", "version": "15.0.1.0.0", "author": "Camptocamp,Odoo Community Association (OCA)", "license": "LGPL-3", "category": "Hidden", "depends": ["connector"], "website": "https://github.com/OCA/connector", "data": [ "security/ir.model.access.csv", "data/queue_job_function_data.xml", ], "installable": True, }
30.666667
552
2,321
py
PYTHON
15.0
# Copyright 2013-2017 Camptocamp SA # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) import mock from odoo.exceptions import UserError from odoo.addons.component.tests.common import TransactionComponentCase class TestRelatedActionBinding(TransactionComponentCase): """Test Related Actions with Bindings""" def setUp(self): super().setUp() self.backend_record = self.env["test.backend"].create({}) def test_unwrap_binding(self): """Call the unwrap binding related action""" binding = self.env["connector.test.binding"].create( {"backend_id": self.backend_record.id, "external_id": 99} ) job = binding.with_delay().job_related_action_unwrap() db_job = job.db_record() action = db_job.open_related_action() expected = { "name": mock.ANY, "type": "ir.actions.act_window", "view_type": "form", "view_mode": "form", "res_id": binding.odoo_id.id, "res_model": "connector.test.record", } self.assertEqual(action, expected) def test_unwrap_binding_direct_binding(self): """Call the unwrap binding related action""" binding = self.env["no.inherits.binding"].create( {"backend_id": self.backend_record.id, "external_id": 99} ) job = binding.with_delay().job_related_action_unwrap() db_job = job.db_record() action = db_job.open_related_action() expected = { "name": mock.ANY, "type": "ir.actions.act_window", "view_type": "form", "view_mode": "form", "res_id": binding.id, "res_model": "no.inherits.binding", } self.assertEqual(action, expected) def test_unwrap_binding_not_exists(self): """Call the related action on the model on non-existing record""" binding = self.env["connector.test.binding"].create( {"backend_id": self.backend_record.id, "external_id": 99} ) job = binding.with_delay().job_related_action_unwrap() db_job = job.db_record() binding.unlink() with self.assertRaisesRegex(UserError, "No action available for this job"): db_job.open_related_action()
33.157143
2,321
2,136
py
PYTHON
15.0
# Copyright 2013-2017 Camptocamp SA # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) from odoo.addons.component.tests.common import TransactionComponentCase class TestDefaultBinder(TransactionComponentCase): """Test the default binder implementation using Components""" def setUp(self): super().setUp() # create our backend, in case of components, # the version would not be required self.backend_record = self.env["test.backend"].create({}) def test_default_binder(self): """Small scenario with the default binder""" # create a work context with the model we want to work with with self.backend_record.work_on("connector.test.binding") as work: # get our binder component (for the model in whe work context) self.binder = work.component(usage="binder") test_record = self.env["connector.test.record"].create({}) test_binding = self.env["connector.test.binding"].create( {"backend_id": self.backend_record.id, "odoo_id": test_record.id} ) # bind the test binding to external id = 99 self.binder.bind(99, test_binding) # find the odoo binding bound to external record 99 binding = self.binder.to_internal(99) self.assertEqual(binding, test_binding) # find the odoo record bound to external record 99 record = self.binder.to_internal(99, unwrap=True) self.assertEqual(record, test_record) # find the external record bound to odoo binding external_id = self.binder.to_external(test_binding) self.assertEqual(external_id, 99) # find the external record bound to odoo record external_id = self.binder.to_external(test_record, wrap=True) self.assertEqual(external_id, 99) self.assertEqual(self.binder.unwrap_model(), "connector.test.record") # unwrapping the binding should give the same binding self.assertEqual(self.binder.unwrap_binding(test_binding), test_record)
48.545455
2,136
1,924
py
PYTHON
15.0
# Copyright 2016 Camptocamp SA # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) from odoo import fields, models class TestBackend(models.Model): _name = "test.backend" _inherit = ["connector.backend"] _description = "Backends for testing Connector" class ConnectorTestRecord(models.Model): _name = "connector.test.record" _description = "Records for testing Connector" class ConnectorTestBinding(models.Model): _name = "connector.test.binding" _inherit = "external.binding" _inherits = {"connector.test.record": "odoo_id"} _description = "Bindings for testing Connector" backend_id = fields.Many2one( comodel_name="test.backend", string="Backend", required=True, ondelete="restrict", ) external_id = fields.Integer(string="ID on External") odoo_id = fields.Many2one( comodel_name="connector.test.record", string="Test Record", required=True, index=True, ondelete="restrict", ) _sql_constraints = [ ( "test_binding_uniq", "unique(backend_id, external_id)", "A binding already exists for this record", ) ] def job_related_action_unwrap(self): return self class NoInheritsBinding(models.Model): _name = "no.inherits.binding" _inherit = "external.binding" _description = "Bindings without inherit for testing Connector" backend_id = fields.Many2one( comodel_name="test.backend", string="Backend", required=True, ondelete="restrict", ) external_id = fields.Integer(string="ID on External") _sql_constraints = [ ( "test_binding_uniq", "unique(backend_id, external_id)", "A binding already exists for this record", ) ] def job_related_action_unwrap(self): return self
26
1,924
612
py
PYTHON
15.0
# Copyright 2016 Camptocamp SA # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) from odoo.addons.component.core import Component class ConnectorTestBinder(Component): _name = "connector.test.binder" _inherit = ["base.binder"] _apply_on = ["connector.test.binding"] class NoInheritsBinder(Component): _name = "connector.test.no.inherits.binder" _inherit = ["base.binder"] _apply_on = ["no.inherits.binding"] def unwrap_binding(self, binding): raise ValueError("Not an inherits") def unwrap_model(self): raise ValueError("Not an inherits")
27.818182
612
5,990
py
PYTHON
15.0
# Copyright 2017 Camptocamp SA # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) """ Events Internals ================ Core classes for the events system. """ from odoo.addons.component.core import WorkContext class EventWorkContext(WorkContext): """Work context used by the Events internals Should not be used outside of the events internals. The work context to use generally is :class:`odoo.addons.component.core.WorkContext` or your own subclass. The events are a special kind of components because they are not attached to any collection (they can but not the main use case). So the work context must not need to have a collection, but when it has no collection, it must at least have an 'env'. When no collection is provided, the methods to get the Components cannot be used, but :meth:`work_on` can be used to switch back to a :class:`odoo.addons.component.core.WorkContext` with collection. This is needed when one want to get a component for a collection from inside an event listener. """ def __init__( self, model_name=None, collection=None, env=None, components_registry=None, **kwargs ): if not (collection is not None or env): raise ValueError("collection or env is required") if collection and env: # when a collection is used, the env will be the one of # the collection raise ValueError("collection and env cannot both be provided") self.env = env super(EventWorkContext, self).__init__( model_name=model_name, collection=collection, components_registry=components_registry, **kwargs ) if self._env: self._propagate_kwargs.remove("collection") self._propagate_kwargs.append("env") @property def env(self): """Return the current Odoo env""" if self._env: return self._env return super(EventWorkContext, self).env @env.setter def env(self, value): self._env = value @property def collection(self): """Return the current Odoo env""" if self._collection is not None: return self._collection raise ValueError("No collection, it is optional for EventWorkContext") @collection.setter def collection(self, value): self._collection = value def work_on(self, model_name=None, collection=None): """Create a new work context for another model keeping attributes Used when one need to lookup components for another model. Used on an EventWorkContext, it switch back to a normal WorkContext. It means we are inside an event listener, and we want to get a component. We need to set a collection to be able to get components. """ if self._collection is None and collection is None: raise ValueError("you must provide a collection to work with") if collection is not None: if self.env is not collection.env: raise ValueError( "the Odoo env of the collection must be " "the same than the current one" ) kwargs = { attr_name: getattr(self, attr_name) for attr_name in self._propagate_kwargs } kwargs.pop("env", None) if collection is not None: kwargs["collection"] = collection if model_name is not None: kwargs["model_name"] = model_name return WorkContext(**kwargs) def component_by_name(self, name, model_name=None): if self._collection is not None: # switch to a normal WorkContext work = self.work_on(collection=self._collection, model_name=model_name) else: raise TypeError( "Can't be used on an EventWorkContext without collection. " "The collection must be known to find components.\n" "Hint: you can set the collection and get a component with:\n" ">>> work.work_on(collection=self.env[...].browse(...))\n" ">>> work.component_by_name(name, model_name=model_name)" ) return work.component_by_name(name, model_name=model_name) def component(self, usage=None, model_name=None): if self._collection is not None: # switch to a normal WorkContext work = self.work_on(collection=self._collection, model_name=model_name) else: raise TypeError( "Can't be used on an EventWorkContext without collection. " "The collection must be known to find components.\n" "Hint: you can set the collection and get a component with:\n" ">>> work.work_on(collection=self.env[...].browse(...))\n" ">>> work.component(usage=usage, model_name=model_name)" ) return work.component(usage=usage, model_name=model_name) def many_components(self, usage=None, model_name=None): if self._collection is not None: # switch to a normal WorkContext work = self.work_on(collection=self._collection, model_name=model_name) else: raise TypeError( "Can't be used on an EventWorkContext without collection. " "The collection must be known to find components.\n" "Hint: you can set the collection and get a component with:\n" ">>> work.work_on(collection=self.env[...].browse(...))\n" ">>> work.many_components(usage=usage, model_name=model_name)" ) return work.component(usage=usage, model_name=model_name) def __str__(self): return "EventWorkContext({},{})".format( repr(self._env or self._collection), self.model_name )
37.4375
5,990
469
py
PYTHON
15.0
# Copyright 2019 Camptocamp SA # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) { "name": "Components Events", "version": "15.0.1.0.1", "author": "Camptocamp," "Odoo Community Association (OCA)", "website": "https://github.com/OCA/connector", "license": "LGPL-3", "category": "Generic Modules", "depends": ["component"], "external_dependencies": {"python": ["cachetools"]}, "data": [], "installable": True, }
31.266667
469
17,026
py
PYTHON
15.0
# Copyright 2017 Camptocamp SA # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) import unittest import mock from odoo.tests.common import tagged from odoo.addons.component.core import Component from odoo.addons.component.tests.common import ( ComponentRegistryCase, TransactionComponentRegistryCase, ) from odoo.addons.component_event.components.event import skip_if from odoo.addons.component_event.core import EventWorkContext @tagged("standard", "at_install") class TestEventWorkContext(unittest.TestCase): """Test Events Components""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.test_sequence = 0 def setUp(self): super().setUp() self.env = mock.MagicMock(name="env") self.record = mock.MagicMock(name="record") self.components_registry = mock.MagicMock(name="ComponentRegistry") def test_env(self): """WorkContext with env""" work = EventWorkContext( model_name="res.users", env=self.env, components_registry=self.components_registry, ) self.assertEqual(self.env, work.env) self.assertEqual("res.users", work.model_name) with self.assertRaises(ValueError): # pylint: disable=W0104 work.collection # noqa def test_collection(self): """WorkContext with collection""" env = mock.MagicMock(name="env") collection = mock.MagicMock(name="collection") collection.env = env work = EventWorkContext( model_name="res.users", collection=collection, components_registry=self.components_registry, ) self.assertEqual(collection, work.collection) self.assertEqual(env, work.env) self.assertEqual("res.users", work.model_name) def test_env_and_collection(self): """WorkContext with collection and env is forbidden""" env = mock.MagicMock(name="env") collection = mock.MagicMock(name="collection") collection.env = env with self.assertRaises(ValueError): EventWorkContext( model_name="res.users", collection=collection, env=env, components_registry=self.components_registry, ) def test_missing(self): """WorkContext with collection and env is forbidden""" with self.assertRaises(ValueError): EventWorkContext( model_name="res.users", components_registry=self.components_registry ) def test_env_work_on(self): """WorkContext propagated through work_on""" env = mock.MagicMock(name="env") collection = mock.MagicMock(name="collection") collection.env = env work = EventWorkContext( env=env, model_name="res.users", components_registry=self.components_registry, ) work2 = work.work_on(model_name="res.partner", collection=collection) self.assertEqual("WorkContext", work2.__class__.__name__) self.assertEqual(env, work2.env) self.assertEqual("res.partner", work2.model_name) self.assertEqual(self.components_registry, work2.components_registry) with self.assertRaises(ValueError): # pylint: disable=W0104 work.collection # noqa def test_collection_work_on(self): """WorkContext propagated through work_on""" env = mock.MagicMock(name="env") collection = mock.MagicMock(name="collection") collection.env = env work = EventWorkContext( collection=collection, model_name="res.users", components_registry=self.components_registry, ) work2 = work.work_on(model_name="res.partner") self.assertEqual("WorkContext", work2.__class__.__name__) self.assertEqual(collection, work2.collection) self.assertEqual(env, work2.env) self.assertEqual("res.partner", work2.model_name) self.assertEqual(self.components_registry, work2.components_registry) def test_collection_work_on_collection(self): """WorkContext collection changed with work_on""" env = mock.MagicMock(name="env") collection = mock.MagicMock(name="collection") collection.env = env work = EventWorkContext( model_name="res.users", env=env, components_registry=self.components_registry, ) work2 = work.work_on(collection=collection) # when work_on is used inside an event component, we want # to switch back to a normal WorkContext, because we don't # need anymore the EventWorkContext self.assertEqual("WorkContext", work2.__class__.__name__) self.assertEqual(collection, work2.collection) self.assertEqual(env, work2.env) self.assertEqual("res.users", work2.model_name) self.assertEqual(self.components_registry, work2.components_registry) class TestEvent(ComponentRegistryCase): """Test Events Components""" def setUp(self): super(TestEvent, self).setUp() self._setup_registry(self) self._load_module_components("component_event") # get the collecter to notify the event # we don't mind about the collection and the model here, # the events we test are global env = mock.MagicMock() self.work = EventWorkContext( model_name="res.users", env=env, components_registry=self.comp_registry ) self.collecter = self.comp_registry["base.event.collecter"](self.work) def test_event(self): class MyEventListener(Component): _name = "my.event.listener" _inherit = "base.event.listener" def on_record_create(self, recipient, something, fields=None): recipient.append(("OK", something, fields)) MyEventListener._build_component(self.comp_registry) something = object() fields = ["name", "code"] # as there is no return value by the event, we # modify this recipient to check it has been called recipient = [] # collect the event and notify it self.collecter.collect_events("on_record_create").notify( recipient, something, fields=fields ) self.assertEqual([("OK", something, fields)], recipient) def test_collect_several(self): class MyEventListener(Component): _name = "my.event.listener" _inherit = "base.event.listener" def on_record_create(self, recipient, something, fields=None): recipient.append(("OK", something, fields)) class MyOtherEventListener(Component): _name = "my.other.event.listener" _inherit = "base.event.listener" def on_record_create(self, recipient, something, fields=None): recipient.append(("OK", something, fields)) MyEventListener._build_component(self.comp_registry) MyOtherEventListener._build_component(self.comp_registry) something = object() fields = ["name", "code"] # as there is no return value by the event, we # modify this recipient to check it has been called recipient = [] # collect the event and notify them collected = self.collecter.collect_events("on_record_create") self.assertEqual(2, len(collected.events)) collected.notify(recipient, something, fields=fields) self.assertEqual( [("OK", something, fields), ("OK", something, fields)], recipient ) def test_event_cache(self): class MyEventListener(Component): _name = "my.event.listener" _inherit = "base.event.listener" def on_record_create(self): pass MyEventListener._build_component(self.comp_registry) # collect the event collected = self.collecter.collect_events("on_record_create") # CollectedEvents.events contains the collected events self.assertEqual(1, len(collected.events)) event = list(collected.events)[0] self.assertEqual(self.work, event.__self__.work) self.assertEqual(self.work.env, event.__self__.work.env) # build and register a new listener class MyOtherEventListener(Component): _name = "my.other.event.listener" _inherit = "base.event.listener" def on_record_create(self): pass MyOtherEventListener._build_component(self.comp_registry) # get a new collecter and check that we it finds the same # events even if we built a new one: it means the cache works env = mock.MagicMock() work = EventWorkContext( model_name="res.users", env=env, components_registry=self.comp_registry ) collecter = self.comp_registry["base.event.collecter"](work) collected = collecter.collect_events("on_record_create") # CollectedEvents.events contains the collected events self.assertEqual(1, len(collected.events)) event = list(collected.events)[0] self.assertEqual(work, event.__self__.work) self.assertEqual(env, event.__self__.work.env) # if we empty the cache, as it on the class, both collecters # should now find the 2 events collecter._cache.clear() self.comp_registry._cache.clear() # CollectedEvents.events contains the collected events self.assertEqual(2, len(collecter.collect_events("on_record_create").events)) self.assertEqual( 2, len(self.collecter.collect_events("on_record_create").events) ) def test_event_cache_collection(self): class MyEventListener(Component): _name = "my.event.listener" _inherit = "base.event.listener" def on_record_create(self): pass MyEventListener._build_component(self.comp_registry) # collect the event collected = self.collecter.collect_events("on_record_create") # CollectedEvents.events contains the collected events self.assertEqual(1, len(collected.events)) # build and register a new listener class MyOtherEventListener(Component): _name = "my.other.event.listener" _inherit = "base.event.listener" _collection = "base.collection" def on_record_create(self): pass MyOtherEventListener._build_component(self.comp_registry) # get a new collecter and check that we it finds the same # events even if we built a new one: it means the cache works collection = mock.MagicMock(name="base.collection") collection._name = "base.collection" collection.env = mock.MagicMock() work = EventWorkContext( model_name="res.users", collection=collection, components_registry=self.comp_registry, ) collecter = self.comp_registry["base.event.collecter"](work) collected = collecter.collect_events("on_record_create") # for a different collection, we should not have the same # cache entry self.assertEqual(2, len(collected.events)) def test_event_cache_model_name(self): class MyEventListener(Component): _name = "my.event.listener" _inherit = "base.event.listener" def on_record_create(self): pass MyEventListener._build_component(self.comp_registry) # collect the event collected = self.collecter.collect_events("on_record_create") # CollectedEvents.events contains the collected events self.assertEqual(1, len(collected.events)) # build and register a new listener class MyOtherEventListener(Component): _name = "my.other.event.listener" _inherit = "base.event.listener" _apply_on = ["res.country"] def on_record_create(self): pass MyOtherEventListener._build_component(self.comp_registry) # get a new collecter and check that we it finds the same # events even if we built a new one: it means the cache works env = mock.MagicMock() work = EventWorkContext( model_name="res.country", env=env, components_registry=self.comp_registry ) collecter = self.comp_registry["base.event.collecter"](work) collected = collecter.collect_events("on_record_create") # for a different collection, we should not have the same # cache entry self.assertEqual(2, len(collected.events)) def test_skip_if(self): class MyEventListener(Component): _name = "my.event.listener" _inherit = "base.event.listener" def on_record_create(self, msg): pass class MyOtherEventListener(Component): _name = "my.other.event.listener" _inherit = "base.event.listener" @skip_if(lambda self, msg: msg == "foo") def on_record_create(self, msg): raise AssertionError() self._build_components(MyEventListener, MyOtherEventListener) # collect the event and notify it collected = self.collecter.collect_events("on_record_create") self.assertEqual(2, len(collected.events)) collected.notify("foo") class TestEventFromModel(TransactionComponentRegistryCase): """Test Events Components from Models""" def setUp(self): super(TestEventFromModel, self).setUp() self._setup_registry(self) self._load_module_components("component_event") def test_event_from_model(self): class MyEventListener(Component): _name = "my.event.listener" _inherit = "base.event.listener" def on_foo(self, record, name): record.name = name MyEventListener._build_component(self.comp_registry) partner = self.env["res.partner"].create({"name": "test"}) # Normally you would not pass a components_registry, # this is for the sake of the test, letting it empty # will use the global registry. # In a real code it would look like: # partner._event('on_foo').notify('bar') events = partner._event("on_foo", components_registry=self.comp_registry) events.notify(partner, "bar") self.assertEqual("bar", partner.name) def test_event_filter_on_model(self): class GlobalListener(Component): _name = "global.event.listener" _inherit = "base.event.listener" def on_foo(self, record, name): record.name = name class PartnerListener(Component): _name = "partner.event.listener" _inherit = "base.event.listener" _apply_on = ["res.partner"] def on_foo(self, record, name): record.ref = name class UserListener(Component): _name = "user.event.listener" _inherit = "base.event.listener" _apply_on = ["res.users"] def on_foo(self, record, name): raise AssertionError() self._build_components(GlobalListener, PartnerListener, UserListener) partner = self.env["res.partner"].create({"name": "test"}) partner._event("on_foo", components_registry=self.comp_registry).notify( partner, "bar" ) self.assertEqual("bar", partner.name) self.assertEqual("bar", partner.ref) def test_event_filter_on_collection(self): class GlobalListener(Component): _name = "global.event.listener" _inherit = "base.event.listener" def on_foo(self, record, name): record.name = name class PartnerListener(Component): _name = "partner.event.listener" _inherit = "base.event.listener" _collection = "collection.base" def on_foo(self, record, name): record.ref = name class UserListener(Component): _name = "user.event.listener" _inherit = "base.event.listener" _collection = "magento.backend" def on_foo(self, record, name): raise AssertionError() self._build_components(GlobalListener, PartnerListener, UserListener) partner = self.env["res.partner"].create({"name": "test"}) events = partner._event( "on_foo", collection=self.env["collection.base"], components_registry=self.comp_registry, ) events.notify(partner, "bar") self.assertEqual("bar", partner.name) self.assertEqual("bar", partner.ref)
36.852814
17,026
4,127
py
PYTHON
15.0
# Copyright 2017 Camptocamp SA # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) """ Base Model ========== Extend the 'base' Odoo Model to add Events related features. """ from odoo import api, models from odoo.addons.component.core import _component_databases from ..components.event import CollectedEvents from ..core import EventWorkContext class Base(models.AbstractModel): """The base model, which is implicitly inherited by all models. Add an :meth:`_event` method to all Models. This method allows to trigger events. It also notifies the following events: * ``on_record_create(self, record, fields=None)`` * ``on_record_write(self, record, fields=none)`` * ``on_record_unlink(self, record)`` ``on_record_unlink`` is notified just *before* the unlink is done. """ _inherit = "base" def _event(self, name, collection=None, components_registry=None): """Collect events for notifications Usage:: def button_do_something(self): for record in self: # do something self._event('on_do_something').notify('something') With this line, every listener having a ``on_do_something`` method with be called and receive 'something' as argument. See: :mod:`..components.event` :param name: name of the event, start with 'on_' :param collection: optional collection to filter on, only listeners with similar ``_collection`` will be notified :param components_registry: component registry for lookups, mainly used for tests :type components_registry: :class:`odoo.addons.components.core.ComponentRegistry` """ dbname = self.env.cr.dbname components_registry = self.env.context.get( "components_registry", components_registry ) comp_registry = components_registry or _component_databases.get(dbname) if not comp_registry or not comp_registry.ready: # No event should be triggered before the registry has been loaded # This is a very special case, when the odoo registry is being # built, it calls odoo.modules.loading.load_modules(). # This function might trigger events (by writing on records, ...). # But at this point, the component registry is not guaranteed # to be ready, and anyway we should probably not trigger events # during the initialization. Hence we return an empty list of # events, the 'notify' calls will do nothing. return CollectedEvents([]) if not comp_registry.get("base.event.collecter"): return CollectedEvents([]) model_name = self._name if collection is not None: work = EventWorkContext( collection=collection, model_name=model_name, components_registry=components_registry, ) else: work = EventWorkContext( env=self.env, model_name=model_name, components_registry=components_registry, ) collecter = work._component_class_by_name("base.event.collecter")(work) return collecter.collect_events(name) @api.model_create_multi def create(self, vals_list): records = super(Base, self).create(vals_list) for idx, vals in enumerate(vals_list): fields = list(vals.keys()) self._event("on_record_create").notify(records[idx], fields=fields) return records def write(self, vals): result = super(Base, self).write(vals) fields = list(vals.keys()) for record in self: self._event("on_record_write").notify(record, fields=fields) return result def unlink(self): for record in self: self._event("on_record_unlink").notify(record) result = super(Base, self).unlink() return result
34.680672
4,127
9,356
py
PYTHON
15.0
# Copyright 2017 Camptocamp SA # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) """ Events ====== Events are a notification system. On one side, one or many listeners await for an event to happen. On the other side, when such event happen, a notification is sent to the listeners. An example of event is: 'when a record has been created'. The event system allows to write the notification code in only one place, in one Odoo addon, and to write as many listeners as we want, in different places, different addons. We'll see below how the ``on_record_create`` is implemented. Notifier -------- The first thing is to find where/when the notification should be sent. For the creation of a record, it is in :meth:`odoo.models.BaseModel.create`. We can inherit from the `'base'` model to add this line: :: class Base(models.AbstractModel): _inherit = 'base' @api.model def create(self, vals): record = super(Base, self).create(vals) self._event('on_record_create').notify(record, fields=vals.keys()) return record The :meth:`..models.base.Base._event` method has been added to the `'base'` model, so an event can be notified from any model. The :meth:`CollectedEvents.notify` method triggers the event and forward the arguments to the listeners. This should be done only once. See :class:`..models.base.Base` for a list of events that are implemented in the `'base'` model. Listeners --------- Listeners are Components that respond to the event names. The components must have a ``_usage`` equals to ``'event.listener'``, but it doesn't to be set manually if the component inherits from ``'base.event.listener'`` Here is how we would log something each time a record is created:: class MyEventListener(Component): _name = 'my.event.listener' _inherit = 'base.event.listener' def on_record_create(self, record, fields=None): _logger.info("%r has been created", record) Many listeners such as this one could be added for the same event. Collection and models --------------------- In the example above, the listeners is global. It will be executed for any model and collection. You can also restrict a listener to only a collection or model, using the ``_collection`` or ``_apply_on`` attributes. :: class MyEventListener(Component): _name = 'my.event.listener' _inherit = 'base.event.listener' _collection = 'magento.backend' def on_record_create(self, record, fields=None): _logger.info("%r has been created", record) class MyModelEventListener(Component): _name = 'my.event.listener' _inherit = 'base.event.listener' _apply_on = ['res.users'] def on_record_create(self, record, fields=None): _logger.info("%r has been created", record) If you want an event to be restricted to a collection, the notification must also precise the collection, otherwise all listeners will be executed:: collection = self.env['magento.backend'] self._event('on_foo_created', collection=collection).notify(record, vals) An event can be skipped based on a condition evaluated from the notified arguments. See :func:`skip_if` """ import logging import operator from collections import defaultdict from functools import wraps # pylint: disable=W7950 from odoo.addons.component.core import AbstractComponent, Component _logger = logging.getLogger(__name__) try: from cachetools import LRUCache, cachedmethod except ImportError: _logger.debug("Cannot import 'cachetools'.") __all__ = ["skip_if"] # Number of items we keep in LRU cache when we collect the events. # 1 item means: for an event name, model_name, collection, return # the event methods DEFAULT_EVENT_CACHE_SIZE = 512 def skip_if(cond): """Decorator allowing to skip an event based on a condition The condition is a python lambda expression, which takes the same arguments than the event. Example:: @skip_if(lambda self, *args, **kwargs: self.env.context.get('connector_no_export')) def on_record_write(self, record, fields=None): _logger('I'll delay a job, but only if we didn't disabled ' ' the export with a context key') record.with_delay().export_record() @skip_if(lambda self, record, kind: kind == 'complete') def on_record_write(self, record, kind): _logger("I'll delay a job, but only if the kind is 'complete'") record.with_delay().export_record() """ def skip_if_decorator(func): @wraps(func) def func_wrapper(*args, **kwargs): if cond(*args, **kwargs): return else: return func(*args, **kwargs) return func_wrapper return skip_if_decorator class CollectedEvents: """Event methods ready to be notified This is a rather internal class. An instance of this class is prepared by the :class:`EventCollecter` when we need to notify the listener that the event has been triggered. :meth:`EventCollecter.collect_events` collects the events, feed them to the instance, so we can use the :meth:`notify` method that will forward the arguments and keyword arguments to the listeners of the event. :: >>> # collecter is an instance of CollectedEvents >>> collecter.collect_events('on_record_create').notify(something) """ def __init__(self, events): self.events = events def notify(self, *args, **kwargs): """Forward the arguments to every listeners of an event""" for event in self.events: event(*args, **kwargs) class EventCollecter(Component): """Component that collects the event from an event name For doing so, it searches all the components that respond to the ``event.listener`` ``_usage`` and having an event of the same name. Then it feeds the events to an instance of :class:`EventCollecter` and return it to the caller. It keeps the results in a cache, the Component is rebuilt when the Odoo's registry is rebuilt, hence the cache is cleared as well. An event always starts with ``on_``. Note that the special :class:`odoo.addons.component_event.core.EventWorkContext` class should be used for this Component, because it can work without a collection. It is used by :meth:`odoo.addons.component_event.models.base.Base._event`. """ _name = "base.event.collecter" @classmethod def _complete_component_build(cls): """Create a cache on the class when the component is built""" super(EventCollecter, cls)._complete_component_build() # the _cache being on the component class, which is # dynamically rebuild when odoo registry is rebuild, we # are sure that the result is always the same for a lookup # until the next rebuild of odoo's registry cls._cache = LRUCache(maxsize=DEFAULT_EVENT_CACHE_SIZE) return def _collect_events(self, name): collection_name = None if self.work._collection is not None: collection_name = self.work.collection._name return self._collect_events_cached(collection_name, self.work.model_name, name) @cachedmethod(operator.attrgetter("_cache")) def _collect_events_cached(self, collection_name, model_name, name): events = defaultdict(set) component_classes = self.work.components_registry.lookup( collection_name=collection_name, usage="event.listener", model_name=model_name, ) for cls in component_classes: if cls.has_event(name): events[cls].add(name) return events def _init_collected_events(self, class_events): events = set() for cls, names in class_events.items(): for name in names: component = cls(self.work) events.add(getattr(component, name)) return events def collect_events(self, name): """Collect the events of a given name""" if not name.startswith("on_"): raise ValueError("an event name always starts with 'on_'") events = self._init_collected_events(self._collect_events(name)) return CollectedEvents(events) class EventListener(AbstractComponent): """Base Component for the Event listeners Events must be methods starting with ``on_``. Example: :class:`RecordsEventListener` """ _name = "base.event.listener" _usage = "event.listener" @classmethod def has_event(cls, name): """Indicate if the class has an event of this name""" return name in cls._events @classmethod def _build_event_listener_component(cls): """Make a list of events listeners for this class""" events = set() if not cls._abstract: for attr_name in dir(cls): if attr_name.startswith("on_"): events.add(attr_name) cls._events = events @classmethod def _complete_component_build(cls): super(EventListener, cls)._complete_component_build() cls._build_event_listener_component() return
31.395973
9,356
719
py
PYTHON
15.0
import setuptools with open('VERSION.txt', 'r') as f: version = f.read().strip() setuptools.setup( name="odoo-addons-oca-connector", description="Meta package for oca-connector Odoo addons", version=version, install_requires=[ 'odoo-addon-component>=15.0dev,<15.1dev', 'odoo-addon-component_event>=15.0dev,<15.1dev', 'odoo-addon-connector>=15.0dev,<15.1dev', 'odoo-addon-connector_base_product>=15.0dev,<15.1dev', 'odoo-addon-test_component>=15.0dev,<15.1dev', 'odoo-addon-test_connector>=15.0dev,<15.1dev', ], classifiers=[ 'Programming Language :: Python', 'Framework :: Odoo', 'Framework :: Odoo :: 15.0', ] )
31.26087
719
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
367
py
PYTHON
15.0
# Copyright 2017 Camptocamp SA # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) class ComponentException(Exception): """Base Exception for the components""" class NoComponentError(ComponentException): """No component has been found""" class SeveralComponentError(ComponentException): """More than one component have been found"""
26.214286
367
34,488
py
PYTHON
15.0
# Copyright 2017 Camptocamp SA # Copyright 2017 Odoo # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) """ Core ==== Core classes for the components. The most common classes used publicly are: * :class:`Component` * :class:`AbstractComponent` * :class:`WorkContext` """ import logging import operator from collections import OrderedDict, defaultdict from odoo import models from odoo.tools import LastOrderedSet, OrderedSet from .exception import NoComponentError, SeveralComponentError _logger = logging.getLogger(__name__) try: from cachetools import LRUCache, cachedmethod except ImportError: _logger.debug("Cannot import 'cachetools'.") # The Cache size represents the number of items, so the number # of components (include abstract components) we will keep in the LRU # cache. We would need stats to know what is the average but this is a bit # early. DEFAULT_CACHE_SIZE = 512 # this is duplicated from odoo.models.MetaModel._get_addon_name() which we # unfortunately can't use because it's an instance method and should have been # a @staticmethod def _get_addon_name(full_name): # The (Odoo) module name can be in the ``odoo.addons`` namespace # or not. For instance, module ``sale`` can be imported as # ``odoo.addons.sale`` (the right way) or ``sale`` (for backward # compatibility). module_parts = full_name.split(".") if len(module_parts) > 2 and module_parts[:2] == ["odoo", "addons"]: addon_name = full_name.split(".")[2] else: addon_name = full_name.split(".")[0] return addon_name class ComponentDatabases(dict): """Holds a registry of components for each database""" class ComponentRegistry: """Store all the components and allow to find them using criteria The key is the ``_name`` of the components. This is an OrderedDict, because we want to keep the registration order of the components, addons loaded first have their components found first. The :attr:`ready` attribute must be set to ``True`` when all the components are loaded. """ def __init__(self, cachesize=DEFAULT_CACHE_SIZE): self._cache = LRUCache(maxsize=cachesize) self._components = OrderedDict() self._loaded_modules = set() self.ready = False def __getitem__(self, key): return self._components[key] def __setitem__(self, key, value): self._components[key] = value def __contains__(self, key): return key in self._components def get(self, key, default=None): return self._components.get(key, default) def __iter__(self): return iter(self._components) def load_components(self, module): if module in self._loaded_modules: return for component_class in MetaComponent._modules_components[module]: component_class._build_component(self) self._loaded_modules.add(module) @cachedmethod(operator.attrgetter("_cache")) def lookup(self, collection_name=None, usage=None, model_name=None): """Find and return a list of components for a usage If a component is not registered in a particular collection (no ``_collection``), it will be returned in any case (as far as the ``usage`` and ``model_name`` match). This is useful to share generic components across different collections. If no collection name is given, components from any collection will be returned. Then, the components of a collection are filtered by usage and/or model. The ``_usage`` is mandatory on the components. When the ``_model_name`` is empty, it means it can be used for every models, and it will ignore the ``model_name`` argument. The abstract components are never returned. This is a rather low-level function, usually you will use the high-level :meth:`AbstractComponent.component`, :meth:`AbstractComponent.many_components` or even :meth:`AbstractComponent.component_by_name`. :param collection_name: the name of the collection the component is registered into. :param usage: the usage of component we are looking for :param model_name: filter on components that apply on this model """ # keep the order so addons loaded first have components used first candidates = ( component for component in self._components.values() if not component._abstract ) if collection_name is not None: candidates = ( component for component in candidates if ( component._collection == collection_name or component._collection is None ) ) if usage is not None: candidates = ( component for component in candidates if component._usage == usage ) if model_name is not None: candidates = ( c for c in candidates if c.apply_on_models is None or model_name in c.apply_on_models ) return list(candidates) # We will store a ComponentRegistry per database here, # it will be cleared and updated when the odoo's registry is rebuilt _component_databases = ComponentDatabases() class WorkContext: """Transport the context required to work with components It is propagated through all the components, so any data or instance (like a random RPC client) that need to be propagated transversally to the components should be kept here. Including: .. attribute:: model_name Name of the model we are working with. It means that any lookup for a component will be done for this model. It also provides a shortcut as a `model` attribute to use directly with the Odoo model from the components .. attribute:: collection The collection we are working with. The collection is an Odoo Model that inherit from 'collection.base'. The collection attribute can be a record or an "empty" model. .. attribute:: model Odoo Model for ``model_name`` with the same Odoo :class:`~odoo.api.Environment` than the ``collection`` attribute. This is also the entrypoint to work with the components. :: collection = self.env['my.collection'].browse(1) work = WorkContext(model_name='res.partner', collection=collection) component = work.component(usage='record.importer') Usually you will use the context manager on the ``collection.base`` Model: :: collection = self.env['my.collection'].browse(1) with collection.work_on('res.partner') as work: component = work.component(usage='record.importer') It supports any arbitrary keyword arguments that will become attributes of the instance, and be propagated throughout all the components. :: collection = self.env['my.collection'].browse(1) with collection.work_on('res.partner', hello='world') as work: assert work.hello == 'world' When you need to work on a different model, a new work instance will be created for you when you are using the high-level API. This is what happens under the hood: :: collection = self.env['my.collection'].browse(1) with collection.work_on('res.partner', hello='world') as work: assert work.model_name == 'res.partner' assert work.hello == 'world' work2 = work.work_on('res.users') # => spawn a new WorkContext with a copy of the attributes assert work2.model_name == 'res.users' assert work2.hello == 'world' """ def __init__( self, model_name=None, collection=None, components_registry=None, **kwargs ): self.collection = collection self.model_name = model_name self.model = self.env[model_name] # lookup components in an alternative registry, used by the tests if components_registry is not None: self.components_registry = components_registry else: dbname = self.env.cr.dbname try: self.components_registry = _component_databases[dbname] except KeyError: _logger.error( "No component registry for database %s. " "Probably because the Odoo registry has not been built " "yet.", dbname, ) raise self._propagate_kwargs = ["collection", "model_name", "components_registry"] for attr_name, value in kwargs.items(): setattr(self, attr_name, value) self._propagate_kwargs.append(attr_name) @property def env(self): """Return the current Odoo env This is the environment of the current collection. """ return self.collection.env def work_on(self, model_name=None, collection=None): """Create a new work context for another model keeping attributes Used when one need to lookup components for another model. """ kwargs = { attr_name: getattr(self, attr_name) for attr_name in self._propagate_kwargs } if collection is not None: kwargs["collection"] = collection if model_name is not None: kwargs["model_name"] = model_name return self.__class__(**kwargs) def _component_class_by_name(self, name): components_registry = self.components_registry component_class = components_registry.get(name) if not component_class: raise NoComponentError("No component with name '%s' found." % name) return component_class def component_by_name(self, name, model_name=None): """Return a component by its name If the component exists, an instance of it will be returned, initialized with the current :class:`WorkContext`. A :exc:`odoo.addons.component.exception.NoComponentError` is raised if: * no component with this name exists * the ``_apply_on`` of the found component does not match with the current working model In the latter case, it can be an indication that you need to switch to a different model, you can do so by providing the ``model_name`` argument. """ if isinstance(model_name, models.BaseModel): model_name = model_name._name component_class = self._component_class_by_name(name) work_model = model_name or self.model_name if ( component_class._collection and self.collection._name != component_class._collection ): raise NoComponentError( "Component with name '%s' can't be used for collection '%s'." % (name, self.collection._name) ) if ( component_class.apply_on_models and work_model not in component_class.apply_on_models ): if len(component_class.apply_on_models) == 1: hint_models = "'{}'".format(component_class.apply_on_models[0]) else: hint_models = "<one of {!r}>".format(component_class.apply_on_models) raise NoComponentError( "Component with name '%s' can't be used for model '%s'.\n" "Hint: you might want to use: " "component_by_name('%s', model_name=%s)" % (name, work_model, name, hint_models) ) if work_model == self.model_name: work_context = self else: work_context = self.work_on(model_name) return component_class(work_context) def _lookup_components(self, usage=None, model_name=None, **kw): component_classes = self.components_registry.lookup( self.collection._name, usage=usage, model_name=model_name ) matching_components = [] for cls in component_classes: try: matching = cls._component_match( self, usage=usage, model_name=model_name, **kw ) except TypeError as err: # Backward compat _logger.info(str(err)) _logger.info( "The signature of %s._component_match has changed. " "Please, adapt your code as " "(self, usage=usage, model_name=model_name, **kw)", cls.__name__, ) matching = cls._component_match(self) if matching: matching_components.append(cls) return matching_components def _filter_components_by_collection(self, component_classes): return [c for c in component_classes if c._collection == self.collection._name] def _filter_components_by_model(self, component_classes, model_name): return [ c for c in component_classes if c.apply_on_models and model_name in c.apply_on_models ] def _ensure_model_name(self, model_name): """Make sure model name is a string or fallback to current ctx value.""" if isinstance(model_name, models.BaseModel): model_name = model_name._name return model_name or self.model_name def _matching_components(self, usage=None, model_name=None, **kw): """Retrieve matching components and their work context.""" component_classes = self._lookup_components( usage=usage, model_name=model_name, **kw ) if model_name == self.model_name: work_context = self else: work_context = self.work_on(model_name) return component_classes, work_context def component(self, usage=None, model_name=None, **kw): """Find a component by usage and model for the current collection It searches a component using the rules of :meth:`ComponentRegistry.lookup`. When a component is found, it initialize it with the current :class:`WorkContext` and returned. A component with a ``_apply_on`` matching the asked ``model_name`` takes precedence over a generic component without ``_apply_on``. A component with a ``_collection`` matching the current collection takes precedence over a generic component without ``_collection``. This behavior allows to define generic components across collections and/or models and override them only for a particular collection and/or model. A :exc:`odoo.addons.component.exception.SeveralComponentError` is raised if more than one component match for the provided ``usage``/``model_name``. A :exc:`odoo.addons.component.exception.NoComponentError` is raised if no component is found for the provided ``usage``/``model_name``. """ model_name = self._ensure_model_name(model_name) component_classes, work_context = self._matching_components( usage=usage, model_name=model_name, **kw ) if not component_classes: raise NoComponentError( "No component found for collection '%s', " "usage '%s', model_name '%s'." % (self.collection._name, usage, model_name) ) elif len(component_classes) > 1: # If we have more than one component, try to find the one # specifically linked to the collection... component_classes = self._filter_components_by_collection(component_classes) if len(component_classes) > 1: # ... or try to find the one specifically linked to the model component_classes = self._filter_components_by_model( component_classes, model_name ) if len(component_classes) != 1: raise SeveralComponentError( "Several components found for collection '%s', " "usage '%s', model_name '%s'. Found: %r" % ( self.collection._name, usage or "", model_name or "", component_classes, ) ) return component_classes[0](work_context) def many_components(self, usage=None, model_name=None, **kw): """Find many components by usage and model for the current collection It searches a component using the rules of :meth:`ComponentRegistry.lookup`. When components are found, they initialized with the current :class:`WorkContext` and returned as a list. If no component is found, an empty list is returned. """ model_name = self._ensure_model_name(model_name) component_classes, work_context = self._matching_components( usage=usage, model_name=model_name, **kw ) return [comp(work_context) for comp in component_classes] def __str__(self): return "WorkContext({}, {})".format(self.model_name, repr(self.collection)) __repr__ = __str__ class MetaComponent(type): """Metaclass for Components Every new :class:`Component` will be added to ``_modules_components``, that will be used by the component builder. """ _modules_components = defaultdict(list) def __init__(cls, name, bases, attrs): if not cls._register: cls._register = True super().__init__(name, bases, attrs) return # If components are declared in tests, exclude them from the # "components of the addon" list. If not, when we use the # "load_components" method, all the test components would be loaded. # This should never be an issue when running the app normally, as the # Python tests should never be executed. But this is an issue when a # test creates a test components for the purpose of the test, then a # second tests uses the "load_components" to load all the addons of the # module: it will load the component of the previous test. if "tests" in cls.__module__.split("."): return if not hasattr(cls, "_module"): cls._module = _get_addon_name(cls.__module__) cls._modules_components[cls._module].append(cls) @property def apply_on_models(cls): # None means all models if cls._apply_on is None: return None # always return a list, used for the lookup elif isinstance(cls._apply_on, str): return [cls._apply_on] return cls._apply_on class AbstractComponent(metaclass=MetaComponent): """Main Component Model All components have a Python inheritance either on :class:`AbstractComponent` or either on :class:`Component`. Abstract Components will not be returned by lookups on components, however they can be used as a base for other Components through inheritance (using ``_inherit``). Inheritance mechanism The inheritance mechanism is like the Odoo's one for Models. Each component has a ``_name``. This is the absolute minimum in a Component class. :: class MyComponent(Component): _name = 'my.component' def speak(self, message): print message Every component implicitly inherit from the `'base'` component. There are two close but distinct inheritance types, which look familiar if you already know Odoo. The first uses ``_inherit`` with an existing name, the name of the component we want to extend. With the following example, ``my.component`` is now able to speak and to yell. :: class MyComponent(Component): # name of the class does not matter _inherit = 'my.component' def yell(self, message): print message.upper() The second has a different ``_name``, it creates a new component, including the behavior of the inherited component, but without modifying it. In the following example, ``my.component`` is still able to speak and to yell (brough by the previous inherit), but not to sing. ``another.component`` is able to speak, to yell and to sing. :: class AnotherComponent(Component): _name = 'another.component' _inherit = 'my.component' def sing(self, message): print message.upper() Registration and lookups It is handled by 3 attributes on the class: _collection The name of the collection where we want to register the component. This is not strictly mandatory as a component can be shared across several collections. But usually, you want to set a collection to segregate the components for a domain. A collection can be for instance ``magento.backend``. It is also the name of a model that inherits from ``collection.base``. See also :class:`~WorkContext` and :class:`~odoo.addons.component.models.collection.Collection`. _apply_on List of names or name of the Odoo model(s) for which the component can be used. When not set, the component can be used on any model. _usage The collection and the model (``_apply_on``) will help to filter the candidate components according to our working context (e.g. I'm working on ``magento.backend`` with the model ``magento.res.partner``). The usage will define **what** kind of task the component we are looking for serves to. For instance, it might be ``record.importer``, ``export.mapper```... but you can be as creative as you want. Now, to get a component, you'll likely use :meth:`WorkContext.component` when you start to work with components in your flow, but then from within your components, you are more likely to use one of: * :meth:`component` * :meth:`many_components` * :meth:`component_by_name` (more rarely though) Declaration of some Components can look like:: class FooBar(models.Model): _name = 'foo.bar.collection' _inherit = 'collection.base' # this inherit is required class FooBarBase(AbstractComponent): _name = 'foo.bar.base' _collection = 'foo.bar.collection' # name of the model above class Foo(Component): _name = 'foo' _inherit = 'foo.bar.base' # we will inherit the _collection _apply_on = 'res.users' _usage = 'speak' def utter(self, message): print message class Bar(Component): _name = 'bar' _inherit = 'foo.bar.base' # we will inherit the _collection _apply_on = 'res.users' _usage = 'yell' def utter(self, message): print message.upper() + '!!!' class Vocalizer(Component): _name = 'vocalizer' _inherit = 'foo.bar.base' _usage = 'vocalizer' # can be used for any model def vocalize(action, message): self.component(usage=action).utter(message) And their usage:: >>> coll = self.env['foo.bar.collection'].browse(1) >>> with coll.work_on('res.users') as work: ... vocalizer = work.component(usage='vocalizer') ... vocalizer.vocalize('speak', 'hello world') ... hello world ... vocalizer.vocalize('yell', 'hello world') HELLO WORLD!!! Hints: * If you want to create components without ``_apply_on``, choose a ``_usage`` that will not conflict other existing components. * Unless this is what you want and in that case you use :meth:`many_components` which will return all components for a usage with a matching or a not set ``_apply_on``. * It is advised to namespace the names of the components (e.g. ``magento.xxx``) to prevent conflicts between addons. """ _register = False _abstract = True # used for inheritance _name = None #: Name of the component #: Name or list of names of the component(s) to inherit from _inherit = None #: name of the collection to subscribe in _collection = None #: List of models on which the component can be applied. #: None means any Model, can be a list ['res.users', ...] _apply_on = None #: Component purpose ('import.mapper', ...). _usage = None def __init__(self, work_context): super().__init__() self.work = work_context @classmethod def _component_match(cls, work, usage=None, model_name=None, **kw): """Evaluated on candidate components When a component lookup is done and candidate(s) have been found for a usage, a final call is done on this method. If the method return False, the candidate component is ignored. It can be used for instance to dynamically choose a component according to a value in the :class:`WorkContext`. Beware, if the lookups from usage, model and collection are cached, the calls to :meth:`_component_match` are executed each time we get components. Heavy computation should be avoided. :param work: the :class:`WorkContext` we are working with """ return True @property def collection(self): """Collection we are working with""" return self.work.collection @property def env(self): """Current Odoo environment, the one of the collection record""" return self.work.env @property def model(self): """The model instance we are working with""" return self.work.model def component_by_name(self, name, model_name=None): """Return a component by its name Shortcut to meth:`~WorkContext.component_by_name` """ return self.work.component_by_name(name, model_name=model_name) def component(self, usage=None, model_name=None, **kw): """Return a component Shortcut to meth:`~WorkContext.component` """ return self.work.component(usage=usage, model_name=model_name, **kw) def many_components(self, usage=None, model_name=None, **kw): """Return several components Shortcut to meth:`~WorkContext.many_components` """ return self.work.many_components(usage=usage, model_name=model_name, **kw) def __str__(self): return "Component(%s)" % self._name __repr__ = __str__ @classmethod def _build_component(cls, registry): """Instantiate a given Component in the components registry. This method is called at the end of the Odoo's registry build. The caller is :meth:`component.builder.ComponentBuilder.load_components`. It generates new classes, which will be the Component classes we will be using. The new classes are generated following the inheritance of ``_inherit``. It ensures that the ``__bases__`` of the generated Component classes follow the ``_inherit`` chain. Once a Component class is created, it adds it in the Component Registry (:class:`ComponentRegistry`), so it will be available for lookups. At the end of new class creation, a hook method :meth:`_complete_component_build` is called, so you can customize further the created components. An example can be found in :meth:`odoo.addons.connector.components.mapper.Mapper._complete_component_build` The following code is roughly the same than the Odoo's one for building Models. """ # In the simplest case, the component's registry class inherits from # cls and the other classes that define the component in a flat # hierarchy. The registry contains the instance ``component`` (on the # left). Its class, ``ComponentClass``, carries inferred metadata that # is shared between all the component's instances for this registry # only. # # class A1(Component): Component # _name = 'a' / | \ # A3 A2 A1 # class A2(Component): \ | / # _inherit = 'a' ComponentClass # # class A3(Component): # _inherit = 'a' # # When a component is extended by '_inherit', its base classes are # modified to include the current class and the other inherited # component classes. # Note that we actually inherit from other ``ComponentClass``, so that # extensions to an inherited component are immediately visible in the # current component class, like in the following example: # # class A1(Component): # _name = 'a' Component # / / \ \ # class B1(Component): / A2 A1 \ # _name = 'b' / \ / \ # B2 ComponentA B1 # class B2(Component): \ | / # _name = 'b' \ | / # _inherit = ['b', 'a'] \ | / # ComponentB # class A2(Component): # _inherit = 'a' # determine inherited components parents = cls._inherit if isinstance(parents, str): parents = [parents] elif parents is None: parents = [] if cls._name in registry and not parents: raise TypeError( "Component %r (in class %r) already exists. " "Consider using _inherit instead of _name " "or using a different _name." % (cls._name, cls) ) # determine the component's name name = cls._name or (len(parents) == 1 and parents[0]) if not name: raise TypeError("Component %r must have a _name" % cls) # all components except 'base' implicitly inherit from 'base' if name != "base": parents = list(parents) + ["base"] # create or retrieve the component's class if name in parents: if name not in registry: raise TypeError("Component %r does not exist in registry." % name) ComponentClass = registry[name] ComponentClass._build_component_check_base(cls) check_parent = ComponentClass._build_component_check_parent else: ComponentClass = type( name, (AbstractComponent,), { "_name": name, "_register": False, # names of children component "_inherit_children": OrderedSet(), }, ) check_parent = cls._build_component_check_parent # determine all the classes the component should inherit from bases = LastOrderedSet([cls]) for parent in parents: if parent not in registry: raise TypeError( "Component %r inherits from non-existing component %r." % (name, parent) ) parent_class = registry[parent] if parent == name: for base in parent_class.__bases__: bases.add(base) else: check_parent(cls, parent_class) bases.add(parent_class) parent_class._inherit_children.add(name) ComponentClass.__bases__ = tuple(bases) ComponentClass._complete_component_build() registry[name] = ComponentClass return ComponentClass @classmethod def _build_component_check_base(cls, extend_cls): """Check whether ``cls`` can be extended with ``extend_cls``.""" if cls._abstract and not extend_cls._abstract: msg = ( "%s transforms the abstract component %r into a " "non-abstract component. " "That class should either inherit from AbstractComponent, " "or set a different '_name'." ) raise TypeError(msg % (extend_cls, cls._name)) @classmethod def _build_component_check_parent(component_class, cls, parent_class): # noqa: B902 """Check whether ``model_class`` can inherit from ``parent_class``.""" if component_class._abstract and not parent_class._abstract: msg = ( "In %s, the abstract Component %r cannot inherit " "from the non-abstract Component %r." ) raise TypeError(msg % (cls, component_class._name, parent_class._name)) @classmethod def _complete_component_build(cls): """Complete build of the new component class After the component has been built from its bases, this method is called, and can be used to customize the class before it can be used. Nothing is done in the base Component, but a Component can inherit the method to add its own behavior. """ class Component(AbstractComponent): """Concrete Component class This is the class you inherit from when you want your component to be registered in the component collections. Look in :class:`AbstractComponent` for more details. """ _register = False _abstract = False
36.885561
34,488
3,670
py
PYTHON
15.0
# Copyright 2019 Camptocamp SA # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) """ Components Builder ================== Build the components at the build of a registry. """ import odoo from odoo import models from .core import DEFAULT_CACHE_SIZE, ComponentRegistry, _component_databases class ComponentBuilder(models.AbstractModel): """Build the component classes And register them in a global registry. Every time an Odoo registry is built, the know components are cleared and rebuilt as well. The Component classes are built using the same mechanism than Odoo's Models: a final class is created, taking every Components with a ``_name`` and applying Components with an ``_inherits`` upon them. The final Component classes are registered in global registry. This class is an Odoo model, allowing us to hook the build of the components at the end of the Odoo's registry loading, using ``_register_hook``. This method is called after all modules are loaded, so we are sure that we have all the components Classes and in the correct order. """ _name = "component.builder" _description = "Component Builder" _components_registry_cache_size = DEFAULT_CACHE_SIZE def _register_hook(self): # This method is called by Odoo when the registry is built, # so in case the registry is rebuilt (cache invalidation, ...), # we have to to rebuild the components. We use a new # registry so we have an empty cache and we'll add components in it. components_registry = self._init_global_registry() self.build_registry(components_registry) components_registry.ready = True def _init_global_registry(self): components_registry = ComponentRegistry( cachesize=self._components_registry_cache_size ) _component_databases[self.env.cr.dbname] = components_registry return components_registry def build_registry(self, components_registry, states=None, exclude_addons=None): if not states: states = ("installed", "to upgrade") # lookup all the installed (or about to be) addons and generate # the graph, so we can load the components following the order # of the addons' dependencies graph = odoo.modules.graph.Graph() graph.add_module(self.env.cr, "base") query = "SELECT name " "FROM ir_module_module " "WHERE state IN %s " params = [tuple(states)] if exclude_addons: query += " AND name NOT IN %s " params.append(tuple(exclude_addons)) self.env.cr.execute(query, params) module_list = [name for (name,) in self.env.cr.fetchall() if name not in graph] graph.add_modules(self.env.cr, module_list) for module in graph: self.load_components(module.name, components_registry=components_registry) def load_components(self, module, components_registry=None): """Build every component known by MetaComponent for an odoo module The final component (composed by all the Component classes in this module) will be pushed into the registry. :param module: the name of the addon for which we want to load the components :type module: str | unicode :param registry: the registry in which we want to put the Component :type registry: :py:class:`~.core.ComponentRegistry` """ components_registry = ( components_registry or _component_databases[self.env.cr.dbname] ) components_registry.load_components(module)
38.229167
3,670
675
py
PYTHON
15.0
# Copyright 2017 Camptocamp SA # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) { "name": "Components", "summary": "Add capabilities to register and use decoupled components," " as an alternative to model classes", "version": "15.0.1.0.2", "author": "Camptocamp," "Odoo Community Association (OCA)", "website": "https://github.com/OCA/connector", "license": "LGPL-3", "category": "Generic Modules", "depends": ["base"], "external_dependencies": { "python": [ "cachetools", ] }, "installable": True, "development_status": "Production/Stable", "maintainers": ["guewen"], }
30.681818
675
3,052
py
PYTHON
15.0
# Copyright 2017 Camptocamp SA # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) from odoo.addons.component.core import ComponentRegistry, WorkContext from .common import TransactionComponentRegistryCase class TestWorkOn(TransactionComponentRegistryCase): """Test on WorkContext This model is mostly a container, so we check the access to the attributes and properties. """ def setUp(self): super().setUp() self._setup_registry(self) def tearDown(self): self._teardown_registry(self) super().tearDown() def test_collection_work_on(self): """Create a new instance and test attributes access""" collection_record = self.collection.new() with collection_record.work_on("res.partner") as work: self.assertEqual(collection_record, work.collection) self.assertEqual("collection.base", work.collection._name) self.assertEqual("res.partner", work.model_name) self.assertEqual(self.env["res.partner"], work.model) self.assertEqual(self.env, work.env) def test_collection_work_on_registry_via_context(self): """Test propagation of registry via context""" registry = ComponentRegistry() collection_record = self.collection.with_context( components_registry=registry ).new() with collection_record.work_on("res.partner") as work: self.assertEqual(collection_record, work.collection) self.assertEqual("collection.base", work.collection._name) self.assertEqual("res.partner", work.model_name) self.assertEqual(self.env["res.partner"], work.model) self.assertEqual(work.env, collection_record.env) self.assertEqual(work.components_registry, registry) def test_propagate_work_on(self): """Check custom attributes and their propagation""" registry = ComponentRegistry() work = WorkContext( model_name="res.partner", collection=self.collection, # we can customize the lookup registry, but used mostly for tests components_registry=registry, # we can pass our own keyword args that will set as attributes test_keyword="value", ) self.assertIs(registry, work.components_registry) # check that our custom keyword is set as attribute self.assertEqual("value", work.test_keyword) # when we want to work on another model, work_on() create # another instance and propagate the attributes to it work2 = work.work_on("res.users") self.assertNotEqual(work, work2) self.assertEqual(self.env, work2.env) self.assertEqual(self.collection, work2.collection) self.assertEqual("res.users", work2.model_name) self.assertIs(registry, work2.components_registry) # test_keyword has been propagated to the new WorkContext instance self.assertEqual("value", work2.test_keyword)
41.808219
3,052
9,723
py
PYTHON
15.0
# Copyright 2017 Camptocamp SA # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) # Tell pylint to not bother us for all our fake component classes # pylint: disable=consider-merging-classes-inherited import mock from odoo.addons.component.core import AbstractComponent, Component from .common import TransactionComponentRegistryCase class TestBuildComponent(TransactionComponentRegistryCase): """Test build of components All the tests in this suite are based on the same principle with variations: * Create new Components (classes inheriting from :class:`component.core.Component` or :class:`component.core.AbstractComponent` * Call :meth:`component.core.Component._build_component` on them in order to build the 'final class' composed from all the ``_inherit`` and push it in the components registry (``self.comp_registry`` here) * Assert that classes are built, registered, have correct ``__bases__``... """ def setUp(self): super().setUp() self._setup_registry(self) def tearDown(self): self._teardown_registry(self) super().tearDown() def test_no_name(self): """Ensure that a component has a _name""" class Component1(Component): pass msg = ".*must have a _name.*" with self.assertRaisesRegex(TypeError, msg): Component1._build_component(self.comp_registry) def test_register(self): """Able to register components in components registry""" class Component1(Component): _name = "component1" class Component2(Component): _name = "component2" # build the 'final classes' for the components and check that we find # them in the components registry Component1._build_component(self.comp_registry) Component2._build_component(self.comp_registry) self.assertEqual(["base", "component1", "component2"], list(self.comp_registry)) def test_inherit_bases(self): """Check __bases__ of Component with _inherit""" class Component1(Component): _name = "component1" class Component2(Component): _inherit = "component1" class Component3(Component): _inherit = "component1" Component1._build_component(self.comp_registry) Component2._build_component(self.comp_registry) Component3._build_component(self.comp_registry) self.assertEqual( (Component3, Component2, Component1, self.comp_registry["base"]), self.comp_registry["component1"].__bases__, ) def test_prototype_inherit_bases(self): """Check __bases__ of Component with _inherit and different _name""" class Component1(Component): _name = "component1" class Component2(Component): _name = "component2" _inherit = "component1" class Component3(Component): _name = "component3" _inherit = "component1" class Component4(Component): _name = "component4" _inherit = ["component2", "component3"] Component1._build_component(self.comp_registry) Component2._build_component(self.comp_registry) Component3._build_component(self.comp_registry) Component4._build_component(self.comp_registry) self.assertEqual( (Component1, self.comp_registry["base"]), self.comp_registry["component1"].__bases__, ) self.assertEqual( (Component2, self.comp_registry["component1"], self.comp_registry["base"]), self.comp_registry["component2"].__bases__, ) self.assertEqual( (Component3, self.comp_registry["component1"], self.comp_registry["base"]), self.comp_registry["component3"].__bases__, ) self.assertEqual( ( Component4, self.comp_registry["component2"], self.comp_registry["component3"], self.comp_registry["base"], ), self.comp_registry["component4"].__bases__, ) # pylint: disable=W8110 def test_custom_build(self): """Check that we can hook at the end of a Component build""" class Component1(Component): _name = "component1" @classmethod def _complete_component_build(cls): # This method should be called after the Component # is built, and before it is pushed in the registry cls._build_done = True Component1._build_component(self.comp_registry) # we inspect that our custom build has been executed self.assertTrue(self.comp_registry["component1"]._build_done) def test_inherit_attrs(self): """Check attributes inheritance of Components with _inherit""" class Component1(Component): _name = "component1" msg = "ping" def say(self): return "foo" class Component2(Component): _name = "component2" _inherit = "component1" msg = "pong" def say(self): return super().say() + " bar" Component1._build_component(self.comp_registry) Component2._build_component(self.comp_registry) # we initialize the components, normally we should pass # an instance of WorkContext, but we don't need a real one # for this test component1 = self.comp_registry["component1"](mock.Mock()) component2 = self.comp_registry["component2"](mock.Mock()) self.assertEqual("ping", component1.msg) self.assertEqual("pong", component2.msg) self.assertEqual("foo", component1.say()) self.assertEqual("foo bar", component2.say()) def test_duplicate_component(self): """Check that we can't have 2 components with the same name""" class Component1(Component): _name = "component1" class Component2(Component): _name = "component1" Component1._build_component(self.comp_registry) msg = "Component.*already exists.*" with self.assertRaisesRegex(TypeError, msg): Component2._build_component(self.comp_registry) def test_no_parent(self): """Ensure we can't _inherit a non-existent component""" class Component1(Component): _name = "component1" _inherit = "component1" msg = "Component.*does not exist in registry.*" with self.assertRaisesRegex(TypeError, msg): Component1._build_component(self.comp_registry) def test_no_parent2(self): """Ensure we can't _inherit by prototype a non-existent component""" class Component1(Component): _name = "component1" class Component2(Component): _name = "component2" _inherit = ["component1", "component3"] Component1._build_component(self.comp_registry) msg = "Component.*inherits from non-existing component.*" with self.assertRaisesRegex(TypeError, msg): Component2._build_component(self.comp_registry) def test_add_inheritance(self): """Ensure we can add a new inheritance""" class Component1(Component): _name = "component1" class Component2(Component): _name = "component2" class Component2bis(Component): _name = "component2" _inherit = ["component2", "component1"] Component1._build_component(self.comp_registry) Component2._build_component(self.comp_registry) Component2bis._build_component(self.comp_registry) self.assertEqual( ( Component2bis, Component2, self.comp_registry["component1"], self.comp_registry["base"], ), self.comp_registry["component2"].__bases__, ) def test_check_parent_component_over_abstract(self): """Component can inherit from AbstractComponent""" class Component1(AbstractComponent): _name = "component1" class Component2(Component): _name = "component2" _inherit = "component1" Component1._build_component(self.comp_registry) Component2._build_component(self.comp_registry) self.assertTrue(self.comp_registry["component1"]._abstract) self.assertFalse(self.comp_registry["component2"]._abstract) def test_check_parent_abstract_over_component(self): """Prevent AbstractComponent to inherit from Component""" class Component1(Component): _name = "component1" class Component2(AbstractComponent): _name = "component2" _inherit = "component1" Component1._build_component(self.comp_registry) msg = ".*cannot inherit from the non-abstract.*" with self.assertRaisesRegex(TypeError, msg): Component2._build_component(self.comp_registry) def test_check_transform_abstract_to_component(self): """Prevent AbstractComponent to be transformed to Component""" class Component1(AbstractComponent): _name = "component1" class Component1bis(Component): _inherit = "component1" Component1._build_component(self.comp_registry) msg = ".*transforms the abstract component.*into a non-abstract.*" with self.assertRaisesRegex(TypeError, msg): Component1bis._build_component(self.comp_registry)
34.115789
9,723
16,804
py
PYTHON
15.0
# Copyright 2017 Camptocamp SA # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) from contextlib import contextmanager from odoo.addons.component.core import Component from odoo.addons.component.exception import NoComponentError, SeveralComponentError from .common import TransactionComponentRegistryCase class TestComponent(TransactionComponentRegistryCase): """Test usage of components These tests are a bit more broad that mere unit tests. We test the chain odoo Model -> generate a WorkContext instance -> Work with Component. Tests are inside Odoo transactions, so we can work with Odoo's env / models. """ def setUp(self): super().setUp() self._setup_registry(self) self._setUpComponents() def tearDown(self): self._teardown_registry(self) super().tearDown() def _setUpComponents(self): # create some Component to play with class Component1(Component): _name = "component1" _collection = "collection.base" _usage = "for.test" _apply_on = ["res.partner"] class Component2(Component): _name = "component2" _collection = "collection.base" _usage = "for.test" _apply_on = ["res.users"] # build the components and register them in our # test component registry Component1._build_component(self.comp_registry) Component2._build_component(self.comp_registry) # our collection, in a less abstract use case, it # could be a record of 'magento.backend' for instance self.collection_record = self.collection.new() @contextmanager def get_base(): # Our WorkContext, it will be passed along in every # components so we can share data transversally. # We are working with res.partner in the following tests, # unless we change it in the test. with self.collection_record.work_on( "res.partner", # we use a custom registry only # for the sake of the tests components_registry=self.comp_registry, ) as work: # We get the 'base' component, handy to test the base # methods component, many_components, ... yield work.component_by_name("base") self.get_base = get_base def test_component_attrs(self): """Basic access to a Component's attribute""" with self.get_base() as base: # as we are working on res.partner, we should get 'component1' comp = base.work.component(usage="for.test") # but this is not what we test here, we test the attributes: self.assertEqual(self.collection_record, comp.collection) self.assertEqual(base.work, comp.work) self.assertEqual(self.env, comp.env) self.assertEqual(self.env["res.partner"], comp.model) def test_component_get_by_name_same_model(self): """Use component_by_name with current working model""" with self.get_base() as base: # we ask a component directly by it's name, considering # we work with res.partner, we should get 'component1' # this is ok because it's _apply_on contains res.partner comp = base.component_by_name("component1") self.assertEqual("component1", comp._name) self.assertEqual(self.env["res.partner"], comp.model) def test_component_get_by_name_other_model(self): """Use component_by_name with another model""" with self.get_base() as base: # we ask a component directly by it's name, but we # want to work with 'res.users', this is ok since # component2's _apply_on contains res.users comp = base.component_by_name("component2", model_name="res.users") self.assertEqual("component2", comp._name) self.assertEqual(self.env["res.users"], comp.model) # what happens under the hood, is that a new WorkContext # has been created for this model, with all the other values # identical to the previous WorkContext (the one for res.partner) # We can check that with: self.assertNotEqual(base.work, comp.work) self.assertEqual("res.partner", base.work.model_name) self.assertEqual("res.users", comp.work.model_name) def test_component_get_by_name_wrong_model(self): """Use component_by_name with a model not in _apply_on""" msg = ( "Component with name 'component2' can't be used " "for model 'res.partner'.*" ) with self.get_base() as base: with self.assertRaisesRegex(NoComponentError, msg): # we ask for the model 'component2' but we are working # with res.partner, and it only accepts res.users base.component_by_name("component2") def test_component_get_by_name_not_exist(self): """Use component_by_name on a component that do not exist""" msg = "No component with name 'foo' found." with self.get_base() as base: with self.assertRaisesRegex(NoComponentError, msg): base.component_by_name("foo") def test_component_by_usage_same_model(self): """Use component(usage=...) on the same model""" # we ask for a component having _usage == 'for.test', and # model being res.partner (the model in the current WorkContext) with self.get_base() as base: comp = base.component(usage="for.test") self.assertEqual("component1", comp._name) self.assertEqual(self.env["res.partner"], comp.model) def test_component_by_usage_other_model(self): """Use component(usage=...) on a different model (name)""" # we ask for a component having _usage == 'for.test', and # a different model (res.users) with self.get_base() as base: comp = base.component(usage="for.test", model_name="res.users") self.assertEqual("component2", comp._name) self.assertEqual(self.env["res.users"], comp.model) # what happens under the hood, is that a new WorkContext # has been created for this model, with all the other values # identical to the previous WorkContext (the one for res.partner) # We can check that with: self.assertNotEqual(base.work, comp.work) self.assertEqual("res.partner", base.work.model_name) self.assertEqual("res.users", comp.work.model_name) def test_component_by_usage_other_model_env(self): """Use component(usage=...) on a different model (instance)""" with self.get_base() as base: comp = base.component(usage="for.test", model_name=self.env["res.users"]) self.assertEqual("component2", comp._name) self.assertEqual(self.env["res.users"], comp.model) def test_component_error_several(self): """Use component(usage=...) when more than one generic component match""" # we create 1 new Component with _usage 'for.test', in the same # collection and no _apply_on, and we remove the _apply_on of component # 1 so they are generic components for a collection class Component3(Component): _name = "component3" _collection = "collection.base" _usage = "for.test" class Component1(Component): _inherit = "component1" _collection = "collection.base" _usage = "for.test" _apply_on = None Component3._build_component(self.comp_registry) Component1._build_component(self.comp_registry) with self.get_base() as base: with self.assertRaises(SeveralComponentError): # When a component has no _apply_on, it means it can be applied # on *any* model. Here, the candidates components would be: # component3 (because it has no _apply_on so apply in any case) # component4 (for the same reason) base.component(usage="for.test") def test_component_error_several_same_model(self): """Use component(usage=...) when more than one component match a model""" # we create a new Component with _usage 'for.test', in the same # collection and no _apply_on class Component3(Component): _name = "component3" _collection = "collection.base" _usage = "for.test" _apply_on = ["res.partner"] Component3._build_component(self.comp_registry) with self.get_base() as base: with self.assertRaises(SeveralComponentError): # Here, the candidates components would be: # component1 (because we are working with res.partner), # component3 (for the same reason) base.component(usage="for.test") def test_component_specific_model(self): """Use component(usage=...) when more than one component match but only one for the specific model""" # we create a new Component with _usage 'for.test', in the same # collection and no _apply_on. This is a generic component for the # collection class Component3(Component): _name = "component3" _collection = "collection.base" _usage = "for.test" Component3._build_component(self.comp_registry) with self.get_base() as base: # When a component has no _apply_on, it means it can be applied on # *any* model. Here, the candidates components would be: # component1 # (because we are working with res.partner), # component3 (because it # has no _apply_on so apply in any case). # When a component is specifically linked to a model with # _apply_on, it takes precedence over a generic component. It # allows to create a generic implementation (component3 here) and # override it only for a given model. So in this case, the final # component is component1. comp = base.component(usage="for.test") self.assertEqual("component1", comp._name) def test_component_specific_collection(self): """Use component(usage=...) when more than one component match but only one for the specific collection""" # we create a new Component with _usage 'for.test', without collection # and no _apply_on class Component3(Component): _name = "component3" _usage = "for.test" Component3._build_component(self.comp_registry) with self.get_base() as base: # When a component has no _apply_on, it means it can be applied # on *any* model. Here, the candidates components would be: # component1 (because we are working with res.partner), # component3 (because it has no _apply_on so apply in any case). # When a component has no _collection, it means it can be applied # on all model if no component is found for the current collection: # component3 must be ignored since a component (component1) exists # and is specificaly linked to the expected collection. comp = base.component(usage="for.test") self.assertEqual("component1", comp._name) def test_component_specific_collection_specific_model(self): """Use component(usage=...) when more than one component match but only one for the specific model and collection""" # we create a new Component with _usage 'for.test', without collection # and no _apply_on. This is a component generic for all collections and # models class Component3(Component): _name = "component3" _usage = "for.test" Component3._build_component(self.comp_registry) with self.get_base() as base: # When a component has no _apply_on, it means it can be applied on # *any* model, no _collection, it can be applied on *any* # collection. # Here, the candidates components would be: # component1 (because we are working with res.partner), # component3 (because it has no _apply_on and no _collection so # apply in any case). # When a component is specifically linked to a model with # _apply_on, it takes precedence over a generic component, the same # happens for collection. It allows to create a generic # implementation (component3 here) and override it only for a given # collection and model. So in this case, the final component is # component1. comp = base.component(usage="for.test") self.assertEqual("component1", comp._name) def test_many_components(self): """Use many_components(usage=...) on the same model""" class Component3(Component): _name = "component3" _collection = "collection.base" _usage = "for.test" Component3._build_component(self.comp_registry) with self.get_base() as base: comps = base.many_components(usage="for.test") # When a component has no _apply_on, it means it can be applied # on *any* model. So here, both component1 and component3 match self.assertEqual(["component1", "component3"], [c._name for c in comps]) def test_many_components_other_model(self): """Use many_components(usage=...) on a different model (name)""" class Component3(Component): _name = "component3" _collection = "collection.base" _apply_on = "res.users" _usage = "for.test" Component3._build_component(self.comp_registry) with self.get_base() as base: comps = base.many_components(usage="for.test", model_name="res.users") self.assertEqual(["component2", "component3"], [c._name for c in comps]) def test_many_components_other_model_env(self): """Use many_components(usage=...) on a different model (instance)""" class Component3(Component): _name = "component3" _collection = "collection.base" _apply_on = "res.users" _usage = "for.test" Component3._build_component(self.comp_registry) with self.get_base() as base: comps = base.many_components( usage="for.test", model_name=self.env["res.users"] ) self.assertEqual(["component2", "component3"], [c._name for c in comps]) def test_no_component(self): """No component found for asked usage""" with self.get_base() as base: with self.assertRaises(NoComponentError): base.component(usage="foo") def test_no_many_component(self): """No component found for asked usage for many_components()""" with self.get_base() as base: self.assertEqual([], base.many_components(usage="foo")) def test_work_on_component(self): """Check WorkContext.component() (shortcut to Component.component)""" with self.get_base() as base: comp = base.work.component(usage="for.test") self.assertEqual("component1", comp._name) def test_work_on_many_components(self): """Check WorkContext.many_components() (shortcut to Component.many_components) """ with self.get_base() as base: comps = base.work.many_components(usage="for.test") self.assertEqual("component1", comps[0]._name) def test_component_match(self): """Lookup with match method""" class Foo(Component): _name = "foo" _collection = "collection.base" _usage = "speaker" _apply_on = ["res.partner"] @classmethod def _component_match(cls, work, **kw): return False class Bar(Component): _name = "bar" _collection = "collection.base" _usage = "speaker" _apply_on = ["res.partner"] self._build_components(Foo, Bar) with self.get_base() as base: # both components would we returned without the # _component_match method comp = base.component(usage="speaker", model_name=self.env["res.partner"]) self.assertEqual("bar", comp._name)
43.309278
16,804
8,045
py
PYTHON
15.0
# Copyright 2017 Camptocamp SA # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) import copy import unittest from contextlib import contextmanager import odoo from odoo import api from odoo.tests import common from odoo.addons.component.core import ComponentRegistry, MetaComponent, _get_addon_name @contextmanager def new_rollbacked_env(): registry = odoo.registry(common.get_db_name()) uid = odoo.SUPERUSER_ID cr = registry.cursor() try: yield api.Environment(cr, uid, {}) finally: cr.rollback() # we shouldn't have to commit anything cr.close() class ComponentMixin: @classmethod def setUpComponent(cls): with new_rollbacked_env() as env: builder = env["component.builder"] # build the components of every installed addons comp_registry = builder._init_global_registry() cls._components_registry = comp_registry # ensure that we load only the components of the 'installed' # modules, not 'to install', which means we load only the # dependencies of the tested addons, not the siblings or # children addons builder.build_registry(comp_registry, states=("installed",)) # build the components of the current tested addon current_addon = _get_addon_name(cls.__module__) env["component.builder"].load_components(current_addon) if hasattr(cls, "env"): cls.env.context = dict( cls.env.context, components_registry=cls._components_registry ) # pylint: disable=W8106 def setUp(self): # should be ready only during tests, never during installation # of addons self._components_registry.ready = True @self.addCleanup def notready(): self._components_registry.ready = False class TransactionComponentCase(common.TransactionCase, ComponentMixin): """A TransactionCase that loads all the components It it used like an usual Odoo's TransactionCase, but it ensures that all the components of the current addon and its dependencies are loaded. """ @classmethod def setUpClass(cls): super().setUpClass() cls.setUpComponent() # pylint: disable=W8106 def setUp(self): # resolve an inheritance issue (common.TransactionCase does not call # super) common.TransactionCase.setUp(self) ComponentMixin.setUp(self) # There's no env on setUpClass of TransactionCase, must do it here. self.env.context = dict( self.env.context, components_registry=self._components_registry ) class ComponentRegistryCase(unittest.TestCase, common.MetaCase("DummyCase", (), {})): """This test case can be used as a base for writings tests on components This test case is meant to test components in a special component registry, where you want to have maximum control on which components are loaded or not, or when you want to create additional components in your tests. If you only want to *use* the components of the tested addon in your tests, then consider using: * :class:`TransactionComponentCase` This test case creates a special :class:`odoo.addons.component.core.ComponentRegistry` for the purpose of the tests. By default, it loads all the components of the dependencies, but not the components of the current addon (which you have to handle manually). In your tests, you can add more components in 2 manners. All the components of an Odoo module:: self._load_module_components('connector') Only specific components:: self._build_components(MyComponent1, MyComponent2) Note: for the lookups of the components, the default component registry is a global registry for the database. Here, you will need to explicitly pass ``self.comp_registry`` in the :class:`~odoo.addons.component.core.WorkContext`:: work = WorkContext(model_name='res.users', collection='my.collection', components_registry=self.comp_registry) Or:: collection_record = self.env['my.collection'].browse(1) with collection_record.work_on( 'res.partner', components_registry=self.comp_registry) as work: """ @staticmethod def _setup_registry(class_or_instance): # keep the original classes registered by the metaclass # so we'll restore them at the end of the tests, it avoid # to pollute it with Stub / Test components class_or_instance._original_components = copy.deepcopy( MetaComponent._modules_components ) # it will be our temporary component registry for our test session class_or_instance.comp_registry = ComponentRegistry() # it builds the 'final component' for every component of the # 'component' addon and push them in the component registry class_or_instance.comp_registry.load_components("component") # build the components of every installed addons already installed # but the current addon (when running with pytest/nosetest, we # simulate the --test-enable behavior by excluding the current addon # which is in 'to install' / 'to upgrade' with --test-enable). current_addon = _get_addon_name(class_or_instance.__module__) with new_rollbacked_env() as env: env["component.builder"].build_registry( class_or_instance.comp_registry, states=("installed",), exclude_addons=[current_addon], ) # Fake that we are ready to work with the registry # normally, it is set to True and the end of the build # of the components. Here, we'll add components later in # the components registry, but we don't mind for the tests. class_or_instance.comp_registry.ready = True if hasattr(class_or_instance, "env"): # let it propagate via ctx class_or_instance.env.context = dict( class_or_instance.env.context, components_registry=class_or_instance.comp_registry, ) @staticmethod def _teardown_registry(class_or_instance): # restore the original metaclass' classes MetaComponent._modules_components = class_or_instance._original_components def _load_module_components(self, module): self.comp_registry.load_components(module) def _build_components(self, *classes): for cls in classes: cls._build_component(self.comp_registry) class TransactionComponentRegistryCase(common.TransactionCase, ComponentRegistryCase): """Adds Odoo Transaction in the base Component TestCase. This class doesn't set up the registry for you. You're supposed to explicitly call `_setup_registry` and `_teardown_registry` when you need it, either on setUpClass and tearDownClass or setUp and tearDown. class MyTestCase(TransactionComponentRegistryCase): def setUp(self): super().setUp() self._setup_registry(self) def tearDown(self): self._teardown_registry(self) super().tearDown() class MyTestCase(TransactionComponentRegistryCase): @classmethod def setUpClass(cls): super().setUpClass() cls._setup_registry(cls) @classmethod def tearDownClass(cls): cls._teardown_registry(cls) super().tearDownClass() """ # pylint: disable=W8106 @classmethod def setUpClass(cls): # resolve an inheritance issue (common.TransactionCase does not use # super) common.TransactionCase.setUpClass() cls.collection = cls.env["collection.base"] @classmethod def tearDownClass(cls): common.TransactionCase.tearDownClass()
36.73516
8,045
6,162
py
PYTHON
15.0
# Copyright 2017 Camptocamp SA # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) from odoo.addons.component.core import AbstractComponent, Component from .common import TransactionComponentRegistryCase class TestLookup(TransactionComponentRegistryCase): """Test the ComponentRegistry Tests in this testsuite mainly do: * Create new Components (classes inheriting from :class:`component.core.Component` or :class:`component.core.AbstractComponent` * Call :meth:`component.core.Component._build_component` on them in order to build the 'final class' composed from all the ``_inherit`` and push it in the components registry (``self.comp_registry`` here) * Use the lookup method of the components registry and check that we get the correct result """ def setUp(self): super().setUp() self._setup_registry(self) def tearDown(self): self._teardown_registry(self) super().tearDown() def test_lookup_collection(self): """Lookup components of a collection""" # we register 2 components in foobar and one in other class Foo(Component): _name = "foo" _collection = "foobar" class Bar(Component): _name = "bar" _collection = "foobar" class Homer(Component): _name = "homer" _collection = "other" self._build_components(Foo, Bar, Homer) # we should no see the component in 'other' components = self.comp_registry.lookup("foobar") self.assertEqual(["foo", "bar"], [c._name for c in components]) def test_lookup_usage(self): """Lookup components by usage""" class Foo(Component): _name = "foo" _collection = "foobar" _usage = "speaker" class Bar(Component): _name = "bar" _collection = "foobar" _usage = "speaker" class Baz(Component): _name = "baz" _collection = "foobar" _usage = "listener" self._build_components(Foo, Bar, Baz) components = self.comp_registry.lookup("foobar", usage="listener") self.assertEqual("baz", components[0]._name) components = self.comp_registry.lookup("foobar", usage="speaker") self.assertEqual(["foo", "bar"], [c._name for c in components]) def test_lookup_no_component(self): """No component""" # we just expect an empty list when no component match, the error # handling is handled at an higher level self.assertEqual([], self.comp_registry.lookup("something", usage="something")) def test_get_by_name(self): """Get component by name""" class Foo(AbstractComponent): _name = "foo" _collection = "foobar" self._build_components(Foo) # this is just a dict access self.assertEqual("foo", self.comp_registry["foo"]._name) def test_lookup_abstract(self): """Do not include abstract components in lookup""" class Foo(AbstractComponent): _name = "foo" _collection = "foobar" _usage = "speaker" class Bar(Component): _name = "bar" _inherit = "foo" self._build_components(Foo, Bar) comp_registry = self.comp_registry # we should never have 'foo' in the returned components # as it is abstract components = comp_registry.lookup("foobar", usage="speaker") self.assertEqual("bar", components[0]._name) components = comp_registry.lookup("foobar", usage="speaker") self.assertEqual(["bar"], [c._name for c in components]) def test_lookup_model_name(self): """Lookup with model names""" class Foo(Component): _name = "foo" _collection = "foobar" _usage = "speaker" # support list _apply_on = ["res.partner"] class Bar(Component): _name = "bar" _collection = "foobar" _usage = "speaker" # support string _apply_on = "res.users" class Any(Component): # can be used with any model as far as we look it up # with its usage _name = "any" _collection = "foobar" _usage = "listener" self._build_components(Foo, Bar, Any) components = self.comp_registry.lookup( "foobar", usage="speaker", model_name="res.partner" ) self.assertEqual("foo", components[0]._name) components = self.comp_registry.lookup( "foobar", usage="speaker", model_name="res.users" ) self.assertEqual("bar", components[0]._name) components = self.comp_registry.lookup( "foobar", usage="listener", model_name="res.users" ) self.assertEqual("any", components[0]._name) def test_lookup_cache(self): """Lookup uses a cache""" class Foo(Component): _name = "foo" _collection = "foobar" self._build_components(Foo) components = self.comp_registry.lookup("foobar") self.assertEqual(["foo"], [c._name for c in components]) # we add a new component class Bar(Component): _name = "bar" _collection = "foobar" self._build_components(Bar) # As the lookups are cached, we should still see only foo, # even if we added a new component. # We do this for testing, but in a real use case, we can't # add new Component classes on the fly, and when we install # new addons, the registry is rebuilt and cache cleared. components = self.comp_registry.lookup("foobar") self.assertEqual(["foo"], [c._name for c in components]) self.comp_registry._cache.clear() # now we should find them both as the cache has been cleared components = self.comp_registry.lookup("foobar") self.assertEqual(["foo", "bar"], [c._name for c in components])
32.09375
6,162
3,511
py
PYTHON
15.0
# Copyright 2017 Camptocamp SA # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) """ Collection Model ================ This is the base Model shared by all the Collections. In the context of the Connector, a collection is the Backend. The `_name` given to the Collection Model will be the name to use in the `_collection` of the Components usable for the Backend. """ from contextlib import contextmanager from odoo import models from ..core import WorkContext class Collection(models.AbstractModel): """The model on which components are subscribed It would be for instance the ``backend`` for the connectors. Example:: class MagentoBackend(models.Model): _name = 'magento.backend' # name of the collection _inherit = 'collection.base' class MagentoSaleImporter(Component): _name = 'magento.sale.importer' _apply_on = 'magento.sale.order' _collection = 'magento.backend' # name of the collection def run(self, magento_id): mapper = self.component(usage='import.mapper') extra_mappers = self.many_components( usage='import.mapper.extra', ) # ... Use it:: >>> backend = self.env['magento.backend'].browse(1) >>> with backend.work_on('magento.sale.order') as work: ... importer = work.component(usage='magento.sale.importer') ... importer.run(1) See also: :class:`odoo.addons.component.core.WorkContext` """ _name = "collection.base" _description = "Base Abstract Collection" @contextmanager def work_on(self, model_name, **kwargs): """Entry-point for the components, context manager Start a work using the components on the model. Any keyword argument will be assigned to the work context. See documentation of :class:`odoo.addons.component.core.WorkContext`. It is a context manager, so you can attach objects and clean them at the end of the work session, such as:: @contextmanager def work_on(self, model_name, **kwargs): self.ensure_one() magento_location = MagentoLocation( self.location, self.username, self.password, ) # We create a Magento Client API here, so we can create the # client once (lazily on the first use) and propagate it # through all the sync session, instead of recreating a client # in each backend adapter usage. with MagentoAPI(magento_location) as magento_api: _super = super(MagentoBackend, self) # from the components we'll be able to do: # self.work.magento_api with _super.work_on( model_name, magento_api=magento_api, **kwargs ) as work: yield work """ self.ensure_one() # Allow propagation of custom component registry via context # TODO: maybe to be moved to `WorkContext.__init__` components_registry = self.env.context.get("components_registry") if components_registry: kwargs["components_registry"] = components_registry yield WorkContext(model_name=model_name, collection=self, **kwargs)
34.762376
3,511
349
py
PYTHON
15.0
# Copyright 2017 Camptocamp SA # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) from ..core import AbstractComponent class BaseComponent(AbstractComponent): """This is the base component for every component It is implicitely inherited by all components. All your base are belong to us """ _name = "base"
23.266667
349
971
py
PYTHON
15.0
# Copyright 2012 Camptocamp SA # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) from odoo.addons.queue_job.exception import JobError, RetryableJobError # Connector related errors class ConnectorException(Exception): """Base Exception for the connectors""" class NoConnectorUnitError(ConnectorException): """No ConnectorUnit has been found""" class InvalidDataError(ConnectorException): """Data Invalid""" # Job related errors class MappingError(ConnectorException): """An error occurred during a mapping transformation.""" class NetworkRetryableError(RetryableJobError): """A network error caused the failure of the job, it can be retried later.""" class NoExternalId(RetryableJobError): """No External ID found, it can be retried later.""" class IDMissingInBackend(JobError): """The ID does not exist in the backend""" class ManyIDSInBackend(JobError): """Unique key exists many times in backend"""
23.682927
971
2,967
py
PYTHON
15.0
# Copyright 2013 Camptocamp SA # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) import hashlib import logging import struct _logger = logging.getLogger(__name__) def pg_try_advisory_lock(env, lock): """Try to acquire a Postgres transactional advisory lock. The function tries to acquire a lock, returns a boolean indicating if it could be obtained or not. An acquired lock is released at the end of the transaction. A typical use is to acquire a lock at the beginning of an importer to prevent 2 jobs to do the same import at the same time. Since the record doesn't exist yet, we can't put a lock on a record, so we put an advisory lock. Example: - Job 1 imports Partner A - Job 2 imports Partner B - Partner A has a category X which happens not to exist yet - Partner B has a category X which happens not to exist yet - Job 1 import category X as a dependency - Job 2 import category X as a dependency Since both jobs are executed concurrently, they both create a record for category X so we have duplicated records. With this lock: - Job 1 imports Partner A, it acquires a lock for this partner - Job 2 imports Partner B, it acquires a lock for this partner - Partner A has a category X which happens not to exist yet - Partner B has a category X which happens not to exist yet - Job 1 import category X as a dependency, it acquires a lock for this category - Job 2 import category X as a dependency, try to acquire a lock but can't, Job 2 is retried later, and when it is retried, it sees the category X created by Job 1. The lock is acquired until the end of the transaction. Usage example: :: lock_name = 'import_record({}, {}, {}, {})'.format( self.backend_record._name, self.backend_record.id, self.model._name, self.external_id, ) if pg_try_advisory_lock(lock_name): # do sync else: raise RetryableJobError('Could not acquire advisory lock', seconds=2, ignore_retry=True) :param env: the Odoo Environment :param lock: The lock name. Can be anything convertible to a string. It needs to represents what should not be synchronized concurrently so usually the string will contain at least: the action, the backend type, the backend id, the model name, the external id :return True/False whether lock was acquired. """ hasher = hashlib.sha1(str(lock).encode()) # pg_lock accepts an int8 so we build an hash composed with # contextual information and we throw away some bits int_lock = struct.unpack("q", hasher.digest()[:8]) env.cr.execute("SELECT pg_try_advisory_xact_lock(%s);", (int_lock,)) acquired = env.cr.fetchone()[0] return acquired
38.038462
2,967
564
py
PYTHON
15.0
# Copyright 2013 Camptocamp SA # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) { "name": "Connector", "version": "15.0.1.0.4", "author": "Camptocamp,Odoo Community Association (OCA)", "website": "https://github.com/OCA/connector", "license": "LGPL-3", "category": "Generic Modules", "depends": ["mail", "queue_job", "component", "component_event"], "data": [ "security/connector_security.xml", "views/connector_menu.xml", "views/res_partner_views.xml", ], "installable": True, }
31.333333
564
2,698
py
PYTHON
15.0
# Copyright 2017 Camptocamp SA # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) import mock from odoo import api from odoo.modules.registry import Registry from odoo.tests import common from odoo.addons.component.core import WorkContext from odoo.addons.component.tests.common import TransactionComponentCase from odoo.addons.connector.database import pg_try_advisory_lock from odoo.addons.queue_job.exception import RetryableJobError class TestAdvisoryLock(TransactionComponentCase): def setUp(self): super().setUp() self.registry2 = Registry(common.get_db_name()) self.cr2 = self.registry2.cursor() self.env2 = api.Environment(self.cr2, self.env.uid, {}) @self.addCleanup def reset_cr2(): # rollback and close the cursor, and reset the environments self.env2.reset() self.cr2.rollback() self.cr2.close() def test_concurrent_lock(self): """2 concurrent transactions cannot acquire the same lock""" # the lock is based on a string, a second transaction trying # to acquire the same lock won't be able to acquire it lock = "import_record({}, {}, {}, {})".format( "backend.name", 1, "res.partner", "999999" ) acquired = pg_try_advisory_lock(self.env, lock) self.assertTrue(acquired) # we test the base function inner_acquired = pg_try_advisory_lock(self.env2, lock) self.assertFalse(inner_acquired) def test_concurrent_import_lock(self): """A 2nd concurrent transaction must retry""" # the lock is based on a string, a second transaction trying # to acquire the same lock won't be able to acquire it lock = "import_record({}, {}, {}, {})".format( "backend.name", 1, "res.partner", "999999" ) backend = mock.MagicMock() backend.env = self.env work = WorkContext(model_name="res.partner", collection=backend) # we test the function through a Component instance component = work.component_by_name("base.connector") # acquire the lock component.advisory_lock_or_retry(lock) # instanciate another component using a different odoo env # hence another PG transaction backend2 = mock.MagicMock() backend2.env = self.env2 work2 = WorkContext(model_name="res.partner", collection=backend2) component2 = work2.component_by_name("base.connector") with self.assertRaises(RetryableJobError) as cm: component2.advisory_lock_or_retry(lock, retry_seconds=3) self.assertEqual(cm.exception.seconds, 3)
40.268657
2,698
2,115
py
PYTHON
15.0
# Copyright 2017 Camptocamp SA # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) import mock from odoo.tools import frozendict from odoo.addons.component.core import Component from odoo.addons.component.tests.common import TransactionComponentRegistryCase from odoo.addons.component_event.components.event import skip_if from odoo.addons.component_event.core import EventWorkContext from odoo.addons.connector import components class TestEventListener(TransactionComponentRegistryCase): """Test Connecter Listener""" def setUp(self): super().setUp() self._setup_registry(self) def test_skip_if_no_connector_export(self): class MyEventListener(Component): _name = "my.event.listener" _inherit = "base.event.listener" def on_record_create(self, record, fields=None): assert True class MyOtherEventListener(Component): _name = "my.other.event.listener" _inherit = "base.connector.listener" @skip_if(lambda self, record, fields=None: self.no_connector_export(record)) def on_record_create(self, record, fields=None): raise AssertionError() self.env.context = frozendict(self.env.context, no_connector_export=True) work = EventWorkContext( model_name="res.users", env=self.env, components_registry=self.comp_registry ) # get the collecter to notify the event # we don't mind about the collection and the model here, # the events we test are global self.collecter = self.comp_registry["base.event.collecter"](work) self._build_components( components.core.BaseConnectorComponent, components.listener.ConnectorListener, MyEventListener, MyOtherEventListener, ) # collect the event and notify it record = mock.Mock(name="record") collected = self.collecter.collect_events("on_record_create") self.assertEqual(2, len(collected.events)) collected.notify(record)
35.847458
2,115
30,880
py
PYTHON
15.0
# Copyright 2013 Camptocamp SA # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) import mock from odoo.addons.component.core import Component, WorkContext from odoo.addons.component.tests.common import TransactionComponentRegistryCase from odoo.addons.connector.components.mapper import ( MapOptions, MappingDefinition, changed_by, convert, external_to_m2o, follow_m2o_relations, m2o_to_external, mapping, none, only_create, ) class TestMapper(TransactionComponentRegistryCase): def setUp(self): super().setUp() self._setup_registry(self) self.comp_registry.load_components("connector") def test_mapping_decorator(self): class KifKrokerMapper(Component): _name = "kif.kroker.mapper" _inherit = "base.mapper" @changed_by("name", "city") @mapping @only_create def name(self): pass @changed_by("email") @mapping def email(self): pass @changed_by("street") @mapping def street(self): pass def no_decorator(self): pass # build our mapper component KifKrokerMapper._build_component(self.comp_registry) # what mappings we expect name_def = MappingDefinition(changed_by={"name", "city"}, only_create=True) email_def = MappingDefinition(changed_by={"email"}, only_create=False) street_def = MappingDefinition(changed_by={"street"}, only_create=False) # get our component by name in the components registry comp = self.comp_registry["kif.kroker.mapper"] # _map_methods contains the aggregated mapping methods for a Mapper self.assertEqual( comp._map_methods, {"name": name_def, "email": email_def, "street": street_def}, ) def test_mapping_decorator_cross_classes(self): """Mappings should not propagate to other classes""" class MomMapper(Component): _name = "mom.mapper" _inherit = "base.mapper" _apply_on = "res.users" @changed_by("name", "city") @mapping def name(self): pass class ZappMapper(Component): _name = "zapp.mapper" _inherit = "base.mapper" _apply_on = "res.users" @changed_by("email") @only_create @mapping def email(self): pass self._build_components(MomMapper, ZappMapper) mom_def = MappingDefinition(changed_by={"name", "city"}, only_create=False) zapp_def = MappingDefinition(changed_by={"email"}, only_create=True) comp = self.comp_registry["mom.mapper"] self.assertEqual(comp._map_methods, {"name": mom_def}) comp = self.comp_registry["zapp.mapper"] self.assertEqual(comp._map_methods, {"email": zapp_def}) def test_mapping_decorator_cumul(self): """Mappings should cumulate the ``super`` mappings and the local mappings.""" class FryMapper(Component): _name = "fry.mapper" _inherit = "base.mapper" _apply_on = "res.users" @changed_by("name", "city") @mapping def name(self): pass # pylint: disable=R7980 class FryMapperInherit(Component): _inherit = "fry.mapper" @changed_by("email") @mapping def email(self): pass self._build_components(FryMapper, FryMapperInherit) name_def = MappingDefinition(changed_by={"name", "city"}, only_create=False) email_def = MappingDefinition(changed_by={"email"}, only_create=False) comp = self.comp_registry["fry.mapper"] self.assertEqual(comp._map_methods, {"name": name_def, "email": email_def}) def test_mapping_decorator_cumul_changed_by(self): """Mappings should cumulate the changed_by fields of the ``super`` mappings and the local mappings""" class FryMapper(Component): _name = "fry.mapper" _inherit = "base.mapper" _apply_on = "res.users" @changed_by("name", "city") @mapping def name(self): pass class FryMapperInherit(Component): _inherit = "fry.mapper" _apply_on = "res.users" @changed_by("email") @mapping def name(self): pass class ThirdMapper(Component): _name = "third.mapper" _inherit = "fry.mapper" _apply_on = "res.users" @changed_by("email", "street") @mapping def name(self): pass self._build_components(FryMapper, FryMapperInherit, ThirdMapper) name_def = MappingDefinition( changed_by={"name", "city", "email"}, only_create=False ) comp = self.comp_registry["fry.mapper"] self.assertEqual(comp._map_methods, {"name": name_def}) name_def = MappingDefinition( changed_by={"name", "city", "email", "street"}, only_create=False ) comp = self.comp_registry["third.mapper"] self.assertEqual(comp._map_methods, {"name": name_def}) def test_several_bases_cumul(self): class FryMapper(Component): _name = "fry.mapper" _inherit = "base.mapper" _apply_on = "res.users" @changed_by("name", "city") @mapping def name(self): pass @only_create @mapping def street(self): pass @only_create @mapping def zip(self): pass class FarnsworthMapper(Component): _name = "farnsworth.mapper" _inherit = "base.mapper" _apply_on = "res.users" @changed_by("email") @mapping def name(self): pass @changed_by("street") @mapping def city(self): pass @mapping def zip(self): pass class ThirdMapper(Component): _name = "third.mapper" _inherit = ["fry.mapper", "farnsworth.mapper"] _apply_on = "res.users" @changed_by("email", "street") @mapping def name(self): pass @mapping def email(self): pass self._build_components(FryMapper, FarnsworthMapper, ThirdMapper) name_def = MappingDefinition( changed_by={"name", "city", "email", "street"}, only_create=False ) street_def = MappingDefinition(changed_by=set(), only_create=True) city_def = MappingDefinition(changed_by={"street"}, only_create=False) email_def = MappingDefinition(changed_by=set(), only_create=False) zip_def = MappingDefinition(changed_by=set(), only_create=True) comp = self.comp_registry["third.mapper"] self.assertEqual(comp._map_methods["name"], name_def) self.assertEqual(comp._map_methods["street"], street_def) self.assertEqual(comp._map_methods["city"], city_def) self.assertEqual(comp._map_methods["email"], email_def) self.assertEqual(comp._map_methods["zip"], zip_def) def test_mapping_record(self): """Map a record and check the result""" class MyMapper(Component): _name = "my.mapper" _inherit = "base.import.mapper" _apply_on = "res.users" direct = [("name", "out_name")] @mapping def street(self, record): return {"out_street": record["street"].upper()} self._build_components(MyMapper) record = {"name": "Guewen", "street": "street"} work = mock.MagicMock(name="WorkContext()") mapper = self.comp_registry["my.mapper"](work) map_record = mapper.map_record(record) expected = {"out_name": "Guewen", "out_street": "STREET"} self.assertEqual(map_record.values(), expected) self.assertEqual(map_record.values(for_create=True), expected) def test_mapping_record_on_create(self): """Map a record and check the result for creation of record""" class MyMapper(Component): _name = "my.mapper" _inherit = "base.import.mapper" _apply_on = "res.users" direct = [("name", "out_name")] @mapping def street(self, record): return {"out_street": record["street"].upper()} @only_create @mapping def city(self, record): return {"out_city": "city"} self._build_components(MyMapper) record = {"name": "Guewen", "street": "street"} work = mock.MagicMock(name="WorkContext()") mapper = self.comp_registry["my.mapper"](work) map_record = mapper.map_record(record) expected = {"out_name": "Guewen", "out_street": "STREET"} self.assertEqual(map_record.values(), expected) expected = {"out_name": "Guewen", "out_street": "STREET", "out_city": "city"} self.assertEqual(map_record.values(for_create=True), expected) def test_mapping_update(self): """Force values on a map record""" class MyMapper(Component): _name = "my.mapper" _inherit = "base.import.mapper" direct = [("name", "out_name")] @mapping def street(self, record): return {"out_street": record["street"].upper()} @only_create @mapping def city(self, record): return {"out_city": "city"} self._build_components(MyMapper) record = {"name": "Guewen", "street": "street"} work = mock.MagicMock(name="WorkContext()") mapper = self.comp_registry["my.mapper"](work) map_record = mapper.map_record(record) map_record.update({"test": 1}, out_city="forced") expected = { "out_name": "Guewen", "out_street": "STREET", "out_city": "forced", "test": 1, } self.assertEqual(map_record.values(), expected) expected = { "out_name": "Guewen", "out_street": "STREET", "out_city": "forced", "test": 1, } self.assertEqual(map_record.values(for_create=True), expected) # pylint: disable=W8110 def test_finalize(self): """Inherit finalize to modify values""" class MyMapper(Component): _name = "my.mapper" _inherit = "base.import.mapper" direct = [("name", "out_name")] def finalize(self, record, values): result = super().finalize(record, values) result["test"] = "abc" return result self._build_components(MyMapper) record = {"name": "Guewen", "street": "street"} work = mock.MagicMock(name="WorkContext()") mapper = self.comp_registry["my.mapper"](work) map_record = mapper.map_record(record) expected = {"out_name": "Guewen", "test": "abc"} self.assertEqual(map_record.values(), expected) expected = {"out_name": "Guewen", "test": "abc"} self.assertEqual(map_record.values(for_create=True), expected) def test_some_fields(self): """Map only a selection of fields""" class MyMapper(Component): _name = "my.mapper" _inherit = "base.import.mapper" direct = [("name", "out_name"), ("street", "out_street")] @changed_by("country") @mapping def country(self, record): return {"country": "country"} self._build_components(MyMapper) record = {"name": "Guewen", "street": "street", "country": "country"} work = mock.MagicMock(name="WorkContext()") mapper = self.comp_registry["my.mapper"](work) map_record = mapper.map_record(record) expected = {"out_name": "Guewen", "country": "country"} self.assertEqual(map_record.values(fields=["name", "country"]), expected) expected = {"out_name": "Guewen", "country": "country"} self.assertEqual( map_record.values(for_create=True, fields=["name", "country"]), expected ) def test_mapping_modifier(self): """Map a direct record with a modifier function""" def do_nothing(field): def transform(self, record, to_attr): return record[field] return transform class MyMapper(Component): _name = "my.mapper" _inherit = "base.import.mapper" direct = [(do_nothing("name"), "out_name")] self._build_components(MyMapper) record = {"name": "Guewen"} work = mock.MagicMock(name="WorkContext()") mapper = self.comp_registry["my.mapper"](work) map_record = mapper.map_record(record) expected = {"out_name": "Guewen"} self.assertEqual(map_record.values(), expected) self.assertEqual(map_record.values(for_create=True), expected) def test_mapping_direct_property(self): """Map a direct record with 'direct' being a property""" class MyMapper(Component): _name = "my.mapper" _inherit = "base.import.mapper" @property def direct(self): return [("name", "out_name")] self._build_components(MyMapper) record = {"name": "Foo"} work = mock.MagicMock(name="WorkContext()") mapper = self.comp_registry["my.mapper"](work) map_record = mapper.map_record(record) expected = {"out_name": "Foo"} self.assertEqual(map_record.values(), expected) self.assertEqual(map_record.values(for_create=True), expected) def test_mapping_convert(self): """Map a direct record with the convert modifier function""" class MyMapper(Component): _name = "my.mapper" _inherit = "base.import.mapper" direct = [(convert("name", int), "out_name")] self._build_components(MyMapper) record = {"name": "300"} work = mock.MagicMock(name="WorkContext()") mapper = self.comp_registry["my.mapper"](work) map_record = mapper.map_record(record) expected = {"out_name": 300} self.assertEqual(map_record.values(), expected) self.assertEqual(map_record.values(for_create=True), expected) def test_mapping_modifier_none(self): """Pipeline of modifiers""" class MyMapper(Component): _name = "my.mapper" _inherit = "base.import.mapper" direct = [(none("in_f"), "out_f"), (none("in_t"), "out_t")] self._build_components(MyMapper) record = {"in_f": False, "in_t": True} work = mock.MagicMock(name="WorkContext()") mapper = self.comp_registry["my.mapper"](work) map_record = mapper.map_record(record) expected = {"out_f": None, "out_t": True} self.assertEqual(map_record.values(), expected) self.assertEqual(map_record.values(for_create=True), expected) def test_mapping_modifier_pipeline(self): """Pipeline of modifiers""" class MyMapper(Component): _name = "my.mapper" _inherit = "base.import.mapper" direct = [ (none(convert("in_f", bool)), "out_f"), (none(convert("in_t", bool)), "out_t"), ] self._build_components(MyMapper) record = {"in_f": 0, "in_t": 1} work = mock.MagicMock(name="WorkContext()") mapper = self.comp_registry["my.mapper"](work) map_record = mapper.map_record(record) expected = {"out_f": None, "out_t": True} self.assertEqual(map_record.values(), expected) self.assertEqual(map_record.values(for_create=True), expected) def test_modifier_import_filter_field(self): """A direct mapping with a modifier must still be considered from the list of fields """ class MyMapper(Component): _name = "my.mapper" _inherit = "base.import.mapper" direct = [ ("field", "field2"), ("no_field", "no_field2"), (convert("name", int), "out_name"), ] self._build_components(MyMapper) record = {"name": "300", "field": "value", "no_field": "no_value"} work = mock.MagicMock(name="WorkContext()") mapper = self.comp_registry["my.mapper"](work) map_record = mapper.map_record(record) expected = {"out_name": 300, "field2": "value"} self.assertEqual(map_record.values(fields=["field", "name"]), expected) self.assertEqual( map_record.values(for_create=True, fields=["field", "name"]), expected ) def test_modifier_export_filter_field(self): """A direct mapping with a modifier on an export mapping""" class MyMapper(Component): _name = "my.mapper" _inherit = "base.export.mapper" direct = [ ("field", "field2"), ("no_field", "no_field2"), (convert("name", int), "out_name"), ] self._build_components(MyMapper) record = {"name": "300", "field": "value", "no_field": "no_value"} work = mock.MagicMock(name="WorkContext()") mapper = self.comp_registry["my.mapper"](work) map_record = mapper.map_record(record) expected = {"out_name": 300, "field2": "value"} self.assertEqual(map_record.values(fields=["field", "name"]), expected) self.assertEqual( map_record.values(for_create=True, fields=["field", "name"]), expected ) def test_mapping_custom_option(self): """Usage of custom options in mappings""" class MyMapper(Component): _name = "my.mapper" _inherit = "base.import.mapper" @mapping def any(self, record): if self.options.custom: res = True else: res = False return {"res": res} self._build_components(MyMapper) record = {} work = mock.MagicMock(name="WorkContext()") mapper = self.comp_registry["my.mapper"](work) map_record = mapper.map_record(record) expected = {"res": True} self.assertEqual(map_record.values(custom=True), expected) def test_mapping_custom_option_not_defined(self): """Usage of custom options not defined raise AttributeError""" class MyMapper(Component): _name = "my.mapper" _inherit = "base.import.mapper" @mapping def any(self, record): if self.options.custom is None: res = True else: res = False return {"res": res} self._build_components(MyMapper) record = {} work = mock.MagicMock(name="WorkContext()") mapper = self.comp_registry["my.mapper"](work) map_record = mapper.map_record(record) expected = {"res": True} self.assertEqual(map_record.values(), expected) def test_map_options(self): """Test MapOptions""" options = MapOptions({"xyz": "abc"}, k=1) options.l = 2 # noqa: E741 self.assertEqual(options["xyz"], "abc") self.assertEqual(options["k"], 1) self.assertEqual(options["l"], 2) self.assertEqual(options.xyz, "abc") self.assertEqual(options.k, 1) self.assertEqual(options.l, 2) self.assertEqual(options["undefined"], None) self.assertEqual(options.undefined, None) def test_changed_by_fields(self): """Test attribute ``_changed_by_fields`` on Mapper.""" class MyMapper(Component): _name = "my.mapper" _inherit = "base.export.mapper" direct = [ ("street", "out_street"), (none("in_t"), "out_t"), (none(convert("in_f", bool)), "out_f"), ] @changed_by("name", "city") @mapping def name(self): pass @changed_by("email") @mapping def email(self): pass def no_decorator(self): pass self._build_components(MyMapper) work = mock.MagicMock(name="WorkContext()") mapper = self.comp_registry["my.mapper"](work) self.assertEqual( mapper.changed_by_fields(), {"street", "in_t", "in_f", "name", "city", "email"}, ) class TestMapperRecordsets(TransactionComponentRegistryCase): """Test mapper with "real" records instead of mocks""" def setUp(self): super().setUp() self._setup_registry(self) self.comp_registry.load_components("connector") backend_record = mock.Mock() backend_record.env = self.env self.work = WorkContext( model_name="res.partner", collection=backend_record, components_registry=self.comp_registry, ) def test_mapping_modifier_follow_m2o_relations(self): """Map with the follow_m2o_relations modifier""" class MyMapper(Component): _name = "my.mapper" _inherit = "base.import.mapper" direct = [(follow_m2o_relations("parent_id.name"), "parent_name")] self._build_components(MyMapper) partner = self.env.ref("base.res_partner_address_4") mapper = self.comp_registry["my.mapper"](self.work) map_record = mapper.map_record(partner) expected = {"parent_name": "Deco Addict"} self.assertEqual(map_record.values(), expected) self.assertEqual(map_record.values(for_create=True), expected) class TestMapperBinding(TransactionComponentRegistryCase): """Test Mapper with Bindings""" def setUp(self): super().setUp() self._setup_registry(self) self.comp_registry.load_components("connector") backend_record = mock.Mock() backend_record.env = self.env backend_record._name = "my.collection" self.work = WorkContext( model_name="res.partner", collection=backend_record, components_registry=self.comp_registry, ) self.country_binder = mock.MagicMock(name="country_binder") self.country_binder.return_value = self.country_binder self.country_binder._name = "test.binder" self.country_binder._inherit = "base.binder" self.country_binder.apply_on_models = ["res.country"] self.country_binder._usage = "binder" self.country_binder._collection = "my.collection" self.country_binder._abstract = False self.comp_registry["test.binder"] = self.country_binder def test_mapping_m2o_to_external(self): """Map a direct record with the m2o_to_external modifier function""" class MyMapper(Component): _name = "my.mapper" _inherit = "base.import.mapper" _apply_on = "res.partner" direct = [(m2o_to_external("country_id"), "country")] self._build_components(MyMapper) partner = self.env.ref("base.main_partner") partner.write({"country_id": self.env.ref("base.ch").id}) self.country_binder.to_external.return_value = 10 mapper = self.comp_registry["my.mapper"](self.work) map_record = mapper.map_record(partner) self.assertEqual(map_record.values(), {"country": 10}) self.country_binder.to_external.assert_called_once_with( partner.country_id.id, wrap=False ) def test_mapping_backend_to_m2o(self): """Map a direct record with the backend_to_m2o modifier function""" class MyMapper(Component): _name = "my.mapper" _inherit = "base.import.mapper" _apply_on = "res.partner" direct = [(external_to_m2o("country"), "country_id")] self._build_components(MyMapper) record = {"country": 10} ch = self.env.ref("base.ch") self.country_binder.to_internal.return_value = ch mapper = self.comp_registry["my.mapper"](self.work) map_record = mapper.map_record(record) self.assertEqual(map_record.values(), {"country_id": ch.id}) self.country_binder.to_internal.assert_called_once_with(10, unwrap=False) def test_mapping_record_children_no_map_child(self): """Map a record with children, using default MapChild""" # we need these components which make the 'link' between # the main mapper and the line mapper class LineMapper(Component): _name = "line.mapper" _inherit = "base.import.mapper" _apply_on = "res.currency.rate" direct = [("name", "name")] @mapping def price(self, record): return {"rate": record["rate"] * 2} @only_create @mapping def discount(self, record): return {"test": 0.5} class MyMapper(Component): _name = "my.mapper" _inherit = "base.import.mapper" _apply_on = "res.currency" direct = [("name", "name")] children = [("lines", "line_ids", "res.currency.rate")] self._build_components(LineMapper, MyMapper) record = { "name": "SO1", "lines": [ {"name": "2013-11-07", "rate": 10}, {"name": "2013-11-08", "rate": 20}, ], } mapper = self.comp_registry["my.mapper"](self.work) map_record = mapper.map_record(record) expected = { "name": "SO1", "line_ids": [ (0, 0, {"name": "2013-11-07", "rate": 20}), (0, 0, {"name": "2013-11-08", "rate": 40}), ], } self.assertEqual(map_record.values(), expected) expected = { "name": "SO1", "line_ids": [ (0, 0, {"name": "2013-11-07", "rate": 20, "test": 0.5}), (0, 0, {"name": "2013-11-08", "rate": 40, "test": 0.5}), ], } self.assertEqual(map_record.values(for_create=True), expected) def test_mapping_record_children(self): """Map a record with children, using defined MapChild""" # we need these components which make the 'link' between # the main mapper and the line mapper class LineMapper(Component): _name = "line.mapper" _inherit = "base.import.mapper" _apply_on = "res.currency.rate" direct = [("name", "name")] @mapping def price(self, record): return {"rate": record["rate"] * 2} @only_create @mapping def discount(self, record): return {"test": 0.5} class LineImportMapChild(Component): _name = "line.map.child.import" _inherit = "base.map.child.import" _apply_on = "res.currency.rate" def format_items(self, items_values): return [("ABC", values) for values in items_values] class MyMapper(Component): _name = "my.mapper" _inherit = "base.import.mapper" _apply_on = "res.currency" direct = [("name", "name")] children = [("lines", "line_ids", "res.currency.rate")] self._build_components(LineMapper, LineImportMapChild, MyMapper) record = { "name": "SO1", "lines": [ {"name": "2013-11-07", "rate": 10}, {"name": "2013-11-08", "rate": 20}, ], } mapper = self.comp_registry["my.mapper"](self.work) map_record = mapper.map_record(record) expected = { "name": "SO1", "line_ids": [ ("ABC", {"name": "2013-11-07", "rate": 20}), ("ABC", {"name": "2013-11-08", "rate": 40}), ], } self.assertEqual(map_record.values(), expected) expected = { "name": "SO1", "line_ids": [ ("ABC", {"name": "2013-11-07", "rate": 20, "test": 0.5}), ("ABC", {"name": "2013-11-08", "rate": 40, "test": 0.5}), ], } self.assertEqual(map_record.values(for_create=True), expected) def test_mapping_record_children_void(self): """Map a record with children, using defined MapChild""" class LineMapper(Component): _name = "line.mapper" _inherit = "base.import.mapper" _apply_on = "res.currency.rate" @mapping def price(self, record): rate = record.get("rate") if rate and rate < 40: return {"rate": record["rate"] * 2} class SaleLineImportMapChild(Component): _name = "sale.line.mapper" _inherit = "base.map.child.import" _apply_on = "res.currency.rate" def format_items(self, items_values): return [("ABC", values) for values in items_values] class ObjectMapper(Component): _name = "currency.mapper" _inherit = "base.import.mapper" _apply_on = "res.currency" direct = [("name", "name")] children = [("lines", "line_ids", "res.currency.rate")] self._build_components(ObjectMapper, SaleLineImportMapChild, LineMapper) # Test with an excluded child record record = { "name": "SO1", "lines": [{"rate": 10}, {"rate": 20}, {"rate": 30}, {"rate": 40}], } mapper = self.comp_registry["currency.mapper"](self.work) map_record = mapper.map_record(record) expected = { "name": "SO1", "line_ids": [ ("ABC", {"rate": 20}), ("ABC", {"rate": 40}), ("ABC", {"rate": 60}), ], } self.assertEqual(map_record.values(), expected)
33.097535
30,880
1,588
py
PYTHON
15.0
# Copyright 2018 Camptocamp SA # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). import mock from odoo import api from odoo.modules.registry import Registry from odoo.tests import common from odoo.addons.component.core import WorkContext from odoo.addons.component.tests.common import TransactionComponentRegistryCase from odoo.addons.queue_job.exception import RetryableJobError class TestLocker(TransactionComponentRegistryCase): def setUp(self): super().setUp() self.backend = mock.MagicMock(name="backend") self.backend.env = self.env self.registry2 = Registry(common.get_db_name()) self.cr2 = self.registry2.cursor() self.env2 = api.Environment(self.cr2, self.env.uid, {}) self.backend2 = mock.MagicMock(name="backend2") self.backend2.env = self.env2 @self.addCleanup def reset_cr2(): # rollback and close the cursor, and reset the environments self.env2.reset() self.cr2.rollback() self.cr2.close() def test_lock(self): """Lock a record""" main_partner = self.env.ref("base.main_partner") work = WorkContext(model_name="res.partner", collection=self.backend) work.component("record.locker").lock(main_partner) main_partner2 = self.env2.ref("base.main_partner") work2 = WorkContext(model_name="res.partner", collection=self.backend2) locker2 = work2.component("record.locker") with self.assertRaises(RetryableJobError): locker2.lock(main_partner2)
36.090909
1,588
3,950
py
PYTHON
15.0
# Copyright 2013 Camptocamp SA # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) from odoo import fields, models class ConnectorBackend(models.AbstractModel): """An instance of an external backend to synchronize with. The backends have to ``_inherit`` this model in the connectors modules. The components articulates around a collection, which in the context of the connectors is called a Backend. It must be defined as a Model that inherits from ``'connector.backend'``. Example with the Magento Connector:: # in connector_magento/models/magento_backend.py class MagentoBackend(models.Model): _name = 'magento.backend' _inherit = 'connector.backend' _description = 'Magento Backend' # the version in not mandatory @api.model def _select_versions(self): \"\"\" Available versions Can be inherited to add custom versions. \"\"\" return [('1.7', 'Magento 1.7')] location = fields.Char(string='Location', required=True) username = fields.Char(string='Username') password = fields.Char(string='Password') versions = fields.Selection( selection='_select_versions', required=True ) """ _name = "connector.backend" _inherit = ["collection.base"] _description = "Connector Backend" class ExternalBinding(models.AbstractModel): """An abstract model for bindings to external records. An external binding is a binding between a backend and Odoo. For example, for a partner, it could be ``magento.res.partner`` or for a product, ``magento.product``. The final model, will be an ``_inherits`` of the Odoo model and will ``_inherit`` this model. It will have a relation to the record (via ``_inherits``) and to the concrete backend model (``magento.backend`` for instance). It will also contains all the data relative to the backend for the record. It needs to implements at least these fields: odoo_id The many2one to the record it links (used by ``_inherits``). backend_id The many2one to the backend (for instance ``magento.backend``). external_id The ID on the backend. sync_date Last date of synchronization The definition of the field relations is to be done in the concrete classes because the relations themselves do not exist in this addon. For example, for a ``res.partner.category`` from Magento, I would have (this is a consolidation of all the columns from the abstract models, in ``magentoerpconnect`` you would not find that):: class MagentoResPartnerCategory(models.Model): _name = 'magento.res.partner.category' _inherits = {'res.partner.category': 'odoo_id'} odoo_id = fields.Many2one(comodel_name='res.partner.category', string='Partner Category', required=True, ondelete='cascade') backend_id = fields.Many2one( comodel_name='magento.backend', string='Magento Backend', required=True, ondelete='restrict') external_id = fields.Char(string='ID on Magento') tax_class_id = fields.Integer(string='Tax Class ID') _sql_constraints = [ ('magento_uniq', 'unique(backend_id, magento_id)', 'Partner Tag with same ID on Magento already exists.'), ] """ _name = "external.binding" _description = "External Binding (abstract)" sync_date = fields.Datetime(string="Last synchronization date") # add other fields in concrete models # XXX we could add a default 'external_id'
32.644628
3,950
1,533
py
PYTHON
15.0
# Copyright 2017 Camptocamp SA # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) from odoo import _, models class QueueJob(models.Model): _inherit = "queue.job" def related_action_unwrap_binding(self, component_usage="binder"): """Open a form view with the unwrapped record. For instance, for a job on a ``magento.product.product``, it will open a ``product.product`` form view with the unwrapped record. :param component_usage: base component usage to search for the binder """ self.ensure_one() model_name = self.model_name binding = self.env[model_name].browse(self.record_ids).exists() if not binding: return None if len(binding) > 1: # not handled return None action = { "name": _("Related Record"), "type": "ir.actions.act_window", "view_type": "form", "view_mode": "form", } with binding.backend_id.work_on(binding._name) as work: binder = work.component(usage=component_usage) try: model = binder.unwrap_model() record = binder.unwrap_binding(binding) # the unwrapped record will be displayed action.update({"res_model": model, "res_id": record.id}) except ValueError: # the binding record will be displayed action.update({"res_model": binding._name, "res_id": binding.id}) return action
34.840909
1,533
34,554
py
PYTHON
15.0
# Copyright 2017 Camptocamp SA # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) """ Mappers ======= Mappers are the components responsible to transform external records into Odoo records and conversely. """ import logging from collections import namedtuple from contextlib import contextmanager from odoo import models from odoo.addons.component.core import AbstractComponent from odoo.addons.component.exception import NoComponentError from ..exception import MappingError _logger = logging.getLogger(__name__) __all__ = [ "Mapper", "ImportMapper", "ExportMapper", "mapping", "changed_by", "only_create", "none", "convert", "m2o_to_external", "external_to_m2o", "follow_m2o_relations", "MapRecord", "MapChild", "ImportMapChild", "ExportMapChild", ] def mapping(func): """Decorator, declare that a method is a mapping method. It is then used by the :py:class:`Mapper` to convert the records. Usage:: @mapping def any(self, record): return {'output_field': record['input_field']} """ func.is_mapping = True return func def changed_by(*args): """Decorator for the mapping methods (:py:func:`mapping`) When fields are modified in Odoo, we want to export only the modified fields. Using this decorator, we can specify which fields updates should trigger which mapping method. If ``changed_by`` is empty, the mapping is always active. As far as possible, this decorator should be used for the exports, thus, when we do an update on only a small number of fields on a record, the size of the output record will be limited to only the fields really having to be exported. Usage:: @changed_by('input_field') @mapping def any(self, record): return {'output_field': record['input_field']} :param ``*args``: field names which trigger the mapping when modified """ def register_mapping(func): func.changed_by = args return func return register_mapping def only_create(func): """Decorator for the mapping methods (:py:func:`mapping`) A mapping decorated with ``only_create`` means that it has to be used only for the creation of the records. Usage:: @only_create @mapping def any(self, record): return {'output_field': record['input_field']} """ func.only_create = True return func def none(field): """A modifier intended to be used on the ``direct`` mappings. Replace the False-ish values by None. It can be used in a pipeline of modifiers when . Example:: direct = [(none('source'), 'target'), (none(m2o_to_external('rel_id'), 'rel_id')] :param field: name of the source field in the record :param binding: True if the relation is a binding record """ def modifier(self, record, to_attr): if callable(field): result = field(self, record, to_attr) else: result = record[field] if not result: return None return result return modifier def convert(field, conv_type): """A modifier intended to be used on the ``direct`` mappings. Convert a field's value to a given type. Example:: direct = [(convert('source', str), 'target')] :param field: name of the source field in the record :param binding: True if the relation is a binding record """ def modifier(self, record, to_attr): value = record[field] if not value: return False return conv_type(value) return modifier def m2o_to_external(field, binding=None): """A modifier intended to be used on the ``direct`` mappings. For a many2one, get the external ID and returns it. When the field's relation is not a binding (i.e. it does not point to something like ``magento.*``), the binding model needs to be provided in the ``binding`` keyword argument. Example:: direct = [(m2o_to_external('country_id', binding='magento.res.country'), 'country'), (m2o_to_external('magento_country_id'), 'country')] :param field: name of the source field in the record :param binding: name of the binding model if the relation is not a binding """ def modifier(self, record, to_attr): if not record[field]: return False column = self.model._fields[field] if column.type != "many2one": raise ValueError( "The column {} should be a Many2one, got {}".format(field, type(column)) ) rel_id = record[field].id if binding is None: binding_model = column.comodel_name else: binding_model = binding binder = self.binder_for(binding_model) # if a relation is not a binding, we wrap the record in the # binding, we'll return the id of the binding wrap = bool(binding) value = binder.to_external(rel_id, wrap=wrap) if not value: raise MappingError( "Can not find an external id for record " "%s in model %s %s wrapping" % (rel_id, binding_model, "with" if wrap else "without") ) return value return modifier def external_to_m2o(field, binding=None): """A modifier intended to be used on the ``direct`` mappings. For a field from a backend which is an ID, search the corresponding binding in Odoo and returns it. When the field's relation is not a binding (i.e. it does not point to something like ``magento.*``), the binding model needs to be provided in the ``binding`` keyword argument. Example:: direct = [(external_to_m2o('country', binding='magento.res.country'), 'country_id'), (external_to_m2o('country'), 'magento_country_id')] :param field: name of the source field in the record :param binding: name of the binding model if the relation is not a binding """ def modifier(self, record, to_attr): if not record[field]: return False column = self.model._fields[to_attr] if column.type != "many2one": raise ValueError( "The column {} should be a Many2one, got {}".format( to_attr, type(column) ) ) rel_id = record[field] if binding is None: binding_model = column.comodel_name else: binding_model = binding binder = self.binder_for(binding_model) # if we want the normal record, not a binding, # we ask to the binder to unwrap the binding unwrap = bool(binding) record = binder.to_internal(rel_id, unwrap=unwrap) if not record: raise MappingError( "Can not find an existing %s for external " "record %s %s unwrapping" % (binding_model, rel_id, "with" if unwrap else "without") ) if isinstance(record, models.BaseModel): return record.id else: _logger.debug( "Binder for %s returned an id, " "returning a record should be preferred.", binding_model, ) return record return modifier def follow_m2o_relations(field): """A modifier intended to be used on ``direct`` mappings. 'Follows' Many2one relations and return the final field value. Examples: Assuming model is ``product.product``:: direct = [ (follow_m2o_relations('product_tmpl_id.categ_id.name'), 'cat')] :param field: field "path", using dots for relations as usual in Odoo """ def modifier(self, record, to_attr): attrs = field.split(".") value = record for attr in attrs: value = getattr(value, attr) return value return modifier MappingDefinition = namedtuple("MappingDefinition", ["changed_by", "only_create"]) class MapChild(AbstractComponent): """MapChild is responsible to convert items. Items are sub-records of a main record. In this example, the items are the records in ``lines``:: sales = {'name': 'SO10', 'lines': [{'product_id': 1, 'quantity': 2}, {'product_id': 2, 'quantity': 2}]} A MapChild is always called from another :py:class:`Mapper` which provides a ``children`` configuration. Considering the example above, the "main" :py:class:`Mapper` would returns something as follows:: {'name': 'SO10', 'lines': [(0, 0, {'product_id': 11, 'quantity': 2}), (0, 0, {'product_id': 12, 'quantity': 2})]} A MapChild is responsible to: * Find the :py:class:`Mapper` to convert the items * Possibly filter out some lines (can be done by inheriting :py:meth:`skip_item`) * Convert the items' records using the found :py:class:`Mapper` * Format the output values to the format expected by Odoo or the backend (as seen above with ``(0, 0, {values})`` A MapChild can be extended like any other :py:class:`~component.core.Component`. However, it is not mandatory to explicitly create a MapChild for each children mapping, the default one will be used (:py:class:`ImportMapChild` or :py:class:`ExportMapChild`). The implementation by default does not take care of the updates: if I import a sales order 2 times, the lines will be duplicated. This is not a problem as long as an importation should only support the creation (typical for sales orders). It can be implemented on a case-by-case basis by inheriting :py:meth:`get_item_values` and :py:meth:`format_items`. """ _name = "base.map.child" _inherit = "base.connector" def _child_mapper(self): raise NotImplementedError def skip_item(self, map_record): """Hook to implement in sub-classes when some child records should be skipped. The parent record is accessible in ``map_record``. If it returns True, the current child record is skipped. :param map_record: record that we are converting :type map_record: :py:class:`MapRecord` """ return False def get_items(self, items, parent, to_attr, options): """Returns the formatted output values of items from a main record :param items: list of item records :type items: list :param parent: parent record :param to_attr: destination field (can be used for introspecting the relation) :type to_attr: str :param options: dict of options, herited from the main mapper :return: formatted output values for the item """ mapper = self._child_mapper() mapped = [] for item in items: map_record = mapper.map_record(item, parent=parent) if self.skip_item(map_record): continue item_values = self.get_item_values(map_record, to_attr, options) if item_values: mapped.append(item_values) return self.format_items(mapped) def get_item_values(self, map_record, to_attr, options): """Get the raw values from the child Mappers for the items. It can be overridden for instance to: * Change options * Use a :py:class:`~connector.connector.Binder` to know if an item already exists to modify an existing item, rather than to add it :param map_record: record that we are converting :type map_record: :py:class:`MapRecord` :param to_attr: destination field (can be used for introspecting the relation) :type to_attr: str :param options: dict of options, herited from the main mapper """ return map_record.values(**options) def format_items(self, items_values): """Format the values of the items mapped from the child Mappers. It can be overridden for instance to add the Odoo relationships commands ``(6, 0, [IDs])``, ... As instance, it can be modified to handle update of existing items: check if an 'id' has been defined by :py:meth:`get_item_values` then use the ``(1, ID, {values}``) command :param items_values: mapped values for the items :type items_values: list """ return items_values class ImportMapChild(AbstractComponent): """:py:class:`MapChild` for the Imports""" _name = "base.map.child.import" _inherit = "base.map.child" _usage = "import.map.child" def _child_mapper(self): return self.component(usage="import.mapper") def format_items(self, items_values): """Format the values of the items mapped from the child Mappers. It can be overridden for instance to add the Odoo relationships commands ``(6, 0, [IDs])``, ... As instance, it can be modified to handle update of existing items: check if an 'id' has been defined by :py:meth:`get_item_values` then use the ``(1, ID, {values}``) command :param items_values: list of values for the items to create :type items_values: list """ return [(0, 0, values) for values in items_values] class ExportMapChild(AbstractComponent): """:py:class:`MapChild` for the Exports""" _name = "base.map.child.export" _inherit = "base.map.child" _usage = "export.map.child" def _child_mapper(self): return self.component(usage="export.mapper") class Mapper(AbstractComponent): """A Mapper translates an external record to an Odoo record and conversely. The output of a Mapper is a ``dict``. 3 types of mappings are supported: Direct Mappings Example:: direct = [('source', 'target')] Here, the ``source`` field will be copied in the ``target`` field. A modifier can be used in the source item. The modifier will be applied to the source field before being copied in the target field. It should be a closure function respecting this idiom:: def a_function(field): ''' ``field`` is the name of the source field. Naming the arg: ``field`` is required for the conversion''' def modifier(self, record, to_attr): ''' self is the current Mapper, record is the current record to map, to_attr is the target field''' return record[field] return modifier And used like that:: direct = [ (a_function('source'), 'target'), ] A more concrete example of modifier:: def convert(field, conv_type): ''' Convert the source field to a defined ``conv_type`` (ex. str) before returning it''' def modifier(self, record, to_attr): value = record[field] if not value: return None return conv_type(value) return modifier And used like that:: direct = [ (convert('myfield', float), 'target_field'), ] More examples of modifiers: * :py:func:`convert` * :py:func:`m2o_to_external` * :py:func:`external_to_m2o` Method Mappings A mapping method allows to execute arbitrary code and return one or many fields:: @mapping def compute_state(self, record): # compute some state, using the ``record`` or not state = 'pending' return {'state': state} We can also specify that a mapping methods should be applied only when an object is created, and never applied on further updates:: @only_create @mapping def default_warehouse(self, record): # get default warehouse warehouse_id = ... return {'warehouse_id': warehouse_id} Submappings When a record contains sub-items, like the lines of a sales order, we can convert the children using another Mapper:: children = [('items', 'line_ids', 'model.name')] It allows to create the sales order and all its lines with the same call to :py:meth:`odoo.models.BaseModel.create()`. When using ``children`` for items of a record, we need to create a :py:class:`Mapper` for the model of the items, and optionally a :py:class:`MapChild`. Usage of a Mapper:: >>> mapper = self.component(usage='mapper') >>> map_record = mapper.map_record(record) >>> values = map_record.values() >>> values = map_record.values(for_create=True) >>> values = map_record.values(fields=['name', 'street']) """ _name = "base.mapper" _inherit = "base.connector" _usage = "mapper" direct = [] # direct conversion of a field to another (from_attr, to_attr) children = [] # conversion of sub-records (from_attr, to_attr, model) _map_methods = None _map_child_usage = None _map_child_fallback = None @classmethod def _build_mapper_component(cls): """Build a Mapper component When a Mapper component is built, we will look into every of its bases and look for methods decorated by ``@mapping`` or ``@changed_by``. We keep the definitions in a ``_map_methods`` attribute for later use by the Mapper instances. The ``__bases__`` of a newly generated Component are of 2 kinds: * other dynamically generated components (below 'base' and 'second.mapper') * "real" Python classes applied on top of existing components (here ThirdMapper) :: >>> cls.__bases__ (<class 'odoo.addons.connector.tests.test_mapper.ThirdMapper'>, <class 'odoo.addons.component.core.second.mapper'>, <class 'odoo.addons.component.core.base'>) This method traverses these bases, from the bottom to the top, and merges the mapping definitions. It reuses the computed definitions for the generated components (for which this code already ran), and inspect the real classes to find mapping methods. """ map_methods = {} for base in reversed(cls.__bases__): if hasattr(base, "_map_methods"): # this is already a dynamically generated Component, so we can # use its existing mappings base_map_methods = base._map_methods or {} for attr_name, definition in base_map_methods.items(): if attr_name in map_methods: # Update the existing @changed_by with the content # of each base (it is mutated in place). mapping_changed_by = map_methods[attr_name].changed_by mapping_changed_by.update(definition.changed_by) # keep the last value for @only_create if definition.only_create: new_definition = MappingDefinition( mapping_changed_by, definition.only_create ) map_methods[attr_name] = new_definition else: map_methods[attr_name] = definition else: # this is a real class that needs to be applied upon # the base Components for attr_name in dir(base): attr = getattr(base, attr_name, None) if not getattr(attr, "is_mapping", None): continue has_only_create = getattr(attr, "only_create", False) mapping_changed_by = set(getattr(attr, "changed_by", ())) # if already existing, it has been defined in an previous # base, extend the @changed_by set if map_methods.get(attr_name) is not None: definition = map_methods[attr_name] mapping_changed_by.update(definition.changed_by) # keep the last choice for only_create definition = MappingDefinition(mapping_changed_by, has_only_create) map_methods[attr_name] = definition cls._map_methods = map_methods # pylint: disable=W8110 @classmethod def _complete_component_build(cls): super(Mapper, cls)._complete_component_build() cls._build_mapper_component() def __init__(self, work): super(Mapper, self).__init__(work) self._options = None def _map_direct(self, record, from_attr, to_attr): """Apply the ``direct`` mappings. :param record: record to convert from a source to a target :param from_attr: name of the source attribute or a callable :type from_attr: callable | str :param to_attr: name of the target attribute :type to_attr: str """ raise NotImplementedError def _map_children(self, record, attr, model): raise NotImplementedError @property def map_methods(self): """Yield all the methods decorated with ``@mapping``""" for meth, definition in self._map_methods.items(): yield getattr(self, meth), definition def _get_map_child_component(self, model_name): try: mapper_child = self.component( usage=self._map_child_usage, model_name=model_name ) except NoComponentError: assert self._map_child_fallback is not None, "_map_child_fallback required" # does not force developers to use a MapChild -> # will use the default one if not explicitely defined mapper_child = self.component_by_name( self._map_child_fallback, model_name=model_name ) return mapper_child def _map_child(self, map_record, from_attr, to_attr, model_name): """Convert items of the record as defined by children""" assert self._map_child_usage is not None, "_map_child_usage required" child_records = map_record.source[from_attr] mapper_child = self._get_map_child_component(model_name) items = mapper_child.get_items( child_records, map_record, to_attr, options=self.options ) return items @contextmanager def _mapping_options(self, options): """Change the mapping options for the Mapper. Context Manager to use in order to alter the behavior of the mapping, when using ``_apply`` or ``finalize``. """ current = self._options self._options = options yield self._options = current @property def options(self): """Options can be accessed in the mapping methods with ``self.options``.""" return self._options def changed_by_fields(self): """Build a set of fields used by the mapper It takes in account the ``direct`` fields and the fields used by the decorator: ``changed_by``. """ changed_by = set() if getattr(self, "direct", None): for from_attr, __ in self.direct: fieldname = self._direct_source_field_name(from_attr) changed_by.add(fieldname) for _method_name, method_def in self._map_methods.items(): changed_by |= method_def.changed_by return changed_by def _direct_source_field_name(self, direct_entry): """Get the mapping field name. Goes through the function modifiers. Ex:: [(none(convert(field_name, str)), out_field_name)] It assumes that the modifier has ``field`` as first argument like:: def modifier(field, args): """ fieldname = direct_entry if callable(direct_entry): # Map the closure entries with variable names cells = dict( list( zip( direct_entry.__code__.co_freevars, (c.cell_contents for c in direct_entry.__closure__), ) ) ) assert "field" in cells, "Modifier without 'field' argument." if callable(cells["field"]): fieldname = self._direct_source_field_name(cells["field"]) else: fieldname = cells["field"] return fieldname def map_record(self, record, parent=None): """Get a :py:class:`MapRecord` with record, ready to be converted using the current Mapper. :param record: record to transform :param parent: optional parent record, for items """ return MapRecord(self, record, parent=parent) def _apply(self, map_record, options=None): """Apply the mappings on a :py:class:`MapRecord` :param map_record: source record to convert :type map_record: :py:class:`MapRecord` """ if options is None: options = {} with self._mapping_options(options): return self._apply_with_options(map_record) def _apply_with_options(self, map_record): """Apply the mappings on a :py:class:`MapRecord` with contextual options (the ``options`` given in :py:meth:`MapRecord.values()` are accessible in ``self.options``) :param map_record: source record to convert :type map_record: :py:class:`MapRecord` """ assert ( self.options is not None ), "options should be defined with '_mapping_options'" _logger.debug("converting record %s to model %s", map_record.source, self.model) fields = self.options.fields for_create = self.options.for_create result = {} for from_attr, to_attr in self.direct: if callable(from_attr): attr_name = self._direct_source_field_name(from_attr) else: attr_name = from_attr if not fields or attr_name in fields: value = self._map_direct(map_record.source, from_attr, to_attr) result[to_attr] = value for meth, definition in self.map_methods: mapping_changed_by = definition.changed_by if ( not fields or not mapping_changed_by or mapping_changed_by.intersection(fields) ): if definition.only_create and not for_create: continue values = meth(map_record.source) if not values: continue if not isinstance(values, dict): raise ValueError( "%s: invalid return value for the " "mapping method %s" % (values, meth) ) result.update(values) for from_attr, to_attr, model_name in self.children: if not fields or from_attr in fields: result[to_attr] = self._map_child( map_record, from_attr, to_attr, model_name ) return self.finalize(map_record, result) def finalize(self, map_record, values): """Called at the end of the mapping. Can be used to modify the values generated by all the mappings before returning them. :param map_record: source map_record :type map_record: :py:class:`MapRecord` :param values: mapped values :returns: mapped values :rtype: dict """ return values class ImportMapper(AbstractComponent): """:py:class:`Mapper` for imports. Transform a record from a backend to an Odoo record """ _name = "base.import.mapper" _inherit = "base.mapper" _usage = "import.mapper" _map_child_usage = "import.map.child" _map_child_fallback = "base.map.child.import" def _map_direct(self, record, from_attr, to_attr): """Apply the ``direct`` mappings. :param record: record to convert from a source to a target :param from_attr: name of the source attribute or a callable :type from_attr: callable | str :param to_attr: name of the target attribute :type to_attr: str """ if callable(from_attr): return from_attr(self, record, to_attr) value = record.get(from_attr) if not value: return False # Backward compatibility: when a field is a relation, and a modifier is # not used, we assume that the relation model is a binding. # Use an explicit modifier external_to_m2o in the 'direct' mappings to # change that. field = self.model._fields[to_attr] if field.type == "many2one": mapping_func = external_to_m2o(from_attr) value = mapping_func(self, record, to_attr) return value class ExportMapper(AbstractComponent): """:py:class:`Mapper` for exports. Transform a record from Odoo to a backend record """ _name = "base.export.mapper" _inherit = "base.mapper" _usage = "export.mapper" _map_child_usage = "export.map.child" _map_child_fallback = "base.map.child.export" def _map_direct(self, record, from_attr, to_attr): """Apply the ``direct`` mappings. :param record: record to convert from a source to a target :param from_attr: name of the source attribute or a callable :type from_attr: callable | str :param to_attr: name of the target attribute :type to_attr: str """ if callable(from_attr): return from_attr(self, record, to_attr) value = record[from_attr] if not value: return False # Backward compatibility: when a field is a relation, and a modifier is # not used, we assume that the relation model is a binding. # Use an explicit modifier m2o_to_external in the 'direct' mappings to # change that. field = self.model._fields[from_attr] if field.type == "many2one": mapping_func = m2o_to_external(from_attr) value = mapping_func(self, record, to_attr) return value class MapRecord: """A record prepared to be converted using a :py:class:`Mapper`. MapRecord instances are prepared by :py:meth:`Mapper.map_record`. Usage:: >>> map_record = mapper.map_record(record) >>> output_values = map_record.values() See :py:meth:`values` for more information on the available arguments. """ def __init__(self, mapper, source, parent=None): self._source = source self._mapper = mapper self._parent = parent self._forced_values = {} @property def source(self): """Source record to be converted""" return self._source @property def parent(self): """Parent record if the current record is an item""" return self._parent def values(self, for_create=None, fields=None, **kwargs): """Build and returns the mapped values according to the options. Usage:: >>> map_record = mapper.map_record(record) >>> output_values = map_record.values() Creation of records When using the option ``for_create``, only the mappings decorated with ``@only_create`` will be mapped. :: >>> output_values = map_record.values(for_create=True) Filter on fields When using the ``fields`` argument, the mappings will be filtered using either the source key in ``direct`` arguments, either the ``changed_by`` arguments for the mapping methods. :: >>> output_values = map_record.values( fields=['name', 'street'] ) Custom options Arbitrary key and values can be defined in the ``kwargs`` arguments. They can later be used in the mapping methods using ``self.options``. :: >>> output_values = map_record.values(tax_include=True) :param for_create: specify if only the mappings for creation (``@only_create``) should be mapped. :type for_create: boolean :param fields: filter on fields :type fields: list :param ``**kwargs``: custom options, they can later be used in the mapping methods """ options = MapOptions(for_create=for_create, fields=fields, **kwargs) values = self._mapper._apply(self, options=options) values.update(self._forced_values) return values def update(self, *args, **kwargs): """Force values to be applied after a mapping. Usage:: >>> map_record = mapper.map_record(record) >>> map_record.update(a=1) >>> output_values = map_record.values() # output_values will at least contain {'a': 1} The values assigned with ``update()`` are in any case applied, they have a greater priority than the mapping values. """ self._forced_values.update(*args, **kwargs) class MapOptions(dict): """Container for the options of mappings. Options can be accessed using attributes of the instance. When an option is accessed and does not exist, it returns None. """ def __getitem__(self, key): try: return super(MapOptions, self).__getitem__(key) except KeyError: return None def __getattr__(self, key): return self[key] def __setattr__(self, key, value): self[key] = value
32.783681
34,554
1,781
py
PYTHON
15.0
# Copyright 2013 Camptocamp SA # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) """ Backend Adapter =============== An external adapter has a common interface to speak with the backend. It translates the basic orders (search, read, write) to the protocol used by the backend. """ from odoo.addons.component.core import AbstractComponent class BackendAdapter(AbstractComponent): """Base Backend Adapter for the connectors""" _name = "base.backend.adapter" _inherit = "base.connector" _usage = "backend.adapter" # pylint: disable=W8106 class CRUDAdapter(AbstractComponent): """Base External Adapter specialized in the handling of records on external systems. This is an empty shell, Components can inherit and implement their own implementation for the methods. """ _name = "base.backend.adapter.crud" _inherit = "base.backend.adapter" _usage = "backend.adapter" def search(self, *args, **kwargs): """Search records according to some criterias and returns a list of ids""" raise NotImplementedError def read(self, *args, **kwargs): """Returns the information of a record""" raise NotImplementedError def search_read(self, *args, **kwargs): """Search records according to some criterias and returns their information""" raise NotImplementedError def create(self, *args, **kwargs): """Create a record on the external system""" raise NotImplementedError def write(self, *args, **kwargs): """Update records on the external system""" raise NotImplementedError def delete(self, *args, **kwargs): """Delete a record on the external system""" raise NotImplementedError
27.828125
1,781
2,685
py
PYTHON
15.0
# Copyright 2018 Camptocamp SA # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) import logging import psycopg2 from odoo.addons.component.core import Component from ..exception import RetryableJobError _logger = logging.getLogger(__name__) class RecordLocker(Component): """Component allowing to lock record(s) for the current transaction Example of usage:: self.component('record.locker').lock(self.records) See the definition of :meth:`~lock` for details. """ _name = "base.record.locker" _inherit = ["base.connector"] _usage = "record.locker" def lock(self, records, seconds=None, ignore_retry=True): """Lock the records. Lock the record so we are sure that only one job is running for this record(s) if concurrent jobs have to run a job for the same record(s). When concurrent jobs try to work on the same record(s), the first one will lock and proceed, the others will fail to acquire it and will be retried later (:exc:`~odoo.addons.queue_job.exception.RetryableJobError` is raised). The lock is using a ``FOR UPDATE NOWAIT`` so any concurrent transaction trying FOR UPDATE/UPDATE will be rejected until the current transaction is committed or rollbacked. A classical use case for this is to prevent concurrent exports. The following parameters are forwarded to the exception :exc:`~odoo.addons.queue_job.exception.RetryableJobError` :param seconds: In case of retry because the lock cannot be acquired, in how many seconds it must be retried. If not set, the queue_job configuration is used. :param ignore_retry: If True, the retry counter of the job will not be increased. """ sql = "SELECT id FROM %s WHERE ID IN %%s FOR UPDATE NOWAIT" % self.model._table try: self.env.cr.execute(sql, (tuple(records.ids),), log_exceptions=False) except psycopg2.OperationalError as err: _logger.info( "A concurrent job is already working on the same " "record (%s with one id in %s). Job delayed later.", self.model._name, tuple(records.ids), ) raise RetryableJobError( "A concurrent job is already working on the same record " "(%s with one id in %s). The job will be retried later." % (self.model._name, tuple(records.ids)), seconds=seconds, ignore_retry=ignore_retry, ) from err
38.357143
2,685
4,397
py
PYTHON
15.0
# Copyright 2017 Camptocamp SA # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) """ Base Component ============== The connector proposes a 'base' Component, which can be used in the ``_inherit`` of your own components. This is not a requirement. It is already inherited by every component provided by the Connector. Components are organized according to different usages. The connector suggests 5 main kinds of Components. Each might have a few different usages. You can be as creative as you want when it comes to creating new ones though. One "usage" is responsible for a specific work, and alongside with the collection (the backend) and the model, the usage will be used to find the needed component for a task. Some of the Components have an implementation in the ``Connector`` addon, but some are empty shells that need to be implemented in the different connectors. The usual categories are: :py:class:`~connector.components.binder.Binder` The ``binders`` give the external ID or Odoo ID from respectively an Odoo ID or an external ID. A default implementation is available. Most common usages: * ``binder`` :py:class:`~connector.components.mapper.Mapper` The ``mappers`` transform a external record into an Odoo record or conversely. Most common usages: * ``import.mapper`` * ``export.mapper`` :py:class:`~connector.components.backend_adapter.BackendAdapter` The ``backend.adapters`` implements the discussion with the ``backend's`` APIs. They usually adapt their APIs to a common interface (CRUD). Most common usages: * ``backend.adapter`` :py:class:`~connector.components.synchronizer.Synchronizer` A ``synchronizer`` is the main piece of a synchronization. It orchestrates the flow of a synchronization and use the other Components Most common usages: * ``record.importer`` * ``record.exporter`` * ``batch.importer`` * ``batch.exporter`` The possibilities for components do not stop there, look at the :class:`~connector.components.locker.RecordLocker` for an example of single-purpose, decoupled component. """ from odoo.addons.component.core import AbstractComponent from odoo.addons.queue_job.exception import RetryableJobError from ..database import pg_try_advisory_lock class BaseConnectorComponent(AbstractComponent): """Base component for the connector Is inherited by every components of the Connector (Binder, Mapper, ...) and adds a few methods which are of common usage in the connectors. """ _name = "base.connector" @property def backend_record(self): """Backend record we are working with""" # backward compatibility return self.work.collection def binder_for(self, model=None): """Shortcut to get Binder for a model Equivalent to: ``self.component(usage='binder', model_name='xxx')`` """ return self.component(usage="binder", model_name=model) def advisory_lock_or_retry(self, lock, retry_seconds=1): """Acquire a Postgres transactional advisory lock or retry job When the lock cannot be acquired, it raises a :exc:`odoo.addons.queue_job.exception.RetryableJobError` so the job is retried after n ``retry_seconds``. Usage example: .. code-block:: python lock_name = 'import_record({}, {}, {}, {})'.format( self.backend_record._name, self.backend_record.id, self.model._name, self.external_id, ) self.advisory_lock_or_retry(lock_name, retry_seconds=2) See :func:`odoo.addons.connector.connector.pg_try_advisory_lock` for details. :param lock: The lock name. Can be anything convertible to a string. It needs to represent what should not be synchronized concurrently, usually the string will contain at least: the action, the backend name, the backend id, the model name, the external id :param retry_seconds: number of seconds after which a job should be retried when the lock cannot be acquired. """ if not pg_try_advisory_lock(self.env, lock): raise RetryableJobError( "Could not acquire advisory lock", seconds=retry_seconds, ignore_retry=True, )
32.330882
4,397
5,226
py
PYTHON
15.0
# Copyright 2013 Camptocamp SA # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) """ Binders ======= Binders are components that know how to find the external ID for an Odoo ID, how to find the Odoo ID for an external ID and how to create the binding between them. """ from odoo import fields, models, tools from odoo.addons.component.core import AbstractComponent class Binder(AbstractComponent): """For one record of a model, capable to find an external or internal id, or create the binding (link) between them This is a default implementation that can be inherited or reimplemented in the connectors. This implementation assumes that binding models are ``_inherits`` of the models they are binding. """ _name = "base.binder" _inherit = "base.connector" _usage = "binder" _external_field = "external_id" # override in sub-classes _backend_field = "backend_id" # override in sub-classes _odoo_field = "odoo_id" # override in sub-classes _sync_date_field = "sync_date" # override in sub-classes def to_internal(self, external_id, unwrap=False): """Give the Odoo recordset for an external ID :param external_id: external ID for which we want the Odoo ID :param unwrap: if True, returns the normal record else return the binding record :return: a recordset, depending on the value of unwrap, or an empty recordset if the external_id is not mapped :rtype: recordset """ context = self.env.context bindings = self.model.with_context(active_test=False).search( [ (self._external_field, "=", tools.ustr(external_id)), (self._backend_field, "=", self.backend_record.id), ] ) if not bindings: if unwrap: return self.model.browse()[self._odoo_field] return self.model.browse() bindings.ensure_one() if unwrap: bindings = bindings[self._odoo_field] bindings = bindings.with_context(**context) return bindings def to_external(self, binding, wrap=False): """Give the external ID for an Odoo binding ID :param binding: Odoo binding for which we want the external id :param wrap: if True, binding is a normal record, the method will search the corresponding binding and return the external id of the binding :return: external ID of the record """ if isinstance(binding, models.BaseModel): binding.ensure_one() else: binding = self.model.browse(binding) if wrap: binding = self.model.with_context(active_test=False).search( [ (self._odoo_field, "=", binding.id), (self._backend_field, "=", self.backend_record.id), ] ) if not binding: return None binding.ensure_one() return binding[self._external_field] return binding[self._external_field] def bind(self, external_id, binding): """Create the link between an external ID and an Odoo ID :param external_id: external id to bind :param binding: Odoo record to bind :type binding: int """ # Prevent False, None, or "", but not 0 assert ( external_id or external_id == 0 ) and binding, "external_id or binding missing, " "got: %s, %s" % ( external_id, binding, ) # avoid to trigger the export when we modify the `external_id` now_fmt = fields.Datetime.now() if isinstance(binding, models.BaseModel): binding.ensure_one() else: binding = self.model.browse(binding) binding.with_context(connector_no_export=True).write( { self._external_field: tools.ustr(external_id), self._sync_date_field: now_fmt, } ) def unwrap_binding(self, binding): """For a binding record, gives the normal record. Example: when called with a ``magento.product.product`` id, it will return the corresponding ``product.product`` id. :param browse: when True, returns a browse_record instance rather than an ID """ if isinstance(binding, models.BaseModel): binding.ensure_one() else: binding = self.model.browse(binding) return binding[self._odoo_field] def unwrap_model(self): """For a binding model, gives the normal model. Example: when called on a binder for ``magento.product.product``, it will return ``product.product``. """ try: column = self.model._fields[self._odoo_field] except KeyError as err: raise ValueError( "Cannot unwrap model %s, because it has no %s fields" % (self.model._name, self._odoo_field) ) from err return column.comodel_name
34.84
5,226
16,229
py
PYTHON
15.0
# Copyright 2013 Camptocamp SA # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) """ Synchronizer ============ A synchronizer orchestrates a synchronization with a backend. It's the actor who runs the flow and glues the logic of an import or export (or else). It uses other components for specialized tasks. For instance, it will use the mappings to convert the data between both systems, the backend adapters to read or write data on the backend and the binders to create the link between them. """ import logging from contextlib import contextmanager import psycopg2 import odoo from odoo import _ from odoo.addons.component.core import AbstractComponent from ..exception import IDMissingInBackend, RetryableJobError _logger = logging.getLogger(__name__) class Synchronizer(AbstractComponent): """Base class for synchronizers""" _name = "base.synchronizer" _inherit = "base.connector" #: usage of the component used as mapper, can be customized in sub-classes _base_mapper_usage = "mapper" #: usage of the component used as backend adapter, #: can be customized in sub-classes _base_backend_adapter_usage = "backend.adapter" def __init__(self, work_context): super(Synchronizer, self).__init__(work_context) self._backend_adapter = None self._binder = None self._mapper = None def run(self): """Run the synchronization""" raise NotImplementedError @property def mapper(self): """Return an instance of ``Mapper`` for the synchronization. The instantiation is delayed because some synchronizations do not need such an unit and the unit may not exist. It looks for a Component with ``_usage`` being equal to ``_base_mapper_usage``. :rtype: :py:class:`odoo.addons.component.core.Component` """ if self._mapper is None: self._mapper = self.component(usage=self._base_mapper_usage) return self._mapper @property def binder(self): """Return an instance of ``Binder`` for the synchronization. The instantiations is delayed because some synchronizations do not need such an unit and the unit may not exist. :rtype: :py:class:`odoo.addons.component.core.Component` """ if self._binder is None: self._binder = self.binder_for() return self._binder @property def backend_adapter(self): """Return an instance of ``BackendAdapter`` for the synchronization. The instantiations is delayed because some synchronizations do not need such an unit and the unit may not exist. It looks for a Component with ``_usage`` being equal to ``_base_backend_adapter_usage``. :rtype: :py:class:`odoo.addons.component.core.Component` """ if self._backend_adapter is None: self._backend_adapter = self.component( usage=self._base_backend_adapter_usage ) return self._backend_adapter class Exporter(AbstractComponent): """Synchronizer for exporting data from Odoo to a backend""" _name = "base.exporter" _inherit = "base.synchronizer" _usage = "exporter" #: usage of the component used as mapper, can be customized in sub-classes _base_mapper_usage = "export.mapper" class GenericExporter(AbstractComponent): """Generic Synchronizer for exporting data from Odoo to a backend""" _name = "generic.exporter" _inherit = "base.exporter" _default_binding_field = None def __init__(self, working_context): super(GenericExporter, self).__init__(working_context) self.binding = None self.external_id = None def _should_import(self): return False def _delay_import(self): """Schedule an import of the record. Adapt in the sub-classes when the model is not imported using ``import_record``. """ # force is True because the sync_date will be more recent # so the import would be skipped assert self.external_id self.binding.with_delay().import_record( self.backend_record, self.external_id, force=True ) def run(self, binding, *args, **kwargs): """Run the synchronization :param binding: binding record to export """ self.binding = binding self.external_id = self.binder.to_external(self.binding) try: should_import = self._should_import() except IDMissingInBackend: self.external_id = None should_import = False if should_import: self._delay_import() result = self._run(*args, **kwargs) self.binder.bind(self.external_id, self.binding) # Commit so we keep the external ID when there are several # exports (due to dependencies) and one of them fails. # The commit will also release the lock acquired on the binding # record if not odoo.tools.config["test_enable"]: self.env.cr.commit() # pylint: disable=E8102 self._after_export() return result def _run(self, fields=None): """Flow of the synchronization, implemented in inherited classes""" assert self.binding if not self.external_id: fields = None # should be created with all the fields if self._has_to_skip(): return # export the missing linked resources self._export_dependencies() # prevent other jobs to export the same record # will be released on commit (or rollback) self._lock() map_record = self._map_data() if self.external_id: record = self._update_data(map_record, fields=fields) if not record: return _("Nothing to export.") self._update(record) else: record = self._create_data(map_record, fields=fields) if not record: return _("Nothing to export.") self.external_id = self._create(record) return _("Record exported with ID %s on Backend.") % self.external_id def _after_export(self): """Can do several actions after exporting a record on the backend""" def _lock(self): """Lock the binding record. Lock the binding record so we are sure that only one export job is running for this record if concurrent jobs have to export the same record. When concurrent jobs try to export the same record, the first one will lock and proceed, the others will fail to lock and will be retried later. This behavior works also when the export becomes multilevel with :meth:`_export_dependencies`. Each level will set its own lock on the binding record it has to export. """ sql = "SELECT id FROM %s WHERE ID = %%s FOR UPDATE NOWAIT" % self.model._table try: self.env.cr.execute(sql, (self.binding.id,), log_exceptions=False) except psycopg2.OperationalError as err: _logger.info( "A concurrent job is already exporting the same " "record (%s with id %s). Job delayed later.", self.model._name, self.binding.id, ) raise RetryableJobError( "A concurrent job is already exporting the same record " "(%s with id %s). The job will be retried later." % (self.model._name, self.binding.id) ) from err def _has_to_skip(self): """Return True if the export can be skipped""" return False @contextmanager def _retry_unique_violation(self): """Context manager: catch Unique constraint error and retry the job later. When we execute several jobs workers concurrently, it happens that 2 jobs are creating the same record at the same time (binding record created by :meth:`_export_dependency`), resulting in: IntegrityError: duplicate key value violates unique constraint "my_backend_product_product_odoo_uniq" DETAIL: Key (backend_id, odoo_id)=(1, 4851) already exists. In that case, we'll retry the import just later. .. warning:: The unique constraint must be created on the binding record to prevent 2 bindings to be created for the same External record. """ try: yield except psycopg2.IntegrityError as err: if err.pgcode == psycopg2.errorcodes.UNIQUE_VIOLATION: raise RetryableJobError( "A database error caused the failure of the job:\n" "%s\n\n" "Likely due to 2 concurrent jobs wanting to create " "the same record. The job will be retried later." % err ) from err else: raise def _export_dependency( self, relation, binding_model, component_usage="record.exporter", binding_field=None, binding_extra_vals=None, ): """ Export a dependency. The exporter class is a subclass of ``GenericExporter``. If a more precise class need to be defined, it can be passed to the ``exporter_class`` keyword argument. .. warning:: a commit is done at the end of the export of each dependency. The reason for that is that we pushed a record on the backend and we absolutely have to keep its ID. So you *must* take care not to modify the Odoo database during an export, excepted when writing back the external ID or eventually to store external data that we have to keep on this side. You should call this method only at the beginning of the exporter synchronization, in :meth:`~._export_dependencies`. :param relation: record to export if not already exported :type relation: :py:class:`odoo.models.BaseModel` :param binding_model: name of the binding model for the relation :type binding_model: str | unicode :param component_usage: 'usage' to look for to find the Component to for the export, by default 'record.exporter' :type exporter: str | unicode :param binding_field: name of the one2many field on a normal record that points to the binding record (default: my_backend_bind_ids). It is used only when the relation is not a binding but is a normal record. :type binding_field: str | unicode :binding_extra_vals: In case we want to create a new binding pass extra values for this binding :type binding_extra_vals: dict """ if binding_field is None: binding_field = self._default_binding_field if not relation: return rel_binder = self.binder_for(binding_model) # wrap is typically True if the relation is for instance a # 'product.product' record but the binding model is # 'my_bakend.product.product' wrap = relation._name != binding_model if wrap and hasattr(relation, binding_field): domain = [ ("odoo_id", "=", relation.id), ("backend_id", "=", self.backend_record.id), ] binding = self.env[binding_model].search(domain) if binding: assert len(binding) == 1, ( "only 1 binding for a backend is " "supported in _export_dependency" ) # we are working with a unwrapped record (e.g. # product.category) and the binding does not exist yet. # Example: I created a product.product and its binding # my_backend.product.product and we are exporting it, but we need # to create the binding for the product.category on which it # depends. else: bind_values = { "backend_id": self.backend_record.id, "odoo_id": relation.id, } if binding_extra_vals: bind_values.update(binding_extra_vals) # If 2 jobs create it at the same time, retry # one later. A unique constraint (backend_id, # odoo_id) should exist on the binding model with self._retry_unique_violation(): binding = ( self.env[binding_model] .with_context(connector_no_export=True) .sudo() .create(bind_values) ) # Eager commit to avoid having 2 jobs # exporting at the same time. The constraint # will pop if an other job already created # the same binding. It will be caught and # raise a RetryableJobError. if not odoo.tools.config["test_enable"]: self.env.cr.commit() # pylint: disable=E8102 else: # If my_backend_bind_ids does not exist we are typically in a # "direct" binding (the binding record is the same record). # If wrap is True, relation is already a binding record. binding = relation if not rel_binder.to_external(binding): exporter = self.component(usage=component_usage, model_name=binding_model) exporter.run(binding) def _export_dependencies(self): """Export the dependencies for the record""" return def _map_data(self): """Returns an instance of :py:class:`~odoo.addons.connector.components.mapper.MapRecord` """ return self.mapper.map_record(self.binding) def _validate_create_data(self, data): """Check if the values to import are correct Pro-actively check before the ``Model.create`` if some fields are missing or invalid Raise `InvalidDataError` """ return def _validate_update_data(self, data): """Check if the values to import are correct Pro-actively check before the ``Model.update`` if some fields are missing or invalid Raise `InvalidDataError` """ return def _create_data(self, map_record, fields=None, **kwargs): """Get the data to pass to :py:meth:`_create`""" return map_record.values(for_create=True, fields=fields, **kwargs) def _create(self, data): """Create the External record""" # special check on data before export self._validate_create_data(data) return self.backend_adapter.create(data) def _update_data(self, map_record, fields=None, **kwargs): """Get the data to pass to :py:meth:`_update`""" return map_record.values(fields=fields, **kwargs) def _update(self, data): """Update an External record""" assert self.external_id # special check on data before export self._validate_update_data(data) self.backend_adapter.write(self.external_id, data) class Importer(AbstractComponent): """Synchronizer for importing data from a backend to Odoo""" _name = "base.importer" _inherit = "base.synchronizer" _usage = "importer" #: usage of the component used as mapper, can be customized in sub-classes _base_mapper_usage = "import.mapper" class Deleter(AbstractComponent): """Synchronizer for deleting a record on the backend""" _name = "base.deleter" _inherit = "base.synchronizer" #: usage of the component used as mapper, can be customized in sub-classes _usage = "deleter"
36.387892
16,229
1,587
py
PYTHON
15.0
# Copyright 2013 Camptocamp SA # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) """ Listeners ========= Listeners are Components notified when events happen. Documentation in :mod:`odoo.addons.component_event.components.event` The base listener for the connectors add a method :meth:`ConnectorListener.no_connector_export` which can be used with :func:`odoo.addons.component_event.skip_if`. """ from odoo.addons.component.core import AbstractComponent class ConnectorListener(AbstractComponent): """Base Backend Adapter for the connectors""" _name = "base.connector.listener" _inherit = ["base.connector", "base.event.listener"] def no_connector_export(self, record): """Return if the 'connector_no_export' has been set in context To be used with :func:`odoo.addons.component_event.skip_if` on Events:: from odoo.addons.component.core import Component from odoo.addons.component_event import skip_if class MyEventListener(Component): _name = 'my.event.listener' _inherit = 'base.connector.event.listener' _apply_on = ['magento.res.partner'] @skip_if(lambda: self, record, *args, **kwargs: self.no_connector_export(record)) def on_record_write(self, record, fields=None): record.with_delay().export_record() """ return record.env.context.get("no_connector_export") or record.env.context.get( "connector_no_export" )
31.74
1,587
11,960
py
PYTHON
15.0
# # Connectors documentation build configuration file, created by # sphinx-quickstart on Mon Feb 4 11:35:44 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. # flake8: noqa import os import sys import sphinx_bootstrap_theme # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # sys.path.insert(0, os.path.abspath('.')) sys.path.append(os.path.abspath("_themes")) MANIFEST_FILES = ["__manifest__.py", "__odoo__.py", "__openerp__.py"] def is_module(path): """return False if the path doesn't contain an odoo module, and the full path to the module manifest otherwise""" if not os.path.isdir(path): return False files = os.listdir(path) filtered = [x for x in files if x in (MANIFEST_FILES + ["__init__.py"])] if len(filtered) == 2 and "__init__.py" in filtered: return os.path.join(path, next(x for x in filtered if x != "__init__.py")) else: return False def is_installable_module(path): """return False if the path doesn't contain an installable odoo module, and the full path to the module manifest otherwise""" manifest_path = is_module(path) if manifest_path: manifest = ast.literal_eval(open(manifest_path).read()) if manifest.get("installable", True): return manifest_path return False if os.environ.get("TRAVIS_BUILD_DIR") and os.environ.get("VERSION"): # build from travis repos_home = os.environ["HOME"] deps_path = os.path.join(repos_home, "dependencies") odoo_folder = "odoo-" + os.environ.get("VERSION") odoo_root = os.path.join(repos_home, odoo_folder) build_path = os.environ["TRAVIS_BUILD_DIR"] else: # build from dev odoo_root = os.path.abspath("../../../../src") deps_path = os.path.abspath("../../..") build_path = os.path.abspath("../..") addons_paths = [] def add_path(*paths): addons_paths.append(os.path.join(*paths)) add_path(odoo_root, "odoo", "addons") add_path(odoo_root, "addons") add_path(build_path) deps_repos = [ repo for repo in os.listdir(deps_path) if os.path.isdir(os.path.join(deps_path, repo)) and not repo.startswith(".") ] for repo in deps_repos: add_path(deps_path, repo) addons = [ x for x in os.listdir(build_path) if not x.startswith((".", "__")) and is_installable_module(x) ] # sphinxodoo.ext.autodoc variables sphinxodoo_root_path = odoo_root sphinxodoo_addons = addons sphinxodoo_addons_path = addons_paths sys.path.append(build_path) # -- General configuration ----------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [ "sphinx.ext.autodoc", "sphinx.ext.intersphinx", "sphinx.ext.todo", "sphinx.ext.viewcode", "sphinxodoo.ext.autodoc", ] todo_include_todos = False # Add any paths that contain templates here, relative to this directory. templates_path = ["_templates"] # The suffix of source filenames. source_suffix = ".rst" # The encoding of source files. # source_encoding = 'utf-8-sig' # The master toctree document. master_doc = "index" # autodoc options autodoc_member_order = "bysource" # General information about the project. project = "Connector" copyright = "2013, Camptocamp SA" # pylint: disable=W0622 # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = "" # The full version, including alpha/beta/rc tags. release = "" # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. language = "en" locale_dirs = ["locale"] gettext_compact = True # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # today = '' # Else, today_fmt is used as the format for a strftime call. # today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ["_build"] # The reST default role (used for this markup: `text`) to use for all documents. # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. # add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = "sphinx" # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = "bootstrap" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. html_theme_options = { # Navigation bar title. (Default: ``project`` value) "navbar_title": "Odoo Connector", # Tab name for entire site. (Default: "Site") "navbar_site_name": "Site", # Global TOC depth for "site" navbar tab. (Default: 1) # Switching to -1 shows all levels. "globaltoc_depth": 2, # Include hidden TOCs in Site navbar? # # Note: If this is "false", you cannot have mixed ``:hidden:`` and # non-hidden ``toctree`` directives in the same page, or else the build # will break. # # Values: "true" (default) or "false" "globaltoc_includehidden": "true", # HTML navbar class (Default: "navbar") to attach to <div> element. # For black navbar, do "navbar navbar-inverse" "navbar_class": "navbar", # Fix navigation bar to top of page? # Values: "true" (default) or "false" "navbar_fixed_top": "true", # Location of link to source. # Options are "nav" (default), "footer" or anything else to exclude. "source_link_position": "footer", # Bootswatch (http://bootswatch.com/) theme. # # Options are nothing with "" (default) or the name of a valid theme # such as "amelia" or "cosmo". # # Note that this is served off CDN, so won't be available offline. "bootswatch_theme": "united", } # Add any paths that contain custom themes here, relative to this directory. html_theme_path = sphinx_bootstrap_theme.get_html_theme_path() # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". # html_title = None # A shorter title for the navigation bar. Default is the same as html_title. # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ["_static"] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. # html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # html_use_smartypants = True # Custom sidebar templates, maps document names to template names. # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. # html_additional_pages = {} # If false, no module index is generated. # html_domain_indices = True # If false, no index is generated. # html_use_index = True # If true, the index is split into individual pages for each letter. # html_split_index = False # If true, links to the reST sources are added to the pages. # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = "connector-doc" # -- Options for LaTeX output -------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ("index", "Connector.tex", "Connector Documentation", "Camptocamp SA", "manual") ] # The name of an image file (relative to this directory) to place at the top of # the title page. # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # latex_use_parts = False # If true, show page references after internal links. # latex_show_pagerefs = False # If true, show URL addresses after external links. # latex_show_urls = False # Documents to append as an appendix to all manuals. # latex_appendices = [] # If false, no module index is generated. # latex_domain_indices = True # -- Options for manual page output -------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [("index", "connector", "Connector Documentation", ["Camptocamp SA"], 1)] # If true, show URL addresses after external links. # man_show_urls = False # -- Options for Texinfo output ------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ( "index", "Connector", "Connector Documentation", "Camptocamp SA", "Connector", "Framework for Odoo Connectors.", "Miscellaneous", ) ] # Documents to append as an appendix to all manuals. # texinfo_appendices = [] # If false, no module index is generated. # texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. # texinfo_show_urls = 'footnote' # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = { "http://docs.python.org/": None, "odooweb": ("https://www.odoo.com/documentation/10.0/", None), "odoodev": ("https://www.odoo.com/documentation/10.0/", None), "connectormagento": ("http://www.odoo-magento-connector.com", None), }
31.808511
11,960
496
py
PYTHON
15.0
# © 2014 David BEAL Akretion, Sodexis # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html). { "name": "Connector Base Product", "version": "15.0.1.0.0", "author": "Openerp Connector Core Editors, Odoo Community Association (OCA)", "website": "https://github.com/OCA/connector", "license": "LGPL-3", "category": "Connector", "depends": [ "connector", "product", ], "data": ["views/product_view.xml"], "installable": True, }
29.117647
495
573
py
PYTHON
15.0
# Copyright 2019 Camptocamp SA # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) { "name": "Components Tests", "summary": "Automated tests for Components, do not install.", "version": "15.0.1.0.0", "author": "Camptocamp,Odoo Community Association (OCA)", "license": "LGPL-3", "category": "Hidden", "depends": ["component"], "website": "https://github.com/OCA/connector", "data": ["security/ir.model.access.csv"], "installable": True, "development_status": "Production/Stable", "maintainers": ["guewen"], }
33.705882
573
1,224
py
PYTHON
15.0
# Copyright 2019 Camptocamp SA # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) from odoo.addons.component.tests.common import TransactionComponentCase class TestComponentInheritance(TransactionComponentCase): def setUp(self): super().setUp() self.collection = self.env["test.component.collection"].create({"name": "Test"}) def test_inherit_base(self): with self.collection.work_on("res.users") as work: component = work.component_by_name("base") self.assertEqual("test_inherit_base", component.test_inherit_base()) def test_inherit_component(self): with self.collection.work_on("res.users") as work: component = work.component_by_name("mapper") self.assertEqual( "test_inherit_component", component.test_inherit_component() ) def test_inherit_prototype_component(self): with self.collection.work_on("res.users") as work: component = work.component_by_name("test.mapper") self.assertEqual( "test_inherit_component", component.test_inherit_component() ) self.assertEqual("test.mapper", component.name())
40.8
1,224
967
py
PYTHON
15.0
# Copyright 2013-2019 Camptocamp SA # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) from odoo.addons.component.tests.common import TransactionComponentCase from odoo.addons.test_component.components.components import UserTestComponent class TestComponentCollection(TransactionComponentCase): def setUp(self): super().setUp() self.collection = self.env["test.component.collection"].create({"name": "Test"}) def tearDown(self): super().tearDown() def test_component_by_name(self): with self.collection.work_on("res.users") as work: component = work.component_by_name(name="test.user.component") self.assertEqual(UserTestComponent._name, component._name) def test_components_usage(self): with self.collection.work_on("res.users") as work: component = work.component(usage="test1") self.assertEqual(UserTestComponent._name, component._name)
40.291667
967
328
py
PYTHON
15.0
# Copyright 2016 Camptocamp SA # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) from odoo import fields, models class TestComponentCollection(models.Model): _name = "test.component.collection" _description = "Test Component Collection" _inherit = ["collection.base"] name = fields.Char()
25.230769
328
817
py
PYTHON
15.0
# Copyright 2017 Camptocamp SA # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) from odoo.addons.component.core import AbstractComponent, Component class BaseComponent(AbstractComponent): _inherit = "base" def test_inherit_base(self): return "test_inherit_base" class Mapper(AbstractComponent): _name = "mapper" def test_inherit_component(self): return "test_inherit_component" class ImportTestMapper(Component): _name = "test.mapper" _inherit = "mapper" _usage = "import.mapper" _collection = "test.component.collection" def name(self): return "test.mapper" class UserTestComponent(Component): _name = "test.user.component" _apply_on = ["res.users"] _usage = "test1" _collection = "test.component.collection"
23.342857
817
567
py
PYTHON
15.0
# © 2016 ForgeFlow S.L. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Account Move Line Stock Info", "version": "15.0.1.1.0", "depends": ["stock_account"], "author": "ForgeFlow," "Odoo Community Association (OCA)", "website": "https://github.com/OCA/stock-logistics-warehouse", "category": "Warehouse Management", "installable": True, "license": "AGPL-3", "data": [ "security/ir.model.access.csv", "views/account_move_line_view.xml", "views/stock_move_view.xml", ], }
33.294118
566
6,983
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.tests.common import TransactionCase class TestAccountMoveLineStockInfo(TransactionCase): def setUp(self): super(TestAccountMoveLineStockInfo, self).setUp() self.product_model = self.env["product.product"] self.product_ctg_model = self.env["product.category"] self.acc_type_model = self.env["account.account.type"] self.account_model = self.env["account.account"] self.stock_picking_model = self.env["stock.picking"] self.res_users_model = self.env["res.users"] self.location_stock = self.env.ref("stock.stock_location_stock") self.location_supplier = self.env.ref("stock.stock_location_suppliers") self.location_customer = self.env.ref("stock.stock_location_customers") self.company = self.env.ref("base.main_company") self.picking_type_in = self.env.ref("stock.picking_type_in") self.picking_type_out = self.env.ref("stock.picking_type_out") self.group_stock_manager = self.env.ref("stock.group_stock_manager") self.group_account_invoice = self.env.ref("account.group_account_invoice") self.group_account_manager = self.env.ref("account.group_account_manager") # Create account for Goods Received Not Invoiced acc_type = self._create_account_type("equity", "other", "equity") name = "Goods Received Not Invoiced" code = "grni" self.account_grni = self._create_account(acc_type, name, code, self.company) # Create account for Cost of Goods Sold acc_type = self._create_account_type("expense", "other", "expense") name = "Cost of Goods Sold" code = "cogs" self.account_cogs = self._create_account(acc_type, name, code, self.company) # Create account for Inventory acc_type = self._create_account_type("asset", "other", "asset") name = "Inventory" code = "inventory" self.account_inventory = self._create_account( acc_type, name, code, self.company ) # Create Product self.product = self._create_product() # Create users self.stock_manager = self._create_user( "stock_manager", [self.group_stock_manager, self.group_account_invoice], self.company, ) self.account_invoice = self._create_user( "account_invoice", [self.group_account_invoice], self.company ) self.account_manager = self._create_user( "account_manager", [self.group_account_manager], self.company ) def _create_user(self, login, groups, company): """Create a user.""" group_ids = [group.id for group in groups] user = self.res_users_model.with_context(**{"no_reset_password": True}).create( { "name": "Test User", "login": login, "password": "demo", "email": "test@yourcompany.com", "company_id": company.id, "company_ids": [(4, company.id)], "groups_id": [(6, 0, group_ids)], } ) return user.id def _create_account_type(self, name, a_type, internal_group): acc_type = self.acc_type_model.create( {"name": name, "type": a_type, "internal_group": internal_group} ) return acc_type def _create_account(self, acc_type, name, code, company): """Create an account.""" account = self.account_model.create( { "name": name, "code": code, "user_type_id": acc_type.id, "company_id": company.id, } ) return account def _create_product(self): """Create a Product.""" product_ctg = self.product_ctg_model.create( { "name": "test_product_ctg", "property_valuation": "real_time", "property_stock_account_input_categ_id": self.account_grni.id, "property_stock_account_output_categ_id": self.account_cogs.id, "property_stock_valuation_account_id": self.account_inventory.id, } ) product = self.product_model.create( { "name": "test_product", "categ_id": product_ctg.id, "type": "product", "standard_price": 1.0, "list_price": 1.0, } ) return product def _create_picking(self, picking_type, location, location_dest): picking = self.stock_picking_model.with_user(self.stock_manager).create( { "picking_type_id": picking_type.id, "location_id": location.id, "location_dest_id": location_dest.id, "move_lines": [ ( 0, 0, { "name": "Test move", "product_id": self.product.id, "product_uom": self.product.uom_id.id, "product_uom_qty": 3, "location_id": location.id, "location_dest_id": location_dest.id, "price_unit": 10, }, ) ], } ) return picking def test_account_move_line_stock_move(self): """Test that processing an incoming picking the account moves generated by the picking moves will contain the stock move. """ picking_in = self._create_picking( self.picking_type_in, self.location_supplier, self.location_stock ) picking_in.action_confirm() picking_in.move_lines.quantity_done = 1 picking_in._action_done() account_move_line = False for move in picking_in.move_lines: self.assertEqual(len(move.account_move_line_ids), 2) for aml in move.account_move_line_ids: account_move_line = aml picking_out = self._create_picking( self.picking_type_out, self.location_supplier, self.location_stock ) picking_out.action_confirm() picking_out.move_lines.quantity_done = 1 picking_out._action_done() for move in picking_out.move_lines: self.assertEqual(len(move.account_move_line_ids), 2) # Test that the account invoice user can access to the stock info self.assertTrue(account_move_line.with_user(self.account_invoice).stock_move_id) # Test that the account manager can access to the stock info self.assertTrue(account_move_line.with_user(self.account_manager).stock_move_id)
40.132184
6,983
360
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 AccountMoveLine(models.Model): _inherit = "account.move.line" stock_move_id = fields.Many2one( comodel_name="stock.move", string="Stock Move", copy=False, index=True )
30
360
752
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 api, fields, models class StockMove(models.Model): _inherit = "stock.move" account_move_line_ids = fields.One2many( comodel_name="account.move.line", inverse_name="stock_move_id", copy=False, ) @api.model def _prepare_account_move_line( self, qty, cost, credit_account_id, debit_account_id, description ): res = super(StockMove, self)._prepare_account_move_line( qty, cost, credit_account_id, debit_account_id, description ) for line in res: line[2]["stock_move_id"] = self.id return res
30.08
752
709
py
PYTHON
15.0
# Copyright 2017-2020 ForgeFlow, S.L. # Copyright 2021 Jacques-Etienne Baudoux (BCIM) <je@bcim.be> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { "name": "Procurement Auto Create Group", "version": "15.0.1.0.0", "development_status": "Production/Stable", "license": "AGPL-3", "summary": "Allows to configure the system to propose automatically new " "procurement groups during the procurement run.", "author": "ForgeFlow, BCIM, Odoo Community Association (OCA)", "website": "https://github.com/OCA/stock-logistics-warehouse", "category": "Warehouse", "depends": ["stock"], "data": ["views/procurement_view.xml"], "installable": True, }
41.705882
709
8,973
py
PYTHON
15.0
# Copyright 2017-2020 ForgeFlow, S.L. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo.tests.common import TransactionCase class TestProcurementAutoCreateGroup(TransactionCase): def setUp(self): super(TestProcurementAutoCreateGroup, self).setUp() self.group_obj = self.env["procurement.group"] self.rule_obj = self.env["stock.rule"] self.route_obj = self.env["stock.location.route"] self.move_obj = self.env["stock.move"] self.picking_obj = self.env["stock.picking"] self.product_obj = self.env["product.product"] self.warehouse = self.env.ref("stock.warehouse0") self.location = self.env.ref("stock.stock_location_stock") self.company_id = self.env.ref("base.main_company") self.supplier_location = self.env.ref("stock.stock_location_suppliers") self.loc_components = self.env.ref("stock.stock_location_components") picking_type_id = self.env.ref("stock.picking_type_internal").id self.partner = self.env["res.partner"].create({"name": "Partner"}) # Create rules and routes: pull_push_route_auto = self.route_obj.create({"name": "Auto Create Group"}) self.rule_1 = self.rule_obj.create( { "name": "rule with autocreate", "route_id": pull_push_route_auto.id, "auto_create_group": True, "action": "pull_push", "warehouse_id": self.warehouse.id, "picking_type_id": picking_type_id, "location_id": self.location.id, "location_src_id": self.loc_components.id, "partner_address_id": self.partner.id, } ) pull_push_route_no_auto = self.route_obj.create( {"name": "Not Auto Create Group"} ) self.rule_obj.create( { "name": "rule with no autocreate", "route_id": pull_push_route_no_auto.id, "auto_create_group": False, "action": "pull_push", "warehouse_id": self.warehouse.id, "picking_type_id": picking_type_id, "location_id": self.location.id, "location_src_id": self.loc_components.id, } ) push_route_auto = self.route_obj.create({"name": "Auto Create Group"}) self.rule_1 = self.rule_obj.create( { "name": "route_auto", "location_src_id": self.location.id, "location_id": self.loc_components.id, "route_id": push_route_auto.id, "auto_create_group": True, "auto": "manual", "picking_type_id": picking_type_id, "warehouse_id": self.warehouse.id, "company_id": self.company_id.id, "action": "push", } ) push_route_no_auto = self.route_obj.create({"name": "Not Auto Create Group"}) self.rule_obj.create( { "name": "route_no_auto", "location_src_id": self.location.id, "location_id": self.loc_components.id, "route_id": push_route_no_auto.id, "auto_create_group": False, "auto": "manual", "picking_type_id": picking_type_id, "warehouse_id": self.warehouse.id, "company_id": self.company_id.id, "action": "push", } ) # Prepare products: self.prod_auto_pull_push = self.product_obj.create( { "name": "Test Product 1", "type": "product", "route_ids": [(6, 0, [pull_push_route_auto.id])], } ) self.prod_no_auto_pull_push = self.product_obj.create( { "name": "Test Product 2", "type": "product", "route_ids": [(6, 0, [pull_push_route_no_auto.id])], } ) self.prod_auto_push = self.product_obj.create( { "name": "Test Product 3", "type": "product", "route_ids": [(6, 0, [push_route_auto.id])], } ) self.prod_no_auto_push = self.product_obj.create( { "name": "Test Product 4", "type": "product", "route_ids": [(6, 0, [push_route_no_auto.id])], } ) def _procure(self, product): values = {} self.group_obj.run( [ self.env["procurement.group"].Procurement( product, 5.0, product.uom_id, self.location, "TEST", "odoo tests", self.env.company, values, ) ] ) return True def _push_trigger(self, product): picking = self.picking_obj.create( { "picking_type_id": self.ref("stock.picking_type_in"), "location_id": self.supplier_location.id, "location_dest_id": self.location.id, "move_lines": [ ( 0, 0, { "name": "Test move", "product_id": product.id, "date_deadline": "2099-06-01 18:00:00", "date": "2099-06-01 18:00:00", "product_uom": product.uom_id.id, "product_uom_qty": 1.0, "location_id": self.supplier_location.id, "location_dest_id": self.location.id, }, ) ], } ) picking.move_lines.write({"quantity_done": 1.0}) picking.button_validate() def test_01_pull_push_no_auto_create_group(self): """Test auto creation of group.""" move = self.move_obj.search( [("product_id", "=", self.prod_no_auto_pull_push.id)] ) self.assertFalse(move) self._procure(self.prod_no_auto_pull_push) move = self.move_obj.search( [("product_id", "=", self.prod_no_auto_pull_push.id)] ) self.assertTrue(move) self.assertFalse( move.group_id, "Procurement Group should not have been assigned." ) def test_02_pull_push_auto_create_group(self): move = self.move_obj.search([("product_id", "=", self.prod_auto_pull_push.id)]) self.assertFalse(move) self._procure(self.prod_auto_pull_push) move = self.move_obj.search([("product_id", "=", self.prod_auto_pull_push.id)]) self.assertTrue(move) self.assertTrue(move.group_id, "Procurement Group not assigned.") self.assertEqual( move.group_id.partner_id, self.partner, "Procurement Group partner missing.", ) def test_03_onchange_method(self): """Test onchange method for stock rule.""" proc_rule = self.rule_1 self.assertTrue(proc_rule.auto_create_group) proc_rule.write({"group_propagation_option": "none"}) proc_rule._onchange_group_propagation_option() self.assertFalse(proc_rule.auto_create_group) def test_04_push_no_auto_create_group(self): """Test no auto creation of group.""" move = self.move_obj.search( [ ("product_id", "=", self.prod_no_auto_push.id), ("location_dest_id", "=", self.loc_components.id), ] ) self.assertFalse(move) self._push_trigger(self.prod_no_auto_push) move = self.move_obj.search( [ ("product_id", "=", self.prod_no_auto_push.id), ("location_dest_id", "=", self.loc_components.id), ] ) self.assertTrue(move) self.assertFalse( move.group_id, "Procurement Group should not have been assigned." ) def test_05_push_auto_create_group(self): """Test auto creation of group.""" move = self.move_obj.search( [ ("product_id", "=", self.prod_auto_push.id), ("location_dest_id", "=", self.loc_components.id), ] ) self.assertFalse(move) self._push_trigger(self.prod_auto_push) move = self.move_obj.search( [ ("product_id", "=", self.prod_auto_push.id), ("location_dest_id", "=", self.loc_components.id), ] ) self.assertTrue(move) self.assertTrue(move.group_id, "Procurement Group not assigned.")
38.021186
8,973
917
py
PYTHON
15.0
# Copyright 2017-2020 ForgeFlow, S.L. # Copyright 2021 Jacques-Etienne Baudoux (BCIM) <je@bcim.be> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import api, models class ProcurementGroup(models.Model): _inherit = "procurement.group" @api.model def _get_rule(self, product_id, location_id, values): rule = super()._get_rule(product_id, location_id, values) # If there isn't a date planned in the values it means that this # method has been called outside of a procurement process. if ( rule and not values.get("group_id") and rule.auto_create_group and values.get("date_planned") ): group_data = rule._prepare_auto_procurement_group_data() group = self.env["procurement.group"].create(group_data) values["group_id"] = group return rule
36.68
917
1,335
py
PYTHON
15.0
# Copyright 2017-2020 ForgeFlow, S.L. # Copyright 2021 Jacques-Etienne Baudoux (BCIM) <je@bcim.be> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import _, api, fields, models from odoo.exceptions import UserError class StockRule(models.Model): _inherit = "stock.rule" auto_create_group = fields.Boolean(string="Auto-create Procurement Group") @api.onchange("group_propagation_option") def _onchange_group_propagation_option(self): if self.group_propagation_option != "propagate": self.auto_create_group = False def _push_prepare_move_copy_values(self, move_to_copy, new_date): new_move_vals = super()._push_prepare_move_copy_values(move_to_copy, new_date) if self.auto_create_group: group_data = self._prepare_auto_procurement_group_data() group = self.env["procurement.group"].create(group_data) new_move_vals["group_id"] = group.id return new_move_vals def _prepare_auto_procurement_group_data(self): name = self.env["ir.sequence"].next_by_code("procurement.group") or False if not name: raise UserError(_("No sequence defined for procurement group.")) return { "name": name, "partner_id": self.partner_address_id.id, }
39.264706
1,335
419
py
PYTHON
15.0
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import SUPERUSER_ID, api def enable_multi_locations(cr, registry): env = api.Environment(cr, SUPERUSER_ID, {}) ResConfig = env["res.config.settings"] default_values = ResConfig.default_get(list(ResConfig.fields_get())) default_values.update({"group_stock_multi_locations": True}) ResConfig.create(default_values).execute()
41.9
419
901
py
PYTHON
15.0
# Copyright (C) 2011 Julius Network Solutions SARL <contact@julius.fr> # Copyright 2018 Camptocamp SA # Copyright 2020 Tecnativa - João Marques # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl) { "name": "Move Stock Location", "version": "15.0.1.2.0", "author": "Julius Network Solutions, " "BCIM," "Camptocamp," "Odoo Community Association (OCA)", "summary": "This module allows to move all stock " "in a stock location to an other one.", "website": "https://github.com/OCA/stock-logistics-warehouse", "license": "AGPL-3", "depends": ["stock"], "category": "Stock", "data": [ "data/stock_quant_view.xml", "security/ir.model.access.csv", "views/stock_picking_type_views.xml", "views/stock_picking.xml", "wizard/stock_move_location.xml", ], "post_init_hook": "enable_multi_locations", }
33.333333
900
5,780
py
PYTHON
15.0
# Copyright (C) 2011 Julius Network Solutions SARL <contact@julius.fr> # Copyright 2018 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl) from odoo.tests import Form, common class TestsCommon(common.TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.env = cls.env(context=dict(cls.env.context, tracking_disable=True)) cls.location_obj = cls.env["stock.location"] product_obj = cls.env["product.product"] cls.wizard_obj = cls.env["wiz.stock.move.location"] cls.quant_obj = cls.env["stock.quant"] cls.company = cls.env.ref("base.main_company") cls.partner = cls.env.ref("base.res_partner_category_0") cls.internal_loc_1 = cls.location_obj.create( { "name": "INT_1", "usage": "internal", "active": True, "company_id": cls.company.id, } ) cls.internal_loc_2 = cls.location_obj.create( { "name": "INT_2", "usage": "internal", "active": True, "company_id": cls.company.id, } ) cls.internal_loc_2_shelf = cls.location_obj.create( { "name": "Shelf", "usage": "internal", "active": True, "company_id": cls.company.id, "location_id": cls.internal_loc_2.id, } ) cls.uom_unit = cls.env.ref("uom.product_uom_unit") cls.product_no_lots = product_obj.create( {"name": "Pineapple", "type": "product", "tracking": "none"} ) cls.product_lots = product_obj.create( {"name": "Apple", "type": "product", "tracking": "lot"} ) cls.product_package = product_obj.create( {"name": "Orange", "type": "product", "tracking": "lot"} ) cls.lot1 = cls.env["stock.production.lot"].create( { "name": "lot1", "product_id": cls.product_lots.id, "company_id": cls.company.id, } ) cls.lot2 = cls.env["stock.production.lot"].create( { "name": "lot2", "product_id": cls.product_lots.id, "company_id": cls.company.id, } ) cls.lot3 = cls.env["stock.production.lot"].create( { "name": "lot3", "product_id": cls.product_lots.id, "company_id": cls.company.id, } ) cls.lot4 = cls.env["stock.production.lot"].create( { "name": "lot4", "product_id": cls.product_package.id, "company_id": cls.company.id, } ) cls.lot5 = cls.env["stock.production.lot"].create( { "name": "lot5", "product_id": cls.product_package.id, "company_id": cls.company.id, } ) cls.package1 = cls.env["stock.quant.package"].create({}) cls.package2 = cls.env["stock.quant.package"].create({}) def setup_product_amounts(self): self.set_product_amount(self.product_no_lots, self.internal_loc_1, 123) self.set_product_amount( self.product_lots, self.internal_loc_1, 1.0, lot_id=self.lot1 ) self.set_product_amount( self.product_lots, self.internal_loc_1, 1.0, lot_id=self.lot2 ) self.set_product_amount( self.product_lots, self.internal_loc_1, 1.0, lot_id=self.lot3 ) self.set_product_amount( self.product_package, self.internal_loc_1, 1.0, lot_id=self.lot4, package_id=self.package1, ) self.set_product_amount( self.product_package, self.internal_loc_1, 1.0, lot_id=self.lot5, package_id=self.package2, owner_id=self.partner, ) def set_product_amount( self, product, location, amount, lot_id=None, package_id=None, owner_id=None ): self.env["stock.quant"]._update_available_quantity( product, location, amount, lot_id=lot_id, package_id=package_id, owner_id=owner_id, ) def check_product_amount( self, product, location, amount, lot_id=None, package_id=None, owner_id=None ): self.assertEqual( self.env["stock.quant"]._get_available_quantity( product, location, lot_id=lot_id, package_id=package_id, owner_id=owner_id, ), amount, ) def _create_wizard(self, origin_location, destination_location): move_location_wizard = self.env["wiz.stock.move.location"] return move_location_wizard.create( { "origin_location_id": origin_location.id, "destination_location_id": destination_location.id, } ) def _create_picking(self, picking_type): with Form(self.env["stock.picking"]) as picking_form: picking_form.picking_type_id = picking_type return picking_form.save() def _create_putaway_for_product(self, product, loc_in, loc_out): putaway = self.env["stock.putaway.rule"].create( { "product_id": product.id, "location_in_id": loc_in.id, "location_out_id": loc_out.id, } ) loc_in.write({"putaway_rule_ids": [(4, putaway.id, 0)]})
34.404762
5,780
11,132
py
PYTHON
15.0
# Copyright (C) 2011 Julius Network Solutions SARL <contact@julius.fr> # Copyright 2018 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl) from odoo.exceptions import ValidationError from .test_common import TestsCommon class TestMoveLocation(TestsCommon): def setUp(self): super().setUp() self.setup_product_amounts() def test_move_location_wizard(self): """Test a simple move.""" wizard = self._create_wizard(self.internal_loc_1, self.internal_loc_2) wizard.onchange_origin_location() wizard.action_move_location() self.check_product_amount(self.product_no_lots, self.internal_loc_1, 0) self.check_product_amount(self.product_lots, self.internal_loc_1, 0, self.lot1) self.check_product_amount(self.product_lots, self.internal_loc_1, 0, self.lot2) self.check_product_amount(self.product_lots, self.internal_loc_1, 0, self.lot3) self.check_product_amount( self.product_package, self.internal_loc_1, 0, self.lot4, self.package1 ) self.check_product_amount( self.product_package, self.internal_loc_1, 0, self.lot5, self.package2, self.partner, ) self.check_product_amount(self.product_no_lots, self.internal_loc_2, 123) self.check_product_amount(self.product_lots, self.internal_loc_2, 1, self.lot1) self.check_product_amount(self.product_lots, self.internal_loc_2, 1, self.lot2) self.check_product_amount(self.product_lots, self.internal_loc_2, 1, self.lot3) self.check_product_amount( self.product_package, self.internal_loc_2, 1, self.lot4, self.package1 ) self.check_product_amount( self.product_package, self.internal_loc_2, 1, self.lot5, self.package2, self.partner, ) def test_move_location_wizard_amount(self): """Can't move more than exists.""" wizard = self._create_wizard(self.internal_loc_1, self.internal_loc_2) wizard.onchange_origin_location() with self.assertRaises(ValidationError): wizard.stock_move_location_line_ids[0].move_quantity += 1 def test_move_location_wizard_ignore_reserved(self): """Can't move more than exists.""" wizard = self._create_wizard(self.internal_loc_1, self.internal_loc_2) wizard.onchange_origin_location() # reserve some quants self.quant_obj._update_reserved_quantity( self.product_no_lots, self.internal_loc_1, 50 ) self.quant_obj._update_reserved_quantity( self.product_lots, self.internal_loc_1, 1, lot_id=self.lot1 ) # doesn't care about reservations, everything is moved wizard.action_move_location() self.check_product_amount(self.product_no_lots, self.internal_loc_1, 0) self.check_product_amount(self.product_no_lots, self.internal_loc_2, 123) self.check_product_amount(self.product_lots, self.internal_loc_2, 1, self.lot1) def test_wizard_clear_lines(self): """Test lines getting cleared properly.""" wizard = self._create_wizard(self.internal_loc_1, self.internal_loc_2) wizard.onchange_origin_location() self.assertEqual(len(wizard.stock_move_location_line_ids), 6) wizard._onchange_destination_location_id() self.assertEqual(len(wizard.stock_move_location_line_ids), 6) dest_location_line = wizard.stock_move_location_line_ids.mapped( "destination_location_id" ) self.assertEqual(dest_location_line, wizard.destination_location_id) wizard._onchange_origin_location_id() self.assertEqual(len(wizard.stock_move_location_line_ids), 0) def test_wizard_onchange_origin_location(self): """Test a product that have existing quants with undefined quantity.""" product_not_available = self.env["product.product"].create( {"name": "Mango", "type": "product", "tracking": "none"} ) self.quant_obj.create( { "product_id": product_not_available.id, "location_id": self.internal_loc_1.id, } ) wizard = self._create_wizard(self.internal_loc_1, self.internal_loc_2) wizard.onchange_origin_location() # we check there is no line for product_not_available self.assertEqual( len( wizard.stock_move_location_line_ids.filtered( lambda x: x.product_id.id == product_not_available.id ) ), 0, ) def test_planned_transfer(self): """Test planned transfer.""" wizard = self._create_wizard(self.internal_loc_1, self.internal_loc_2) wizard.onchange_origin_location() wizard = wizard.with_context(planned=True) wizard.action_move_location() picking = wizard.picking_id self.assertEqual(picking.state, "assigned") self.assertEqual(len(picking.move_line_ids), 6) self.assertEqual( sorted(picking.move_line_ids.mapped("product_uom_qty")), [1, 1, 1, 1, 1, 123], ) def test_quant_transfer(self): """Test quants transfer.""" quants = self.product_lots.stock_quant_ids wizard = self.wizard_obj.with_context( active_model="stock.quant", active_ids=quants.ids, origin_location_disable=True, ).create( { "origin_location_id": quants[:1].location_id.id, "destination_location_id": self.internal_loc_2.id, } ) lines = wizard.stock_move_location_line_ids self.assertEqual(len(lines), 3) wizard.onchange_origin_location() self.assertEqual(len(lines), 3) wizard.destination_location_id = self.internal_loc_1 wizard._onchange_destination_location_id() self.assertEqual(lines.mapped("destination_location_id"), self.internal_loc_1) wizard.origin_location_id = self.internal_loc_2 wizard._onchange_destination_location_id() self.assertEqual(len(lines), 3) def test_readonly_location_computation(self): """Test that origin_location_disable and destination_location_disable are computed correctly.""" wizard = self._create_wizard(self.internal_loc_1, self.internal_loc_2) # locations are editable. self.assertFalse(wizard.origin_location_disable) self.assertFalse(wizard.destination_location_disable) # Disable edit mode: wizard.edit_locations = False self.assertTrue(wizard.origin_location_disable) self.assertTrue(wizard.destination_location_disable) def test_picking_type_action_dummy(self): """Test that no error is raised from actions.""" pick_type = self.env.ref("stock.picking_type_internal") pick_type.action_move_location() def test_wizard_with_putaway_strategy(self): """Test that Putaway strategies are being applied.""" self._create_putaway_for_product( self.product_no_lots, self.internal_loc_2, self.internal_loc_2_shelf ) wizard = self._create_wizard(self.internal_loc_1, self.internal_loc_2) wizard.apply_putaway_strategy = True wizard.onchange_origin_location() putaway_line = wizard.stock_move_location_line_ids.filtered( lambda p: p.product_id == self.product_no_lots )[0] self.assertEqual( putaway_line.destination_location_id, self.internal_loc_2_shelf ) def test_delivery_order_assignation_after_transfer(self): """ Make sure using the wizard doesn't break assignation on delivery orders """ delivery_order_type = self.env.ref("stock.picking_type_out") internal_transfer_type = self.env.ref("stock.picking_type_internal") wh_stock_shelf_1 = self.env.ref("stock.stock_location_components") wh_stock_shelf_2 = self.env.ref("stock.stock_location_14") wh_stock_shelf_3 = wh_stock_shelf_1.copy({"name": "Shelf 3"}) # Create some quants self.set_product_amount( self.product_lots, wh_stock_shelf_1, 100, lot_id=self.lot1 ) # Create and assign a delivery picking to reserve some quantities delivery_picking = self._create_picking(delivery_order_type) delivery_move = self.env["stock.move"].create( { "name": "Delivery move", "product_id": self.product_lots.id, "product_uom_qty": 20.0, "product_uom": self.product_lots.uom_id.id, "location_id": delivery_picking.location_id.id, "location_dest_id": delivery_picking.location_dest_id.id, "picking_id": delivery_picking.id, } ) delivery_picking.action_confirm() self.assertEqual(delivery_picking.state, "assigned") # Move all quantities to other location using module's wizard wizard = self._create_wizard(wh_stock_shelf_1, wh_stock_shelf_2) wizard.onchange_origin_location() wizard.action_move_location() self.assertEqual(delivery_picking.state, "assigned") # Do a planned transfer to move quantities to other location # without using module's wizard internal_picking = self._create_picking(internal_transfer_type) internal_picking.write( {"location_id": wh_stock_shelf_2, "location_dest_id": wh_stock_shelf_3.id} ) self.env["stock.move"].create( { "name": "Internal move", "product_id": self.product_lots.id, "product_uom_qty": 100.0, "product_uom": self.product_lots.uom_id.id, "location_id": internal_picking.location_id.id, "location_dest_id": internal_picking.location_dest_id.id, "picking_id": internal_picking.id, } ) # Unreserve quantity on the delivery to allow moving the quantity delivery_picking.do_unreserve() self.assertEqual(delivery_picking.state, "confirmed") internal_picking.action_confirm() internal_picking.action_assign() internal_picking.move_line_ids.qty_done = ( internal_picking.move_line_ids.product_uom_qty ) internal_picking.button_validate() self.assertEqual(internal_picking.state, "done") # Assign the delivery must work delivery_picking.action_assign() self.assertEqual(delivery_picking.state, "assigned") # The old reserved quantities must be in new location after confirm wizard self.assertEqual(len(delivery_move.move_line_ids), 1) self.assertEqual(delivery_move.move_line_ids.product_uom_qty, 20.0) self.assertEqual(delivery_move.move_line_ids.location_id, wh_stock_shelf_3)
44
11,132
2,846
py
PYTHON
15.0
# Copyright Iryna Vyshnevska 2020 Camptocamp # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import odoo.tests.common as common class TestFillwithStock(common.TransactionCase): def setUp(self): super(TestFillwithStock, self).setUp() self.env = self.env( context=dict( self.env.context, tracking_disable=True, ) ) self.stock_location = self.env.ref("stock.stock_location_stock") self.pack_location = self.env.ref("stock.location_pack_zone") self.shelf1_location = self.env["stock.location"].create( { "name": "Test location", "usage": "internal", "location_id": self.stock_location.id, } ) self.product1 = self.env["product.product"].create( { "name": "Product A", "type": "product", } ) self.product2 = self.env["product.product"].create( { "name": "Product B", "type": "product", } ) self.env["stock.quant"].create( { "product_id": self.product1.id, "location_id": self.shelf1_location.id, "quantity": 5.0, "reserved_quantity": 0.0, } ) self.env["stock.quant"].create( { "product_id": self.product1.id, "location_id": self.shelf1_location.id, "quantity": 10.0, "reserved_quantity": 5.0, } ) self.env["stock.quant"].create( { "product_id": self.product2.id, "location_id": self.shelf1_location.id, "quantity": 5.0, "reserved_quantity": 0.0, } ) def test_fillwithstock(self): picking_stock_pack = self.env["stock.picking"].create( { "location_id": self.shelf1_location.id, "location_dest_id": self.pack_location.id, "picking_type_id": self.env.ref("stock.picking_type_internal").id, } ) self.assertFalse(picking_stock_pack.move_lines) picking_stock_pack.button_fillwithstock() # picking filled with quants in bin self.assertEqual(len(picking_stock_pack.move_lines), 2) self.assertEqual( picking_stock_pack.move_lines.filtered( lambda m: m.product_id == self.product1 ).product_uom_qty, 10.0, ) self.assertEqual( picking_stock_pack.move_lines.filtered( lambda m: m.product_id == self.product2 ).product_uom_qty, 5.0, )
31.622222
2,846
6,374
py
PYTHON
15.0
# Copyright (C) 2011 Julius Network Solutions SARL <contact@julius.fr> # Copyright 2018 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl) from odoo import _, api, fields, models from odoo.exceptions import ValidationError from odoo.tools import float_compare class StockMoveLocationWizardLine(models.TransientModel): _name = "wiz.stock.move.location.line" _description = "Wizard move location line" move_location_wizard_id = fields.Many2one( string="Move location Wizard", comodel_name="wiz.stock.move.location", ) product_id = fields.Many2one( string="Product", comodel_name="product.product", required=True ) origin_location_id = fields.Many2one( string="Origin Location", comodel_name="stock.location" ) destination_location_id = fields.Many2one( string="Destination Location", comodel_name="stock.location" ) product_uom_id = fields.Many2one( string="Product Unit of Measure", comodel_name="uom.uom" ) lot_id = fields.Many2one( string="Lot/Serial Number", comodel_name="stock.production.lot", domain="[('product_id','=',product_id)]", ) package_id = fields.Many2one( string="Package Number", comodel_name="stock.quant.package", domain="[('location_id', '=', origin_location_id)]", ) owner_id = fields.Many2one(comodel_name="res.partner", string="From Owner") move_quantity = fields.Float( string="Quantity to move", digits="Product Unit of Measure" ) max_quantity = fields.Float( string="Maximum available quantity", digits="Product Unit of Measure" ) reserved_quantity = fields.Float(digits="Product Unit of Measure") custom = fields.Boolean(string="Custom line", default=True) @staticmethod def _compare(qty1, qty2, precision_rounding): return float_compare(qty1, qty2, precision_rounding=precision_rounding) @api.constrains("max_quantity", "move_quantity") def _constraint_max_move_quantity(self): for record in self: rounding = record.product_uom_id.rounding move_qty_gt_max_qty = ( self._compare(record.move_quantity, record.max_quantity, rounding) == 1 ) move_qty_lt_0 = self._compare(record.move_quantity, 0.0, rounding) == -1 if move_qty_gt_max_qty or move_qty_lt_0: raise ValidationError( _("Move quantity can not exceed max quantity or be negative") ) def get_max_quantity(self): self.product_uom_id = self.product_id.uom_id search_args = [ ("location_id", "=", self.origin_location_id.id), ("product_id", "=", self.product_id.id), ] if self.lot_id: search_args.append(("lot_id", "=", self.lot_id.id)) else: search_args.append(("lot_id", "=", False)) if self.package_id: search_args.append(("package_id", "=", self.package_id.id)) else: search_args.append(("package_id", "=", False)) if self.owner_id: search_args.append(("owner_id", "=", self.owner_id.id)) else: search_args.append(("owner_id", "=", False)) res = self.env["stock.quant"].read_group(search_args, ["quantity"], []) max_quantity = res[0]["quantity"] return max_quantity def create_move_lines(self, picking, move): for line in self: values = line._get_move_line_values(picking, move) if not self.env.context.get("planned") and values.get("qty_done") <= 0: continue self.env["stock.move.line"].create(values) return True def _get_move_line_values(self, picking, move): self.ensure_one() location_dest_id = ( self.move_location_wizard_id.apply_putaway_strategy and self.destination_location_id.get_putaway_strategy(self.product_id).id or self.destination_location_id.id ) qty_todo, qty_done = self._get_available_quantity() return { "product_id": self.product_id.id, "lot_id": self.lot_id.id, "package_id": self.package_id.id, "result_package_id": self.package_id.id, "owner_id": self.owner_id.id, "location_id": self.origin_location_id.id, "location_dest_id": location_dest_id, "product_uom_qty": qty_todo, "qty_done": qty_done, "product_uom_id": self.product_uom_id.id, "picking_id": picking.id, "move_id": move.id, } def _get_available_quantity(self): """We check here if the actual amount changed in the stock. We don't care about the reservations but we do care about not moving more than exists.""" self.ensure_one() if not self.product_id: return 0 if self.env.context.get("planned"): # for planned transfer we don't care about the amounts at all return self.move_quantity, 0 search_args = [ ("location_id", "=", self.origin_location_id.id), ("product_id", "=", self.product_id.id), ] if self.lot_id: search_args.append(("lot_id", "=", self.lot_id.id)) else: search_args.append(("lot_id", "=", False)) if self.package_id: search_args.append(("package_id", "=", self.package_id.id)) else: search_args.append(("package_id", "=", False)) if self.owner_id: search_args.append(("owner_id", "=", self.owner_id.id)) else: search_args.append(("owner_id", "=", False)) res = self.env["stock.quant"].read_group(search_args, ["quantity"], []) available_qty = res[0]["quantity"] if not available_qty: # if it is immediate transfer and product doesn't exist in that # location -> make the transfer of 0. return 0 rounding = self.product_uom_id.rounding available_qty_lt_move_qty = ( self._compare(available_qty, self.move_quantity, rounding) == -1 ) if available_qty_lt_move_qty: return available_qty return 0, self.move_quantity
40.08805
6,374
13,368
py
PYTHON
15.0
# Copyright (C) 2011 Julius Network Solutions SARL <contact@julius.fr> # Copyright 2018 Camptocamp SA # Copyright 2019 Tecnativa - Sergio Teruel # Copyright 2023 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl) from itertools import groupby from odoo import api, fields, models from odoo.fields import first class StockMoveLocationWizard(models.TransientModel): _name = "wiz.stock.move.location" _description = "Wizard move location" def _get_default_picking_type_id(self): company_id = self.env.context.get("company_id") or self.env.user.company_id.id return ( self.env["stock.picking.type"] .search( [ ("code", "=", "internal"), ("warehouse_id.company_id", "=", company_id), ], limit=1, ) .id ) origin_location_disable = fields.Boolean( compute="_compute_readonly_locations", help="technical field to disable the edition of origin location.", ) origin_location_id = fields.Many2one( string="Origin Location", comodel_name="stock.location", required=True, domain=lambda self: self._get_locations_domain(), ) destination_location_disable = fields.Boolean( compute="_compute_readonly_locations", help="technical field to disable the edition of destination location.", ) destination_location_id = fields.Many2one( string="Destination Location", comodel_name="stock.location", required=True, domain=lambda self: self._get_locations_domain(), ) stock_move_location_line_ids = fields.One2many( "wiz.stock.move.location.line", "move_location_wizard_id", string="Move Location lines", ) picking_type_id = fields.Many2one( comodel_name="stock.picking.type", default=_get_default_picking_type_id ) picking_id = fields.Many2one( string="Connected Picking", comodel_name="stock.picking" ) edit_locations = fields.Boolean(default=True) apply_putaway_strategy = fields.Boolean() @api.depends("edit_locations") def _compute_readonly_locations(self): for rec in self: rec.origin_location_disable = self.env.context.get( "origin_location_disable", False ) rec.destination_location_disable = self.env.context.get( "destination_location_disable", False ) if not rec.edit_locations: rec.origin_location_disable = True rec.destination_location_disable = True @api.model def default_get(self, fields): res = super().default_get(fields) if self.env.context.get("active_model", False) != "stock.quant": return res # Load data directly from quants quants = self.env["stock.quant"].browse( self.env.context.get("active_ids", False) ) res["stock_move_location_line_ids"] = self._prepare_wizard_move_lines(quants) res["origin_location_id"] = first(quants).location_id.id return res @api.model def _prepare_wizard_move_lines(self, quants): res = [] exclude_reserved_qty = self.env.context.get("only_reserved_qty", False) if not exclude_reserved_qty: res = [ ( 0, 0, { "product_id": quant.product_id.id, "move_quantity": quant.quantity, "max_quantity": quant.quantity, "origin_location_id": quant.location_id.id, "lot_id": quant.lot_id.id, "package_id": quant.package_id.id, "owner_id": quant.owner_id.id, "product_uom_id": quant.product_uom_id.id, "custom": False, }, ) for quant in quants ] else: # if need move only available qty per product on location for _product, quant in groupby(quants, lambda r: r.product_id): # we need only one quant per product quant = list(quant)[0] qty = quant._get_available_quantity( quant.product_id, quant.location_id, ) if qty: res.append( ( 0, 0, { "product_id": quant.product_id.id, "move_quantity": qty, "max_quantity": qty, "origin_location_id": quant.location_id.id, "lot_id": quant.lot_id.id, "package_id": quant.package_id.id, "owner_id": quant.owner_id.id, "product_uom_id": quant.product_uom_id.id, "custom": False, }, ) ) return res @api.onchange("origin_location_id") def _onchange_origin_location_id(self): if not self.env.context.get("origin_location_disable", False): self._clear_lines() @api.onchange("destination_location_id") def _onchange_destination_location_id(self): for line in self.stock_move_location_line_ids: line.destination_location_id = self.destination_location_id def _clear_lines(self): self.stock_move_location_line_ids = False def _get_locations_domain(self): return [ "|", ("company_id", "=", self.env.user.company_id.id), ("company_id", "=", False), ] def _create_picking(self): return self.env["stock.picking"].create( { "picking_type_id": self.picking_type_id.id, "location_id": self.origin_location_id.id, "location_dest_id": self.destination_location_id.id, } ) def group_lines(self): lines_grouped = {} for line in self.stock_move_location_line_ids: lines_grouped.setdefault( line.product_id.id, self.env["wiz.stock.move.location.line"].browse() ) lines_grouped[line.product_id.id] |= line return lines_grouped def _create_moves(self, picking): self.ensure_one() groups = self.group_lines() moves = self.env["stock.move"] for lines in groups.values(): move = self._create_move(picking, lines) moves |= move return moves def _get_move_values(self, picking, lines): # locations are same for the products location_from_id = lines[0].origin_location_id.id location_to_id = lines[0].destination_location_id.id product = lines[0].product_id product_uom_id = lines[0].product_uom_id.id qty = sum(x.move_quantity for x in lines) return { "name": product.display_name, "location_id": location_from_id, "location_dest_id": location_to_id, "product_id": product.id, "product_uom": product_uom_id, "product_uom_qty": qty, "picking_id": picking.id, "location_move": True, } def _create_move(self, picking, lines): self.ensure_one() move = self.env["stock.move"].create(self._get_move_values(picking, lines)) if not self.env.context.get("planned"): for line in lines: line.create_move_lines(picking, move) return move def _unreserve_moves(self): """ Try to unreserve moves that they has reserved quantity before user moves products from a location to other one and change move origin location to the new location to assign later. :return moves unreserved """ moves_to_reassign = self.env["stock.move"] lines_to_ckeck_reverve = self.stock_move_location_line_ids.filtered( lambda l: ( l.move_quantity > l.max_quantity - l.reserved_quantity and not l.origin_location_id.should_bypass_reservation() ) ) for line in lines_to_ckeck_reverve: move_lines = self.env["stock.move.line"].search( [ ("state", "=", "assigned"), ("product_id", "=", line.product_id.id), ("location_id", "=", line.origin_location_id.id), ("lot_id", "=", line.lot_id.id), ("package_id", "=", line.package_id.id), ("owner_id", "=", line.owner_id.id), ("product_uom_qty", ">", 0.0), ] ) moves_to_unreserve = move_lines.mapped("move_id") # Unreserve in old location moves_to_unreserve._do_unreserve() moves_to_reassign |= moves_to_unreserve return moves_to_reassign def action_move_location(self): self.ensure_one() if not self.picking_id: picking = self._create_picking() else: picking = self.picking_id self._create_moves(picking) if not self.env.context.get("planned"): moves_to_reassign = self._unreserve_moves() picking.button_validate() moves_to_reassign._action_assign() else: picking.action_confirm() picking.action_assign() self.picking_id = picking return self._get_picking_action(picking.id) def _get_picking_action(self, picking_id): action = self.env["ir.actions.act_window"]._for_xml_id( "stock.action_picking_tree_all" ) view_id = self.env.ref("stock.view_picking_form").id action.update( {"view_mode": "form", "views": [(view_id, "form")], "res_id": picking_id} ) return action def _get_group_quants(self): location_id = self.origin_location_id # Using sql as search_group doesn't support aggregation functions # leading to overhead in queries to DB query = """ SELECT product_id, lot_id, package_id, owner_id, SUM(quantity) AS quantity, SUM(reserved_quantity) AS reserved_quantity FROM stock_quant WHERE location_id = %s GROUP BY product_id, lot_id, package_id, owner_id """ self.env.cr.execute(query, (location_id.id,)) return self.env.cr.dictfetchall() def _get_stock_move_location_lines_values(self): product_obj = self.env["product.product"] product_data = [] for group in self._get_group_quants(): product = product_obj.browse(group.get("product_id")).exists() # Apply the putaway strategy location_dest_id = ( self.apply_putaway_strategy and self.destination_location_id._get_putaway_strategy(product).id or self.destination_location_id.id ) product_data.append( { "product_id": product.id, "move_quantity": group.get("quantity") or 0, "max_quantity": group.get("quantity") or 0, "reserved_quantity": group.get("reserved_quantity"), "origin_location_id": self.origin_location_id.id, "destination_location_id": location_dest_id, # cursor returns None instead of False "lot_id": group.get("lot_id") or False, "package_id": group.get("package_id") or False, "owner_id": group.get("owner_id") or False, "product_uom_id": product.uom_id.id, "custom": False, } ) return product_data @api.onchange("origin_location_id") def onchange_origin_location(self): # Get origin_location_disable context key to prevent load all origin # location products when user opens the wizard from stock quants to # move it to other location. if ( not self.env.context.get("origin_location_disable") and self.origin_location_id ): lines = [] line_model = self.env["wiz.stock.move.location.line"] for line_val in self._get_stock_move_location_lines_values(): if line_val.get("max_quantity") <= 0: continue line = line_model.create(line_val) line.max_quantity = line.get_max_quantity() line.reserved_quantity = line.reserved_quantity lines.append(line) self.update( {"stock_move_location_line_ids": [(6, 0, [line.id for line in lines])]} ) def clear_lines(self): self._clear_lines() return {"type": "ir.action.do_nothing"}
39.087719
13,368
1,011
py
PYTHON
15.0
# Copyright 2019 Tecnativa - Sergio Teruel # Copyright 2023 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import fields, models class StockPickingType(models.Model): _inherit = "stock.picking.type" show_move_onhand = fields.Boolean( string="Show Move On hand stock", help="Show a button 'Move On Hand' in the Inventory Dashboard " "to initiate the process to move the products in stock " "at the origin location.", ) def action_move_location(self): action = self.env["ir.actions.act_window"]._for_xml_id( "stock_move_location.wiz_stock_move_location_action" ) action["context"] = { "default_origin_location_id": self.default_location_src_id.id, "default_destination_location_id": self.default_location_dest_id.id, "default_picking_type_id": self.id, "default_edit_locations": False, } return action
37.444444
1,011
604
py
PYTHON
15.0
# Copyright 2019 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl) from odoo import api, fields, models class StockMove(models.Model): _inherit = "stock.move" location_move = fields.Boolean( string="Part of move location", help="Whether this move is a part of stock_location moves", ) @api.depends("location_move") def _compute_show_details_visible(self): res = super()._compute_show_details_visible() for move in self.filtered(lambda x: x.location_move): move.show_details_visible = True return res
30.2
604
1,664
py
PYTHON
15.0
# Copyright Jacques-Etienne Baudoux 2016 Camptocamp # Copyright Iryna Vyshnevska 2020 Camptocamp # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl) from odoo import _, models from odoo.exceptions import UserError class StockPicking(models.Model): _inherit = "stock.picking" def button_fillwithstock(self): # check source location has no children, i.e. we scanned a bin self.ensure_one() self._validate_picking() context = { "active_ids": self._get_movable_quants().ids, "active_model": "stock.quant", "only_reserved_qty": True, "planned": True, } move_wizard = ( self.env["wiz.stock.move.location"] .with_context(**context) .create( { "destination_location_id": self.location_dest_id.id, "origin_location_id": self.location_id.id, "picking_type_id": self.picking_type_id.id, "picking_id": self.id, } ) ) move_wizard._onchange_destination_location_id() move_wizard.action_move_location() return True def _validate_picking(self): if self.location_id.child_ids: raise UserError(_("Please choose a source end location")) if self.move_lines: raise UserError(_("Moves lines already exists")) def _get_movable_quants(self): return self.env["stock.quant"].search( [ ("location_id", "=", self.location_id.id), ("quantity", ">", 0.0), ] )
32.627451
1,664
360
py
PYTHON
15.0
# Copyright 2019 Tecnativa - Ernesto Tejeda # License AGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). def pre_init_hook(cr): cr.execute( """ALTER TABLE stock_quant ADD COLUMN adjustment_cost numeric DEFAULT 0""" ) cr.execute( """ALTER TABLE stock_quant ALTER COLUMN adjustment_cost DROP DEFAULT;""" )
24
360
651
py
PYTHON
15.0
# Copyright 2019 Tecnativa - Ernesto Tejeda # Copyright 2019 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Stock Quant Cost Info", "summary": "Shows the cost of the quants", "version": "15.0.1.1.0", "author": "Tecnativa, Odoo Community Association (OCA)", "website": "https://github.com/OCA/stock-logistics-warehouse", "category": "Warehouse", "depends": ["stock"], "data": ["views/stock_inventory_views.xml", "views/report_stockinventory.xml"], "pre_init_hook": "pre_init_hook", "license": "AGPL-3", "installable": True, "application": False, }
38.294118
651
1,428
py
PYTHON
15.0
# Copyright 2019 Tecnativa - Ernesto Tejeda # Copyright 2019 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo.tests.common import TransactionCase, tagged @tagged("post_install", "-at_install") class TestStockQuantCostInfo(TransactionCase): def setUp(self): super().setUp() product_obj = self.env["product.product"] self.product_1 = product_obj.create( {"name": "product test 1", "type": "product", "standard_price": 1000} ) self.product_2 = product_obj.create( {"name": "product test 2", "type": "product", "standard_price": 2000} ) def test_compute_adjustment_cost(self): """Tests if the adjustment_cost is correctly computed.""" quant_prod_1 = self.env["stock.quant"].create( { "product_id": self.product_1.id, "location_id": self.env.ref("stock.stock_location_stock").id, "inventory_quantity": 10.0, } ) self.assertEqual(quant_prod_1.adjustment_cost, 10000) quant_prod_2 = self.env["stock.quant"].create( { "product_id": self.product_2.id, "location_id": self.env.ref("stock.stock_location_stock").id, "inventory_quantity": 20.0, } ) self.assertEqual(quant_prod_2.adjustment_cost, 40000)
38.594595
1,428
744
py
PYTHON
15.0
# Copyright 2019 Tecnativa - Ernesto Tejeda # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import api, fields, models class StockQuant(models.Model): _inherit = "stock.quant" currency_id = fields.Many2one( comodel_name="res.currency", string="Currency", related="company_id.currency_id" ) adjustment_cost = fields.Monetary( string="Adjustment cost", compute="_compute_adjustment_cost", store=True ) @api.depends("inventory_diff_quantity", "product_id.standard_price") def _compute_adjustment_cost(self): for record in self: record.adjustment_cost = ( record.inventory_diff_quantity * record.product_id.standard_price )
33.818182
744
679
py
PYTHON
15.0
# Copyright 2018 Camptocamp SA # Copyright 2016-19 ForgeFlow S.L. (https://www.forgeflow.com) # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). { "name": "Stock Available Unreserved", "summary": "Quantity of stock available for immediate use", "version": "15.0.1.0.0", "author": "ForgeFlow, Odoo Community Association (OCA)", "development_status": "Production/Stable", "maintainers": ["LoisRForgeFlow"], "website": "https://github.com/OCA/stock-logistics-warehouse", "category": "Warehouse Management", "depends": ["stock"], "data": ["views/stock_quant_view.xml", "views/product_view.xml"], "license": "LGPL-3", }
39.941176
679
17,235
py
PYTHON
15.0
# Copyright 2018 Camptocamp SA # Copyright 2016-19 ForgeFlow S.L. (https://www.forgeflow.com) # Copyright 2019 JARSA Sistemas S.A. de C.V. # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo.tests.common import TransactionCase class TestStockLogisticsWarehouse(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.pickingObj = cls.env["stock.picking"] cls.productObj = cls.env["product.product"] cls.templateObj = cls.env["product.template"] cls.attrObj = cls.env["product.attribute"] cls.attrvalueObj = cls.env["product.attribute.value"] cls.supplier_location = cls.env.ref("stock.stock_location_suppliers") cls.stock_location = cls.env.ref("stock.stock_location_stock") cls.customer_location = cls.env.ref("stock.stock_location_customers") cls.uom_unit = cls.env.ref("uom.product_uom_unit") cls.main_company = cls.env.ref("base.main_company") cls.bin_a = cls.env["stock.location"].create( { "usage": "internal", "name": "Bin A", "location_id": cls.stock_location.id, "company_id": cls.main_company.id, } ) cls.bin_b = cls.env["stock.location"].create( { "usage": "internal", "name": "Bin B", "location_id": cls.stock_location.id, "company_id": cls.main_company.id, } ) cls.env["stock.location"]._parent_store_compute() # Create product template cls.templateAB = cls.templateObj.create( {"name": "templAB", "uom_id": cls.uom_unit.id, "type": "product"} ) # Create product A and B cls.color_attribute = cls.attrObj.create({"name": "Color", "sequence": 1}) cls.color_black = cls.attrvalueObj.create( {"name": "Black", "attribute_id": cls.color_attribute.id, "sequence": 1} ) cls.color_white = cls.attrvalueObj.create( {"name": "White", "attribute_id": cls.color_attribute.id, "sequence": 2} ) cls.color_grey = cls.attrvalueObj.create( {"name": "Grey", "attribute_id": cls.color_attribute.id, "sequence": 3} ) cls.product_attribute_line = cls.env["product.template.attribute.line"].create( { "product_tmpl_id": cls.templateAB.id, "attribute_id": cls.color_attribute.id, "value_ids": [ (6, 0, [cls.color_white.id, cls.color_black.id, cls.color_grey.id]) ], } ) cls.productA = cls.templateAB.product_variant_ids[0] cls.productB = cls.templateAB.product_variant_ids[1] cls.productC = cls.templateAB.product_variant_ids[2] # Create a picking move from INCOMING to STOCK cls.pickingInA = cls.pickingObj.create( { "picking_type_id": cls.env.ref("stock.picking_type_in").id, "location_id": cls.supplier_location.id, "location_dest_id": cls.stock_location.id, "move_lines": [ ( 0, 0, { "name": "Test move", "product_id": cls.productA.id, "product_uom": cls.productA.uom_id.id, "product_uom_qty": 2, "quantity_done": 2, "location_id": cls.supplier_location.id, "location_dest_id": cls.stock_location.id, }, ) ], } ) cls.pickingInB = cls.pickingObj.create( { "picking_type_id": cls.env.ref("stock.picking_type_in").id, "location_id": cls.supplier_location.id, "location_dest_id": cls.stock_location.id, "move_lines": [ ( 0, 0, { "name": "Test move", "product_id": cls.productB.id, "product_uom": cls.productB.uom_id.id, "product_uom_qty": 3, "quantity_done": 3, "location_id": cls.supplier_location.id, "location_dest_id": cls.stock_location.id, }, ) ], } ) cls.pickingOutA = cls.pickingObj.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, "immediate_transfer": False, "move_lines": [ ( 0, 0, { "name": "Test move", "product_id": cls.productB.id, "product_uom": cls.productB.uom_id.id, "product_uom_qty": 2, "location_id": cls.stock_location.id, "location_dest_id": cls.customer_location.id, }, ) ], } ) def compare_qty_available_not_res(self, product, value): product.invalidate_cache() self.assertEqual(product.qty_available_not_res, value) def test_01_stock_levels(self): """checking that qty_available_not_res actually reflects \ the variations in stock, both on product and template""" self.compare_qty_available_not_res(self.productA, 0) self.compare_qty_available_not_res(self.templateAB, 0) self.pickingInA.action_confirm() self.compare_qty_available_not_res(self.productA, 0) self.compare_qty_available_not_res(self.templateAB, 0) self.pickingInA.button_validate() self.compare_qty_available_not_res(self.productA, 2) self.compare_qty_available_not_res(self.templateAB, 2) # will directly trigger button_validate on self.productB self.pickingInB.button_validate() self.compare_qty_available_not_res(self.productA, 2) self.compare_qty_available_not_res(self.productB, 3) self.compare_qty_available_not_res(self.templateAB, 5) self.compare_qty_available_not_res(self.productB, 3) self.compare_qty_available_not_res(self.templateAB, 5) self.pickingOutA.action_confirm() self.compare_qty_available_not_res(self.productB, 1) self.compare_qty_available_not_res(self.templateAB, 3) self.pickingOutA.button_validate() self.compare_qty_available_not_res(self.productB, 1) self.compare_qty_available_not_res(self.templateAB, 3) self.templateAB.action_open_quants_unreserved() def test_02_more_than_one_quant(self): self.env["stock.quant"].create( { "location_id": self.stock_location.id, "company_id": self.main_company.id, "product_id": self.productA.id, "quantity": 10.0, } ) self.env["stock.quant"].create( { "location_id": self.bin_a.id, "company_id": self.main_company.id, "product_id": self.productA.id, "quantity": 10.0, } ) self.env["stock.quant"].create( { "location_id": self.bin_b.id, "company_id": self.main_company.id, "product_id": self.productA.id, "quantity": 60.0, } ) self.compare_qty_available_not_res(self.productA, 80) def check_variants_found_correctly(self, operator, value, expected): domain = [("id", "in", self.templateAB.product_variant_ids.ids)] return self.check_found_correctly( self.env["product.product"], domain, operator, value, expected ) def check_template_found_correctly(self, operator, value, expected): # There may be other products already in the system: ignore those domain = [("id", "in", self.templateAB.ids)] return self.check_found_correctly( self.env["product.template"], domain, operator, value, expected ) def check_found_correctly(self, model, domain, operator, value, expected): found = model.search(domain + [("qty_available_not_res", operator, value)]) if found != expected: self.fail( "Searching for products failed: search for unreserved " "quantity {operator} {value}; expected to find " "{expected}, but found {found}".format( operator=operator, value=value, expected=expected or "no products", found=found, ) ) def test_03_stock_search(self): all_variants = self.templateAB.product_variant_ids a_and_b = self.productA + self.productB b_and_c = self.productB + self.productC a_and_c = self.productA + self.productC no_variants = self.env["product.product"] no_template = self.env["product.template"] # Start: one template with three variants. # All variants have zero unreserved stock self.check_variants_found_correctly("=", 0, all_variants) self.check_variants_found_correctly(">=", 0, all_variants) self.check_variants_found_correctly("<=", 0, all_variants) self.check_variants_found_correctly(">", 0, no_variants) self.check_variants_found_correctly("<", 0, no_variants) self.check_variants_found_correctly("!=", 0, no_variants) self.check_template_found_correctly("=", 0, self.templateAB) self.check_template_found_correctly(">=", 0, self.templateAB) self.check_template_found_correctly("<=", 0, self.templateAB) self.check_template_found_correctly(">", 0, no_template) self.check_template_found_correctly("<", 0, no_template) self.check_template_found_correctly("!=", 0, no_template) self.pickingInA.action_confirm() # All variants still have zero unreserved stock self.check_variants_found_correctly("=", 0, all_variants) self.check_variants_found_correctly(">=", 0, all_variants) self.check_variants_found_correctly("<=", 0, all_variants) self.check_variants_found_correctly(">", 0, no_variants) self.check_variants_found_correctly("<", 0, no_variants) self.check_variants_found_correctly("!=", 0, no_variants) self.check_template_found_correctly("=", 0, self.templateAB) self.check_template_found_correctly(">=", 0, self.templateAB) self.check_template_found_correctly("<=", 0, self.templateAB) self.check_template_found_correctly(">", 0, no_template) self.check_template_found_correctly("<", 0, no_template) self.check_template_found_correctly("!=", 0, no_template) self.pickingInA.action_assign() # All variants still have zero unreserved stock self.check_variants_found_correctly("=", 0, all_variants) self.check_variants_found_correctly(">=", 0, all_variants) self.check_variants_found_correctly("<=", 0, all_variants) self.check_variants_found_correctly(">", 0, no_variants) self.check_variants_found_correctly("<", 0, no_variants) self.check_variants_found_correctly("!=", 0, no_variants) self.check_template_found_correctly("=", 0, self.templateAB) self.check_template_found_correctly(">=", 0, self.templateAB) self.check_template_found_correctly("<=", 0, self.templateAB) self.check_template_found_correctly(">", 0, no_template) self.check_template_found_correctly("<", 0, no_template) self.check_template_found_correctly("!=", 0, no_template) self.pickingInA.button_validate() # product A has 2 unreserved stock, other variants have 0 self.check_variants_found_correctly("=", 2, self.productA) self.check_variants_found_correctly("=", 0, b_and_c) self.check_variants_found_correctly(">", 0, self.productA) self.check_variants_found_correctly("<", 0, no_variants) self.check_variants_found_correctly("!=", 0, self.productA) self.check_variants_found_correctly("!=", 1, all_variants) self.check_variants_found_correctly("!=", 2, b_and_c) self.check_variants_found_correctly("<=", 0, b_and_c) self.check_variants_found_correctly("<=", 1, b_and_c) self.check_variants_found_correctly(">=", 0, all_variants) self.check_variants_found_correctly(">=", 1, self.productA) self.check_template_found_correctly("=", 0, self.templateAB) self.check_template_found_correctly("=", 1, no_template) self.check_template_found_correctly("=", 2, self.templateAB) self.check_template_found_correctly("!=", 0, self.templateAB) self.check_template_found_correctly("!=", 1, self.templateAB) self.check_template_found_correctly("!=", 2, self.templateAB) self.check_template_found_correctly(">", -1, self.templateAB) self.check_template_found_correctly(">", 0, self.templateAB) self.check_template_found_correctly(">", 1, self.templateAB) self.check_template_found_correctly(">", 2, no_template) self.check_template_found_correctly("<", 3, self.templateAB) self.check_template_found_correctly("<", 2, self.templateAB) self.check_template_found_correctly("<", 1, self.templateAB) self.check_template_found_correctly("<", 0, no_template) self.check_template_found_correctly(">=", 0, self.templateAB) self.check_template_found_correctly(">=", 1, self.templateAB) self.check_template_found_correctly(">=", 2, self.templateAB) self.check_template_found_correctly(">=", 3, no_template) self.check_template_found_correctly("<=", 3, self.templateAB) self.check_template_found_correctly("<=", 2, self.templateAB) self.check_template_found_correctly("<=", 1, self.templateAB) self.check_template_found_correctly("<=", 0, self.templateAB) self.check_template_found_correctly("<=", -1, no_template) self.pickingInB.button_validate() # product A has 2 unreserved, product B has 3 unreserved and # the remaining variant has 0 self.check_variants_found_correctly("=", 2, self.productA) self.check_variants_found_correctly("=", 3, self.productB) self.check_variants_found_correctly("=", 0, self.productC) self.check_variants_found_correctly(">", 0, a_and_b) self.check_variants_found_correctly("<", 0, no_variants) self.check_variants_found_correctly("!=", 0, a_and_b) self.check_variants_found_correctly("!=", 1, all_variants) self.check_variants_found_correctly("!=", 2, b_and_c) self.check_variants_found_correctly("!=", 3, a_and_c) self.check_variants_found_correctly("<=", 0, self.productC) self.check_variants_found_correctly("<=", 1, self.productC) self.check_variants_found_correctly(">=", 0, all_variants) self.check_variants_found_correctly(">=", 1, a_and_b) self.check_variants_found_correctly(">=", 2, a_and_b) self.check_variants_found_correctly(">=", 3, self.productB) self.check_variants_found_correctly(">=", 4, no_variants) self.check_template_found_correctly("=", 0, self.templateAB) self.check_template_found_correctly("=", 1, no_template) self.check_template_found_correctly("=", 2, self.templateAB) self.check_template_found_correctly("=", 3, self.templateAB) self.check_template_found_correctly("!=", 0, self.templateAB) self.check_template_found_correctly("!=", 2, self.templateAB) self.check_template_found_correctly("!=", 3, self.templateAB) self.check_template_found_correctly(">", 1, self.templateAB) self.check_template_found_correctly(">", 2, self.templateAB) # This part may seem a bit unintuitive, but this is the # way it works in the Odoo core # Searches are "deferred" to the variants, so while the template says # it has a stock of 5, searching for a stock greater than 3 will not # find anything because no singular variant has a higher stock self.check_template_found_correctly(">", 3, no_template) self.check_template_found_correctly("<", 3, self.templateAB) self.check_template_found_correctly("<", 2, self.templateAB) self.check_template_found_correctly("<", 1, self.templateAB) self.check_template_found_correctly("<", 0, no_template)
46.707317
17,235
879
py
PYTHON
15.0
# Copyright 2018 Camptocamp SA # 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 api, fields, models class StockQuant(models.Model): _inherit = "stock.quant" contains_unreserved = fields.Boolean( string="Contains unreserved products", compute="_compute_contains_unreserved", store=True, ) @api.depends("quantity", "reserved_quantity") def _compute_contains_unreserved(self): for record in self: # Avoid error when adding a new line on manually Update Quantity if isinstance(record.id, models.NewId): record.contains_unreserved = False continue record.contains_unreserved = ( True if record.available_quantity > 0 else False )
33.807692
879
1,691
py
PYTHON
15.0
# Copyright 2018 Camptocamp SA # 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 api, fields, models class ProductTemplate(models.Model): _inherit = "product.template" qty_available_not_res = fields.Float( string="Quantity On Hand Unreserved", digits="Product Unit of Measure", compute="_compute_product_available_not_res", search="_search_quantity_unreserved", help="Quantity of this product that is " "not currently reserved for a stock move", ) @api.depends("product_variant_ids.qty_available_not_res") def _compute_product_available_not_res(self): for tmpl in self: if isinstance(tmpl.id, models.NewId): continue tmpl.qty_available_not_res = sum( tmpl.mapped("product_variant_ids.qty_available_not_res") ) def action_open_quants_unreserved(self): products_ids = self.mapped("product_variant_ids").ids quants = self.env["stock.quant"].search([("product_id", "in", products_ids)]) quant_ids = quants.filtered( lambda x: x.product_id.qty_available_not_res > 0 ).ids result = self.env.ref("stock.group_stock_multi_locations").read()[0] result["domain"] = [("id", "in", quant_ids)] result["context"] = { "search_default_locationgroup": 1, "search_default_internal_loc": 1, } return result def _search_quantity_unreserved(self, operator, value): return [("product_variant_ids.qty_available_not_res", operator, value)]
38.431818
1,691
2,967
py
PYTHON
15.0
# Copyright 2018 Camptocamp SA # 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 _, api, fields, models from odoo.exceptions import UserError from odoo.tools.float_utils import float_round from odoo.addons.stock.models.product import OPERATORS class ProductProduct(models.Model): _inherit = "product.product" qty_available_not_res = fields.Float( string="Qty Available Not Reserved", digits="Product Unit of Measure", compute="_compute_qty_available_not_reserved", search="_search_quantity_unreserved", help="Quantity of this product that is " "not currently reserved for a stock move", ) def _prepare_domain_available_not_reserved(self): domain_quant = [("product_id", "in", self.ids)] domain_quant_locations = self._get_domain_locations()[0] domain_quant.extend(domain_quant_locations) return domain_quant def _compute_product_available_not_res_dict(self): res = {} domain_quant = self._prepare_domain_available_not_reserved() quants = ( self.env["stock.quant"] .with_context(lang=False) .read_group( domain_quant, ["product_id", "location_id", "quantity", "reserved_quantity"], ["product_id", "location_id"], lazy=False, ) ) product_sums = {} for quant in quants: # create a dictionary with the total value per products product_sums.setdefault(quant["product_id"][0], 0.0) product_sums[quant["product_id"][0]] += ( quant["quantity"] - quant["reserved_quantity"] ) for product in self.with_context(prefetch_fields=False, lang=""): available_not_res = float_round( product_sums.get(product.id, 0.0), precision_rounding=product.uom_id.rounding, ) res[product.id] = {"qty_available_not_res": available_not_res} return res @api.depends("stock_move_ids.product_qty", "stock_move_ids.state") def _compute_qty_available_not_reserved(self): res = self._compute_product_available_not_res_dict() for prod in self: qty = res[prod.id]["qty_available_not_res"] prod.qty_available_not_res = qty return res def _search_quantity_unreserved(self, operator, value): if operator not in OPERATORS: raise UserError(_("Invalid domain operator %s") % operator) if not isinstance(value, (float, int)): raise UserError(_("Invalid domain right operand %s") % value) ids = [] for product in self.search([]): if OPERATORS[operator](product.qty_available_not_res, value): ids.append(product.id) return [("id", "in", ids)]
38.038462
2,967
647
py
PYTHON
15.0
# Copyright 2014 Numérigraphe # Copyright 2016 Sodexis # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Stock available to promise", "version": "15.0.1.0.0", "author": "Numérigraphe, Sodexis, Odoo Community Association (OCA)", "website": "https://github.com/OCA/stock-logistics-warehouse", "development_status": "Production/Stable", "category": "Warehouse", "depends": ["stock"], "license": "AGPL-3", "data": [ "views/product_template_view.xml", "views/product_product_view.xml", "views/res_config_settings_views.xml", ], "installable": True, }
32.25
645
6,924
py
PYTHON
15.0
# Copyright 2014 Numérigraphe # Copyright 2016 Sodexis # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo.tests.common import TransactionCase class TestStockLogisticsWarehouse(TransactionCase): def test_res_config(self): """Test the config file""" stock_setting = self.env["res.config.settings"].create({}) self.assertEqual(stock_setting.stock_available_mrp_based_on, "qty_available") stock_setting.stock_available_mrp_based_on = "immediately_usable_qty" stock_setting.set_values() self.assertEqual( stock_setting.stock_available_mrp_based_on, "immediately_usable_qty" ) def test01_stock_levels(self): """checking that immediately_usable_qty actually reflects \ the variations in stock, both on product and template""" moveObj = self.env["stock.move"] productObj = self.env["product.product"] templateObj = self.env["product.template"] supplier_location = self.env.ref("stock.stock_location_suppliers") stock_location = self.env.ref("stock.stock_location_stock") customer_location = self.env.ref("stock.stock_location_customers") uom_unit = self.env.ref("uom.product_uom_unit") # Create product template templateAB = templateObj.create({"name": "templAB", "uom_id": uom_unit.id}) # Create product A and B productA = productObj.create( { "name": "product A", "standard_price": 1, "type": "product", "uom_id": uom_unit.id, "default_code": "A", "product_tmpl_id": templateAB.id, } ) productB = productObj.create( { "name": "product B", "standard_price": 1, "type": "product", "uom_id": uom_unit.id, "default_code": "B", "product_tmpl_id": templateAB.id, } ) # Create a stock move from INCOMING to STOCK stockMoveInA = moveObj.create( { "location_id": supplier_location.id, "location_dest_id": stock_location.id, "name": "MOVE INCOMING -> STOCK ", "product_id": productA.id, "product_uom": productA.uom_id.id, "product_uom_qty": 2, } ) stockMoveInB = moveObj.create( { "location_id": supplier_location.id, "location_dest_id": stock_location.id, "name": "MOVE INCOMING -> STOCK ", "product_id": productB.id, "product_uom": productB.uom_id.id, "product_uom_qty": 3, } ) def compare_product_usable_qty(product, value): """ Compare the immediately_usable_qty with the given value Check also the search function for the immediately_usable_qty field :param product: product (template/product) recordset :param value: int :return: """ # Refresh, because the function field is not recalculated between # transactions product.refresh() self.assertEqual(product.immediately_usable_qty, value) # Now check search function domain = [("immediately_usable_qty", "=", value)] results = self.env[product._name].search(domain) self.assertIn(product.id, results.ids) domain = [("immediately_usable_qty", "!=", value)] results = self.env[product._name].search(domain) self.assertNotIn(product.id, results.ids) domain = [("immediately_usable_qty", ">", value - 1)] results = self.env[product._name].search(domain) self.assertIn(product.id, results.ids) domain = [("immediately_usable_qty", "<", value + 1)] results = self.env[product._name].search(domain) self.assertIn(product.id, results.ids) compare_product_usable_qty(productA, 0) compare_product_usable_qty(templateAB, 0) stockMoveInA._action_confirm() compare_product_usable_qty(productA, 2) compare_product_usable_qty(templateAB, 2) stockMoveInA._action_assign() compare_product_usable_qty(productA, 2) compare_product_usable_qty(templateAB, 2) stockMoveInA._action_done() compare_product_usable_qty(productA, 2) compare_product_usable_qty(templateAB, 2) # will directly trigger action_done on productB stockMoveInB._action_done() compare_product_usable_qty(productA, 2) compare_product_usable_qty(productB, 3) compare_product_usable_qty(templateAB, 5) # Create a stock move from STOCK to CUSTOMER stockMoveOutA = moveObj.create( { "location_id": stock_location.id, "location_dest_id": customer_location.id, "name": " STOCK --> CUSTOMER ", "product_id": productA.id, "product_uom": productA.uom_id.id, "product_uom_qty": 1, "state": "confirmed", } ) stockMoveOutA._action_done() compare_product_usable_qty(productA, 1) compare_product_usable_qty(templateAB, 4) # Potential Qty is set as 0.0 by default self.assertEqual(templateAB.potential_qty, 0.0) self.assertEqual(productA.potential_qty, 0.0) def test_available_stock_multiple_location(self): uom_unit = self.env.ref("uom.product_uom_unit") productA = self.env["product.product"].create( { "name": "product A", "standard_price": 1, "type": "product", "uom_id": uom_unit.id, "default_code": "A", } ) supplier_location = self.env.ref("stock.stock_location_suppliers") shelf1 = self.env.ref("stock.stock_location_components") shelf2 = self.env.ref("stock.stock_location_14") # Create a stock move from INCOMING to STOCK stockMoveIn = self.env["stock.move"].create( { "location_id": supplier_location.id, "location_dest_id": shelf1.id, "name": "MOVE INCOMING -> STOCK ", "product_id": productA.id, "product_uom": productA.uom_id.id, "product_uom_qty": 2, } ) stockMoveIn._action_confirm() self.assertEqual( productA.with_context(location=shelf1.id).immediately_usable_qty, 2.0 ) self.assertEqual( productA.with_context(location=shelf2.id).immediately_usable_qty, 0.0 )
38.461111
6,923
3,120
py
PYTHON
15.0
# Copyright 2014 Numérigraphe # Copyright 2016 Sodexis # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models from odoo.addons.stock.models.product import OPERATORS class ProductTemplate(models.Model): _inherit = "product.template" @api.depends( "product_variant_ids.immediately_usable_qty", "product_variant_ids.potential_qty", ) def _compute_available_quantities(self): res = self._compute_available_quantities_dict() for product in self: for key, value in res[product.id].items(): if key in product._fields: product[key] = value def _compute_available_quantities_dict(self): variants_dict, _ = self.mapped( "product_variant_ids" )._compute_available_quantities_dict() res = {} for template in self: immediately_usable_qty = sum( variants_dict[p.id]["immediately_usable_qty"] - variants_dict[p.id]["potential_qty"] for p in template.product_variant_ids ) potential_qty = max( [ variants_dict[p.id]["potential_qty"] for p in template.product_variant_ids ] or [0.0] ) res[template.id] = { "immediately_usable_qty": immediately_usable_qty + potential_qty, "potential_qty": potential_qty, } return res immediately_usable_qty = fields.Float( digits="Product Unit of Measure", compute="_compute_available_quantities", search="_search_immediately_usable_qty", string="Available to promise", help="Stock for this Product that can be safely proposed " "for sale to Customers.\n" "The definition of this value can be configured to suit " "your needs", ) potential_qty = fields.Float( compute="_compute_available_quantities", digits="Product Unit of Measure", string="Potential", help="Quantity of this Product that could be produced using " "the materials already at hand. " "If the product has several variants, this will be the biggest " "quantity that can be made for a any single variant.", ) @api.model def _search_immediately_usable_qty(self, operator, value): """Search function for the immediately_usable_qty field. The search is quite similar to the Odoo search about quantity available (addons/stock/models/product.py,253; _search_product_quantity function) :param operator: str :param value: str :return: list of tuple (domain) """ products = self.search([]) # Force prefetch products.mapped("immediately_usable_qty") product_ids = [] for product in products: if OPERATORS[operator](product.immediately_usable_qty, value): product_ids.append(product.id) return [("id", "in", product_ids)]
37.130952
3,119
3,162
py
PYTHON
15.0
# Copyright 2014 Numérigraphe # Copyright 2016 Sodexis # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models from odoo.addons.stock.models.product import OPERATORS class ProductProduct(models.Model): """Add a field for the stock available to promise. Useful implementations need to be installed through the Settings menu or by installing one of the modules stock_available_* """ _inherit = "product.product" def _compute_available_quantities_dict(self): stock_dict = self._compute_quantities_dict( self._context.get("lot_id"), self._context.get("owner_id"), self._context.get("package_id"), self._context.get("from_date"), self._context.get("to_date"), ) res = {} for product in self: res[product.id] = { "immediately_usable_qty": stock_dict[product.id]["virtual_available"], "potential_qty": 0.0, } return res, stock_dict @api.depends("virtual_available") @api.depends_context( "lot_id", "owner_id", "package_id", "from_date", "to_date", "location", "warehouse", ) def _compute_available_quantities(self): res, _ = self._compute_available_quantities_dict() for product in self: for key, value in res[product.id].items(): if hasattr(product, key): product[key] = value immediately_usable_qty = fields.Float( digits="Product Unit of Measure", compute="_compute_available_quantities", search="_search_immediately_usable_qty", string="Available to promise", help="Stock for this Product that can be safely proposed " "for sale to Customers.\n" "The definition of this value can be configured to suit " "your needs.", ) potential_qty = fields.Float( compute="_compute_available_quantities", digits="Product Unit of Measure", string="Potential", help="Quantity of this Product that could be produced using " "the materials already at hand.", ) def _get_search_immediately_usable_qty_domain(self): return [("type", "=", "product")] @api.model def _search_immediately_usable_qty(self, operator, value): """Search function for the immediately_usable_qty field. The search is quite similar to the Odoo search about quantity available (addons/stock/models/product.py,253; _search_product_quantity function) :param operator: str :param value: str :return: list of tuple (domain) """ product_domain = self._get_search_immediately_usable_qty_domain() products = self.with_context(prefetch_fields=False).search( product_domain, order="id" ) product_ids = [] for product in products: if OPERATORS[operator](product.immediately_usable_qty, value): product_ids.append(product.id) return [("id", "in", product_ids)]
35.122222
3,161
2,761
py
PYTHON
15.0
# Copyright 2014 Numérigraphe # Copyright 2016 Sodexis # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models class ResConfigSettings(models.TransientModel): """Add options to easily install the submodules""" _inherit = "res.config.settings" @api.model def _get_stock_available_mrp_based_on(self): """Gets the available languages for the selection.""" pdct_fields = ( self.env["ir.model.fields"] .sudo() .search([("model", "=", "product.product"), ("ttype", "=", "float")]) ) return [ (field.name, field.field_description) for field in sorted(pdct_fields, key=lambda f: f.field_description) ] module_stock_available_immediately = fields.Boolean( string="Exclude incoming goods", help="This will subtract incoming quantities from the quantities " "available to promise.\n" "This installs the module stock_available_immediately.", ) module_stock_available_sale = fields.Boolean( string="Exclude goods already in sale quotations", help="This will subtract quantities from the sale quotations from " "the quantities available to promise.\n" "This installs the modules stock_available_sale.\n" "If the modules sale and sale_delivery_date are not " "installed, this will install them too", ) module_stock_available_mrp = fields.Boolean( string="Include the production potential", help="This will add the quantities of goods that can be " "immediately manufactured, to the quantities available to " "promise.\n" "This installs the module stock_available_mrp.\n" "If the module mrp is not installed, this will install it " "too", ) stock_available_mrp_based_on = fields.Selection( _get_stock_available_mrp_based_on, string="based on", help="Choose the field of the product which will be used to compute " "potential.\nIf empty, Quantity On Hand is used.\n" "Only the quantity fields have meaning for computing stock", ) @api.model def get_values(self): res = super(ResConfigSettings, self).get_values() res.update( stock_available_mrp_based_on=self.env["ir.config_parameter"] .sudo() .get_param("stock_available_mrp_based_on", "qty_available") ) return res def set_values(self): res = super(ResConfigSettings, self).set_values() self.env["ir.config_parameter"].sudo().set_param( "stock_available_mrp_based_on", self.stock_available_mrp_based_on ) return res
36.8
2,760
549
py
PYTHON
15.0
# Copyright 2019 ForgeFlow, S.L. # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). { "name": "Stock Orderpoint Move Link", "summary": "Link Reordering rules to stock moves", "version": "15.0.1.0.0", "license": "LGPL-3", "website": "https://github.com/OCA/stock-logistics-warehouse", "author": "ForgeFlow, Odoo Community Association (OCA)", "category": "Warehouse Management", "depends": ["stock"], "data": ["views/stock_move_views.xml"], "installable": True, "auto_install": False, }
34.3125
549
4,272
py
PYTHON
15.0
# Copyright 2019 ForgeFlow S.L. # License LGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import ast from odoo.tests.common import TransactionCase class TestStockOrderpointMoveLink(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.product_obj = cls.env["product.product"] cls.orderpoint_obj = cls.env["stock.warehouse.orderpoint"] cls.loc_obj = cls.env["stock.location"] cls.route_obj = cls.env["stock.location.route"] cls.group_obj = cls.env["procurement.group"] cls.move_obj = cls.env["stock.move"] cls.picking_obj = cls.env["stock.picking"] cls.warehouse = cls.env.ref("stock.warehouse0") cls.stock_loc = cls.env.ref("stock.stock_location_stock") # Create a new locations and routes: cls.intermediate_loc = cls.loc_obj.create( { "name": "Test location 1", "usage": "internal", "location_id": cls.warehouse.view_location_id.id, } ) cls.test_route = cls.route_obj.create( { "name": "Stock -> Test 1", "product_selectable": True, "rule_ids": [ ( 0, 0, { "name": "stock to test", "action": "pull", "location_id": cls.intermediate_loc.id, "location_src_id": cls.stock_loc.id, "procure_method": "make_to_stock", "picking_type_id": cls.env.ref( "stock.picking_type_internal" ).id, }, ) ], } ) cls.need_loc = cls.loc_obj.create( { "name": "Test location 2", "usage": "internal", "location_id": cls.warehouse.view_location_id.id, } ) cls.test_route_2 = cls.route_obj.create( { "name": "Test 1 -> Test 2", "product_selectable": True, "rule_ids": [ ( 0, 0, { "name": "Test 1 to Test 2", "action": "pull", "location_id": cls.need_loc.id, "location_src_id": cls.intermediate_loc.id, "procure_method": "make_to_order", "picking_type_id": cls.env.ref( "stock.picking_type_internal" ).id, }, ) ], } ) # Prepare Products: routes = cls.test_route_2 + cls.test_route cls.product = cls.product_obj.create( {"name": "Test Product", "route_ids": [(6, 0, routes.ids)]} ) # Create Orderpoint: cls.orderpoint_need_loc = cls.orderpoint_obj.create( { "warehouse_id": cls.warehouse.id, "location_id": cls.need_loc.id, "product_id": cls.product.id, "product_min_qty": 10.0, "product_max_qty": 50.0, "product_uom": cls.product.uom_id.id, } ) cls.group_obj.run_scheduler() def test_01_stock_orderpoint_move_link(self): """Tests if manual procurement fills orderpoint_ids field.""" move = self.move_obj.search( [("orderpoint_ids", "=", self.orderpoint_need_loc.id)] ) self.assertTrue(len(move), 2) def test_02_stock_orderpoint_move_link_action_view(self): sp_orderpoint = self.move_obj.search( [("orderpoint_ids", "in", self.orderpoint_need_loc.id)] ).mapped("picking_id") result = self.orderpoint_need_loc.action_view_stock_picking() sp_action = self.picking_obj.search(ast.literal_eval(result["domain"])) self.assertEqual(sp_orderpoint, sp_action)
36.827586
4,272
891
py
PYTHON
15.0
# Copyright 2019 ForgeFlow, S.L., Ecosoft # 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 _get_stock_move_values( self, product_id, product_qty, product_uom, location_id, name, origin, company_id, values, ): vals = super()._get_stock_move_values( product_id, product_qty, product_uom, location_id, name, origin, company_id, values, ) if "orderpoint_id" in values: vals["orderpoint_ids"] = [(4, values["orderpoint_id"].id)] elif "orderpoint_ids" in values: vals["orderpoint_ids"] = [(4, o.id) for o in values["orderpoint_ids"]] return vals
26.205882
891
711
py
PYTHON
15.0
# Copyright 2019 ForgeFlow, S.L. # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import fields, models class StockMove(models.Model): _inherit = "stock.move" orderpoint_ids = fields.Many2many( comodel_name="stock.warehouse.orderpoint", string="Linked Reordering Rules" ) def _prepare_procurement_values(self): res = super()._prepare_procurement_values() if self.orderpoint_ids: res["orderpoint_ids"] = self.orderpoint_ids return res def _merge_moves_fields(self): res = super()._merge_moves_fields() res["orderpoint_ids"] = [(4, m.id) for m in self.mapped("orderpoint_ids")] return res
32.318182
711
666
py
PYTHON
15.0
# Copyright 2019 ForgeFlow S.L. # (http://www.forgeflow.com) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import models class StockWarehouseOrderpoint(models.Model): _inherit = "stock.warehouse.orderpoint" def action_view_stock_picking(self): action = self.env.ref("stock.action_picking_tree_all") result = action.read()[0] result["context"] = {} picking_ids = ( self.env["stock.move"] .search([("orderpoint_ids", "in", self.id)]) .mapped("picking_id") ) result["domain"] = "[('id','in',%s)]" % picking_ids.ids return result
31.714286
666
542
py
PYTHON
15.0
# Copyright 2020 Camptocamp SA # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl) { "name": "Stock packaging calculator", "summary": "Compute product quantity to pick by packaging", "version": "15.0.1.0.0", "development_status": "Alpha", "category": "Warehouse Management", "website": "https://github.com/OCA/stock-logistics-warehouse", "author": "Camptocamp, Odoo Community Association (OCA)", "license": "LGPL-3", "application": False, "installable": True, "depends": ["product"], }
36.133333
542
2,409
py
PYTHON
15.0
# Copyright 2021 Camptocamp SA # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl) from .common import TestCommon class TestAsStr(TestCommon): def test_as_str(self): self.assertEqual(self.product_a.product_qty_by_packaging_as_str(10), "10 Units") self.assertEqual( self.product_a.product_qty_by_packaging_as_str(10, only_packaging=True), "" ) self.assertEqual(self.product_a.product_qty_by_packaging_as_str(100), "2 Box") self.assertEqual( self.product_a.product_qty_by_packaging_as_str(250), "1 Big Box,\xa01 Box" ) self.assertEqual( self.product_a.product_qty_by_packaging_as_str(255), "1 Big Box,\xa01 Box,\xa05 Units", ) # only_packaging has no impact if we get not only units self.assertEqual( self.product_a.product_qty_by_packaging_as_str(255, only_packaging=True), "1 Big Box,\xa01 Box,\xa05 Units", ) def test_as_str_w_units(self): self.assertEqual( self.product_a.product_qty_by_packaging_as_str( 10, include_total_units=True ), "10 Units", ) self.assertEqual( self.product_a.product_qty_by_packaging_as_str( 100, include_total_units=True ), "2 Box (100 Units)", ) self.assertEqual( self.product_a.product_qty_by_packaging_as_str( 250, include_total_units=True ), "1 Big Box,\xa01 Box (250 Units)", ) self.assertEqual( self.product_a.product_qty_by_packaging_as_str( 255, include_total_units=True ), "1 Big Box,\xa01 Box,\xa05 Units (255 Units)", ) # only_packaging has no impact if we get not only units self.assertEqual( self.product_a.product_qty_by_packaging_as_str( 255, include_total_units=True, only_packaging=True ), "1 Big Box,\xa01 Box,\xa05 Units (255 Units)", ) def test_as_str_custom_name(self): self.assertEqual( self.product_a.with_context( _qty_by_packaging_as_str=lambda pkg, qty: f"{pkg.name} {qty} FOO" ).product_qty_by_packaging_as_str(250), "Big Box 1 FOO,\xa0Box 1 FOO", )
37.061538
2,409
1,327
py
PYTHON
15.0
# Copyright 2020 Camptocamp SA # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl) from odoo.tests import TransactionCase class TestCommon(TransactionCase): at_install = False post_install = True maxDiff = None @classmethod def setUpClass(cls): super().setUpClass() cls.env = cls.env(context=dict(cls.env.context, tracking_disable=True)) cls.uom_unit = cls.env.ref("uom.product_uom_unit") cls.product_a = cls.env["product.product"].create( { "name": "Product A", "uom_id": cls.uom_unit.id, "uom_po_id": cls.uom_unit.id, } ) cls.pkg_box = cls.env["product.packaging"].create( {"name": "Box", "product_id": cls.product_a.id, "qty": 50, "barcode": "BOX"} ) cls.pkg_big_box = cls.env["product.packaging"].create( { "name": "Big Box", "product_id": cls.product_a.id, "qty": 200, "barcode": "BIGBOX", } ) cls.pkg_pallet = cls.env["product.packaging"].create( { "name": "Pallet", "product_id": cls.product_a.id, "qty": 2000, "barcode": "PALLET", } )
31.595238
1,327
729
py
PYTHON
15.0
# Copyright 2021 Camptocamp SA # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl) def make_pkg_values(record, **kw): """Helper to generate test values for packaging.""" name = record.name if record._name == "uom.uom": is_unit = True barcode = None qty = record.factor elif record._name == "product.packaging": qty = record.qty is_unit = False barcode = record.barcode if record.product_id: name = record.product_id._packaging_name_getter(record) values = { "id": record.id, "name": name, "qty": qty, "barcode": barcode, "is_unit": is_unit, } values.update(kw) return values
28.038462
729
5,771
py
PYTHON
15.0
# Copyright 2020 Camptocamp SA # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl) from .common import TestCommon from .utils import make_pkg_values class TestCalc(TestCommon): def test_contained_mapping(self): self.assertEqual( self.product_a.packaging_contained_mapping, { str(self.pkg_pallet.id): [make_pkg_values(self.pkg_big_box, qty=10)], str(self.pkg_big_box.id): [make_pkg_values(self.pkg_box, qty=4)], str(self.pkg_box.id): [make_pkg_values(self.uom_unit, qty=50)], }, ) # Update pkg qty self.pkg_pallet.qty = 4000 self.assertEqual( self.product_a.packaging_contained_mapping, { str(self.pkg_pallet.id): [make_pkg_values(self.pkg_big_box, qty=20)], str(self.pkg_big_box.id): [make_pkg_values(self.pkg_box, qty=4)], str(self.pkg_box.id): [make_pkg_values(self.uom_unit, qty=50)], }, ) def test_calc_1(self): """Test easy behavior 1.""" expected = [ make_pkg_values(self.pkg_pallet, qty=1), make_pkg_values(self.pkg_big_box, qty=3), make_pkg_values(self.pkg_box, qty=1), make_pkg_values(self.uom_unit, qty=5), ] self.assertEqual(self.product_a.product_qty_by_packaging(2655), expected) def test_calc_2(self): """Test easy behavior 2.""" expected = [ make_pkg_values(self.pkg_big_box, qty=1), make_pkg_values(self.pkg_box, qty=3), ] self.assertEqual(self.product_a.product_qty_by_packaging(350), expected) def test_calc_3(self): """Test easy behavior 3.""" expected = [ make_pkg_values(self.pkg_box, qty=1), make_pkg_values(self.uom_unit, qty=30), ] self.assertEqual(self.product_a.product_qty_by_packaging(80), expected) def test_calc_6(self): """Test fractional qty is lost.""" expected = [ make_pkg_values(self.pkg_box, qty=1), ] self.assertEqual(self.product_a.product_qty_by_packaging(50.5), expected) def test_calc_filter(self): """Test packaging filter.""" expected = [ make_pkg_values(self.pkg_big_box, qty=13), make_pkg_values(self.pkg_box, qty=1), make_pkg_values(self.uom_unit, qty=5), ] self.assertEqual( self.product_a.with_context( _packaging_filter=lambda x: x != self.pkg_pallet ).product_qty_by_packaging(2655), expected, ) def test_calc_name_get(self): """Test custom name getter.""" expected = [ make_pkg_values(self.pkg_pallet, qty=1, name="FOO " + self.pkg_pallet.name), make_pkg_values( self.pkg_big_box, qty=3, name="FOO " + self.pkg_big_box.name ), make_pkg_values(self.pkg_box, qty=1, name="FOO " + self.pkg_box.name), make_pkg_values(self.uom_unit, qty=5, name=self.uom_unit.name), ] self.assertEqual( self.product_a.with_context( _packaging_name_getter=lambda x: "FOO " + x.name ).product_qty_by_packaging(2655), expected, ) def test_calc_custom_values(self): """Test custom values handler.""" expected = [ {"my_qty": 1, "foo": self.pkg_pallet.name}, {"my_qty": 3, "foo": self.pkg_big_box.name}, {"my_qty": 1, "foo": self.pkg_box.name}, {"my_qty": 5, "foo": self.uom_unit.name}, ] self.assertEqual( self.product_a.with_context( _packaging_values_handler=lambda pkg, qty_per_pkg: { "my_qty": qty_per_pkg, "foo": pkg.name, } ).product_qty_by_packaging(2655), expected, ) def test_calc_sub1(self): """Test contained packaging behavior 1.""" expected = [ make_pkg_values( self.pkg_pallet, qty=1, contained=[make_pkg_values(self.pkg_big_box, qty=10)], ), make_pkg_values( self.pkg_big_box, qty=3, contained=[make_pkg_values(self.pkg_box, qty=4)], ), make_pkg_values( self.pkg_box, qty=1, contained=[make_pkg_values(self.uom_unit, qty=50)], ), make_pkg_values(self.uom_unit, qty=5, contained=None), ] self.assertEqual( self.product_a.product_qty_by_packaging(2655, with_contained=True), expected, ) def test_calc_sub2(self): """Test contained packaging behavior 2.""" self.pkg_box.qty = 30 expected = [ make_pkg_values( self.pkg_pallet, qty=1, contained=[make_pkg_values(self.pkg_big_box, qty=10)], ), make_pkg_values( self.pkg_big_box, qty=3, contained=[ make_pkg_values(self.pkg_box, qty=6), make_pkg_values(self.uom_unit, qty=20), ], ), make_pkg_values( self.pkg_box, qty=1, contained=[make_pkg_values(self.uom_unit, qty=30)], ), make_pkg_values(self.uom_unit, qty=25, contained=None), ] self.assertEqual( self.product_a.product_qty_by_packaging(2655, with_contained=True), expected, )
35.623457
5,771
2,052
py
PYTHON
15.0
# Copyright 2021 Camptocamp SA # @author: Simone Orsi <simone.orsi@camptocamp.com> # @author: Sébastien Alix <sebastien.alix@camptocamp.com> # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl) from odoo import api, fields, models class ProductQtyByPackagingMixin(models.AbstractModel): """Allow displaying product qty by packaging.""" _name = "product.qty_by_packaging.mixin" _description = "Product Qty By Packaging (Mixin)" _qty_by_pkg__product_field_name = "product_id" _qty_by_pkg__qty_field_name = None product_qty_by_packaging_display = fields.Char( compute="_compute_product_qty_by_packaging_display", string="Qty by packaging" ) def _product_qty_by_packaging_display_depends(self): depends = [] if self._qty_by_pkg__product_field_name: depends.append(self._qty_by_pkg__product_field_name) if self._qty_by_pkg__qty_field_name: depends.append(self._qty_by_pkg__qty_field_name) return depends @api.depends_context("lang", "qty_by_pkg_total_units", "qty_by_pkg_only_packaging") @api.depends(lambda self: self._product_qty_by_packaging_display_depends()) def _compute_product_qty_by_packaging_display(self): include_total_units = self.env.context.get("qty_by_pkg_total_units", False) only_packaging = self.env.context.get("qty_by_pkg_only_packaging", False) for record in self: value = "" product = record._qty_by_packaging_get_product() if product: value = product.product_qty_by_packaging_as_str( record._qty_by_packaging_get_qty(), include_total_units=include_total_units, only_packaging=only_packaging, ) record.product_qty_by_packaging_display = value def _qty_by_packaging_get_product(self): return self[self._qty_by_pkg__product_field_name] def _qty_by_packaging_get_qty(self): return self[self._qty_by_pkg__qty_field_name]
41.857143
2,051
7,864
py
PYTHON
15.0
# Copyright 2020 Camptocamp SA # @author: Simone Orsi <simone.orsi@camptocamp.com> # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl) import unicodedata from collections import namedtuple from odoo import api, models from odoo.tools import float_compare from odoo.addons.base_sparse_field.models.fields import Serialized # Unify records as we mix up w/ UoM Packaging = namedtuple("Packaging", "id name qty barcode is_unit") NO_BREAK_SPACE_CHAR = unicodedata.lookup("NO-BREAK SPACE") class Product(models.Model): _inherit = "product.product" packaging_contained_mapping = Serialized( compute="_compute_packaging_contained_mapping", help="Technical field to store contained packaging. ", ) @api.depends_context("lang") @api.depends("packaging_ids.qty") def _compute_packaging_contained_mapping(self): for rec in self: rec.packaging_contained_mapping = rec._packaging_contained_mapping() def _packaging_contained_mapping(self): """Produce a mapping of packaging and contained packagings. Used mainly for `product_qty_by_packaging` but can be used to display info as you prefer. :returns: a dictionary in the form {pkg.id: [contained packages]} """ res = {} packaging = self._ordered_packaging() for i, pkg in enumerate(packaging): if pkg.is_unit: # skip minimal unit continue res[pkg.id] = self._product_qty_by_packaging(packaging[i + 1 :], pkg.qty) return res def product_qty_by_packaging(self, prod_qty, with_contained=False): """Calculate quantity by packaging. The minimal quantity is always represented by the UoM of the product. Limitation: fractional quantities are lost. :prod_qty: total qty to satisfy. :with_contained: include calculation of contained packagings. eg: 1 pallet contains 4 big boxes and 6 little boxes. :returns: list of dict in the form [{id: 1, qty: qty_per_package, name: package_name}] If `with_contained` is passed, each element will include the quantity of smaller packaging, like: {contained: [{id: 1, qty: 4, name: "Big box"}]} """ self.ensure_one() return self._product_qty_by_packaging( self._ordered_packaging(), prod_qty, with_contained=with_contained, ) def _ordered_packaging(self): """Prepare packaging ordered by qty and exclude empty ones. Use ctx key `_packaging_filter` to pass a function to filter packaging to be considered. Use ctx key `_packaging_name_getter` to pass a function to change the display name of the packaging. """ custom_filter = self.env.context.get("_packaging_filter", lambda x: x) name_getter = self.env.context.get( "_packaging_name_getter", self._packaging_name_getter ) packagings = sorted( ( Packaging(x.id, name_getter(x), x.qty, x.barcode, False) for x in self.packaging_ids.filtered(custom_filter) # Exclude the ones w/ zero qty as they are useless for the math if x.qty ), reverse=True, key=lambda x: x.qty, ) # Add minimal unit packagings.append( # NOTE: the ID here could clash w/ one of the packaging's. # If you create a mapping based on IDs, keep this in mind. # You can use `is_unit` to check this. Packaging(self.uom_id.id, self.uom_id.name, self.uom_id.factor, None, True) ) return packagings def _packaging_name_getter(self, packaging): return packaging.name def _product_qty_by_packaging(self, pkg_by_qty, qty, with_contained=False): """Produce a list of dictionaries of packaging info.""" # TODO: refactor to handle fractional quantities (eg: 0.5 Kg) res = [] prepare_values = self.env.context.get( "_packaging_values_handler", self._prepare_qty_by_packaging_values ) for pkg in pkg_by_qty: qty_per_pkg, qty = self._qty_by_pkg(pkg.qty, qty) if qty_per_pkg: value = prepare_values(pkg, qty_per_pkg) if with_contained: contained = None if not pkg.is_unit: mapping = self.packaging_contained_mapping # integer keys are serialized as strings :/ contained = mapping.get(str(pkg.id)) value["contained"] = contained res.append(value) if not qty: break return res def _qty_by_pkg(self, pkg_qty, qty): """Calculate qty needed for given package qty.""" qty_per_pkg = 0 while ( float_compare(qty - pkg_qty, 0.0, precision_digits=self.uom_id.rounding) >= 0.0 ): qty -= pkg_qty qty_per_pkg += 1 return qty_per_pkg, qty def _prepare_qty_by_packaging_values(self, packaging, qty_per_pkg): return { "id": packaging.id, "qty": qty_per_pkg, "name": packaging.name, "is_unit": packaging.is_unit, "barcode": packaging.barcode, } def product_qty_by_packaging_as_str( self, prod_qty, include_total_units=False, only_packaging=False ): """Return a string representing the qty of each packaging. :param prod_qty: the qty of current product to translate to pkg qty :param include_total_units: includes total qty required initially :param only_packaging: exclude units if you have only units. IOW: if the qty does not match any packaging and this flag is true you'll get an empty string instead of `N units`. """ self.ensure_one() if not prod_qty: return "" qty_by_packaging = self.product_qty_by_packaging(prod_qty) if not qty_by_packaging: return "" # Exclude unit qty and reuse it later unit_qty = None has_only_units = True _qty_by_packaging = [] for pkg_qty in qty_by_packaging: if pkg_qty["is_unit"]: unit_qty = pkg_qty["qty"] continue has_only_units = False _qty_by_packaging.append(pkg_qty) # Browse them all at once records = self.env["product.packaging"].browse( [x["id"] for x in _qty_by_packaging] ) _qty_by_packaging_as_str = self.env.context.get( "_qty_by_packaging_as_str", self._qty_by_packaging_as_str ) # Collect all strings representations as_string = [] for record, info in zip(records, _qty_by_packaging): bit = _qty_by_packaging_as_str(record, info["qty"]) if bit: as_string.append(bit) # Restore unit information if any. include_units = (has_only_units and not only_packaging) or not has_only_units if unit_qty and include_units: as_string.append(f"{unit_qty} {self.uom_id.name}") # We want to avoid line break here as this string # can be used by reports res = f",{NO_BREAK_SPACE_CHAR}".join(as_string) if include_total_units and not has_only_units: res += " " + self._qty_by_packaging_total_units(prod_qty) return res def _qty_by_packaging_as_str(self, packaging, qty): return f"{qty} {packaging.name}" def _qty_by_packaging_total_units(self, prod_qty): return f"({prod_qty} {self.uom_id.name})"
36.920188
7,864
743
py
PYTHON
15.0
# Copyright 2018 Tecnativa - Sergio Teruel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Stock Secondary Unit", "summary": "Get product quantities in a secondary unit", "version": "15.0.1.0.0", "development_status": "Production/Stable", "category": "stock", "website": "https://github.com/OCA/stock-logistics-warehouse", "author": "Tecnativa, Odoo Community Association (OCA)", "license": "AGPL-3", "application": False, "installable": True, "depends": ["stock", "product_secondary_unit"], "data": [ "views/product_views.xml", "views/stock_move_views.xml", "views/stock_picking_views.xml", "report/report_deliveryslip.xml", ], }
35.380952
743
10,073
py
PYTHON
15.0
# Copyright 2018 Tecnativa - Sergio Teruel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo.tests import Form, TransactionCase, tagged @tagged("-at_install", "post_install") class TestProductSecondaryUnit(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() # Active multiple units of measure security group for user cls.env.user.groups_id = [(4, cls.env.ref("uom.group_uom").id)] cls.StockPicking = cls.env["stock.picking"] cls.warehouse = cls.env.ref("stock.warehouse0") cls.location_supplier = cls.env.ref("stock.stock_location_suppliers") cls.location_stock = cls.env.ref("stock.stock_location_stock") cls.picking_type_in = cls.env.ref("stock.picking_type_in") cls.picking_type_out = cls.env.ref("stock.picking_type_out") cls.picking_type_out.show_operations = True cls.product_uom_kg = cls.env.ref("uom.product_uom_kgm") cls.product_uom_ton = cls.env.ref("uom.product_uom_ton") cls.product_uom_unit = cls.env.ref("uom.product_uom_unit") ProductAttribute = cls.env["product.attribute"] ProductAttributeValue = cls.env["product.attribute.value"] cls.attribute_color = ProductAttribute.create({"name": "test_color"}) cls.attribute_value_white = ProductAttributeValue.create( {"name": "test_white", "attribute_id": cls.attribute_color.id} ) cls.attribute_value_black = ProductAttributeValue.create( {"name": "test_black", "attribute_id": cls.attribute_color.id} ) cls.product_template = cls.env["product.template"].create( { "name": "test", "uom_id": cls.product_uom_kg.id, "uom_po_id": cls.product_uom_kg.id, "type": "product", "secondary_uom_ids": [ ( 0, 0, { "code": "A", "name": "unit-500", "uom_id": cls.product_uom_unit.id, "factor": 0.5, }, ), ( 0, 0, { "code": "B", "name": "unit-900", "uom_id": cls.product_uom_unit.id, "factor": 0.9, }, ), ( 0, 0, { "code": "C", "name": "box 10", "uom_id": cls.product_uom_unit.id, "factor": 10, }, ), ], "attribute_line_ids": [ ( 0, 0, { "attribute_id": cls.attribute_color.id, "value_ids": [ (4, cls.attribute_value_white.id), (4, cls.attribute_value_black.id), ], }, ) ], } ) secondary_unit = cls.env["product.secondary.unit"].search( [("product_tmpl_id", "=", cls.product_template.id)], limit=1 ) cls.product_template.write({"stock_secondary_uom_id": secondary_unit.id}) StockQuant = cls.env["stock.quant"] cls.quant_white = StockQuant.create( { "product_id": cls.product_template.product_variant_ids[0].id, "location_id": cls.warehouse.lot_stock_id.id, "quantity": 10.0, } ) cls.quant_black = StockQuant.create( { "product_id": cls.product_template.product_variant_ids[1].id, "location_id": cls.warehouse.lot_stock_id.id, "quantity": 10.0, } ) def test_01_stock_secondary_unit_template(self): self.assertEqual(self.product_template.secondary_unit_qty_available, 40.0) def test_02_stock_secondary_unit_variant(self): for variant in self.product_template.product_variant_ids.filtered( "product_template_attribute_value_ids" ): self.assertEqual(variant.secondary_unit_qty_available, 20) def test_03_stock_picking_secondary_unit(self): StockPicking = self.env["stock.picking"] product1 = self.product_template.product_variant_ids[0] move_vals = { "product_id": product1.id, "name": product1.display_name, "secondary_uom_id": product1.secondary_uom_ids[0].id, "product_uom": product1.uom_id.id, "product_uom_qty": 10.0, "location_id": self.location_supplier.id, "location_dest_id": self.location_stock.id, } do_vals = { "location_id": self.location_supplier.id, "location_dest_id": self.location_stock.id, "picking_type_id": self.picking_type_in.id, "move_ids_without_package": [ (0, None, move_vals), (0, None, move_vals), ], # 2 moves } delivery_order = StockPicking.create(do_vals) delivery_order.action_confirm() # Move is merged into 1 line for both stock.move and stock.move.line self.assertEqual(len(delivery_order.move_lines), 1) self.assertEqual(len(delivery_order.move_line_ids), 1) # Qty merged to 20, and secondary unit qty is 40line uom_qty = sum(delivery_order.move_lines.mapped("product_uom_qty")) secondary_uom_qty = sum( delivery_order.move_line_ids.mapped("secondary_uom_qty") ) self.assertEqual(uom_qty, 20.0) self.assertEqual(secondary_uom_qty, 40.0) def test_picking_secondary_unit(self): product = self.product_template.product_variant_ids[0] with Form( self.StockPicking.with_context( planned_picking=True, default_picking_type_id=self.picking_type_out.id, ) ) as picking_form: with picking_form.move_ids_without_package.new() as move: move.product_id = product move.secondary_uom_qty = 1 move.secondary_uom_id = product.secondary_uom_ids[0] self.assertEqual(move.product_uom_qty, 0.5) move.secondary_uom_qty = 2 self.assertEqual(move.product_uom_qty, 1) move.secondary_uom_id = product.secondary_uom_ids[1] self.assertEqual(move.product_uom_qty, 1.8) move.product_uom_qty = 5 self.assertAlmostEqual(move.secondary_uom_qty, 5.56, 2) # Change uom from stock move line move.secondary_uom_qty = 1 move.secondary_uom_id = product.secondary_uom_ids[2] self.assertEqual(move.product_uom_qty, 10) move.product_uom = self.product_uom_ton self.assertAlmostEqual(move.secondary_uom_qty, 1000, 2) picking = picking_form.save() picking.action_confirm() with Form(picking) as picking_form: # Test detail operations with picking_form.move_line_ids_without_package.new() as move: move.product_id = product move.secondary_uom_qty = 1 move.secondary_uom_id = product.secondary_uom_ids[0] self.assertEqual(move.qty_done, 0.5) move.secondary_uom_qty = 2 self.assertEqual(move.qty_done, 1) move.secondary_uom_id = product.secondary_uom_ids[1] self.assertEqual(move.qty_done, 1.8) move.qty_done = 5 self.assertAlmostEqual(move.secondary_uom_qty, 5.56, 2) def test_secondary_unit_merge_move_diff_uom(self): product = self.product_template.product_variant_ids[0] with Form( self.StockPicking.with_context( planned_picking=True, default_picking_type_id=self.picking_type_out.id, ) ) as picking_form: with picking_form.move_ids_without_package.new() as move: move.product_id = product move.secondary_uom_qty = 1 move.secondary_uom_id = product.secondary_uom_ids[0] with picking_form.move_ids_without_package.new() as move: move.product_id = product move.secondary_uom_qty = 1 move.secondary_uom_id = product.secondary_uom_ids[1] picking = picking_form.save() picking.action_confirm() self.assertEqual(len(picking.move_lines), 2) def test_secondary_unit_merge_move_same_uom(self): product = self.product_template.product_variant_ids[0] with Form( self.StockPicking.with_context( planned_picking=True, default_picking_type_id=self.picking_type_out.id, ) ) as picking_form: with picking_form.move_ids_without_package.new() as move: move.product_id = product move.secondary_uom_qty = 1 move.secondary_uom_id = product.secondary_uom_ids[0] with picking_form.move_ids_without_package.new() as move: move.product_id = product move.secondary_uom_qty = 1 move.secondary_uom_id = product.secondary_uom_ids[0] picking = picking_form.save() picking.action_confirm() self.assertEqual(len(picking.move_lines), 1) self.assertEqual(picking.move_lines.secondary_uom_qty, 2)
43.795652
10,073
2,437
py
PYTHON
15.0
# Copyright 2018 Tecnativa - Sergio Teruel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import api, fields, models from odoo.tools.float_utils import float_round class StockMove(models.Model): _inherit = ["stock.move", "product.secondary.unit.mixin"] _name = "stock.move" _secondary_unit_fields = { "qty_field": "product_uom_qty", "uom_field": "product_uom", } product_uom_qty = fields.Float( store=True, readonly=False, compute="_compute_product_uom_qty", copy=True ) @api.depends("secondary_uom_qty", "secondary_uom_id") def _compute_product_uom_qty(self): self._compute_helper_target_field_qty() @api.onchange("product_uom") def onchange_product_uom_for_secondary(self): self._onchange_helper_product_uom_for_secondary() def _merge_moves_fields(self): res = super()._merge_moves_fields() res["secondary_uom_qty"] = sum(self.mapped("secondary_uom_qty")) return res @api.model def _prepare_merge_moves_distinct_fields(self): """Don't merge moves with distinct secondary units""" distinct_fields = super()._prepare_merge_moves_distinct_fields() distinct_fields += ["secondary_uom_id"] return distinct_fields class StockMoveLine(models.Model): _inherit = ["stock.move.line", "product.secondary.unit.mixin"] _name = "stock.move.line" _secondary_unit_fields = {"qty_field": "qty_done", "uom_field": "product_uom_id"} qty_done = fields.Float(store=True, readonly=False, compute="_compute_qty_done") @api.model def create(self, vals): move = self.env["stock.move"].browse(vals.get("move_id", False)) if move.secondary_uom_id: uom = self.env["uom.uom"].browse(vals["product_uom_id"]) factor = move.secondary_uom_id.factor * uom.factor move_line_qty = vals.get("product_uom_qty", vals.get("qty_done", 0.0)) qty = float_round( move_line_qty / (factor or 1.0), precision_rounding=move.secondary_uom_id.uom_id.rounding, ) vals.update( {"secondary_uom_qty": qty, "secondary_uom_id": move.secondary_uom_id.id} ) return super().create(vals) @api.depends("secondary_uom_id", "secondary_uom_qty") def _compute_qty_done(self): self._compute_helper_target_field_qty()
37.492308
2,437
1,689
py
PYTHON
15.0
# Copyright 2018 Tecnativa - Sergio Teruel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import api, fields, models from odoo.tools.float_utils import float_round class StockProductSecondaryUnit(models.AbstractModel): _name = "stock.product.secondary.unit" _description = "Stock Product Secondary Unit" secondary_unit_qty_available = fields.Float( string="Quantity On Hand (2Unit)", compute="_compute_secondary_unit_qty_available", digits="Product Unit of Measure", ) @api.depends("stock_secondary_uom_id") def _compute_secondary_unit_qty_available(self): for product in self: if not product.stock_secondary_uom_id: product.secondary_unit_qty_available = 0.0 else: qty = product.qty_available / ( product.stock_secondary_uom_id.factor or 1.0 ) product.secondary_unit_qty_available = float_round( qty, precision_rounding=product.uom_id.rounding ) class ProductTemplate(models.Model): _inherit = ["product.template", "stock.product.secondary.unit"] _name = "product.template" stock_secondary_uom_id = fields.Many2one( comodel_name="product.secondary.unit", string="Second unit for inventory" ) class ProductProduct(models.Model): _inherit = ["product.product", "stock.product.secondary.unit"] _name = "product.product" stock_secondary_uom_id = fields.Many2one( comodel_name="product.secondary.unit", string="Second unit for inventory", related="product_tmpl_id.stock_secondary_uom_id", )
35.1875
1,689
799
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). { "name": "Stock Demand Estimate Matrix", "summary": "Allows to create demand estimates.", "version": "15.0.1.2.0", "author": "ForgeFlow, Odoo Community Association (OCA)", "development_status": "Production/Stable", "website": "https://github.com/OCA/stock-logistics-warehouse", "category": "Warehouse", "depends": ["stock_demand_estimate", "web_widget_x2many_2d_matrix", "date_range"], "data": [ "security/ir.model.access.csv", "views/stock_demand_estimate_view.xml", "views/date_range.xml", "wizards/stock_demand_estimate_wizard_view.xml", ], "license": "AGPL-3", "installable": True, }
39.95
799