Added 'get_reference_target' function
authorThierry Florac <thierry.florac@onf.fr>
Tue, 12 Sep 2017 16:40:17 +0200
changeset 16 84b57eb4db8c
parent 15 a245b7406e2c
child 17 7657bccb1bdb
Added 'get_reference_target' function
src/pyams_sequence/utility.py
--- a/src/pyams_sequence/utility.py	Mon Sep 11 15:08:12 2017 +0200
+++ b/src/pyams_sequence/utility.py	Tue Sep 12 16:40:17 2017 +0200
@@ -16,6 +16,7 @@
 # import standard library
 
 # import interfaces
+from hypatia.interfaces import ICatalog
 from pyams_i18n.interfaces import II18n
 from pyams_sequence.interfaces import ISequentialIntIds, ISequentialIdTarget, ISequentialIdInfo
 
@@ -29,6 +30,9 @@
 from zope.lifecycleevent.interfaces import IObjectAddedEvent, IObjectRemovedEvent
 
 # import packages
+from hypatia.catalog import CatalogQuery
+from hypatia.query import Eq, Any
+from pyams_catalog.query import CatalogResultSet
 from pyams_utils.registry import query_utility, get_utility
 from pyramid.events import subscriber
 from zope.interface import implementer, Invalid
@@ -80,6 +84,28 @@
             return content
 
 
+def get_reference_target(reference, state=None):
+    """Get target of given reference OID"""
+    catalog = get_utility(ICatalog)
+    params = Eq(catalog['oid'], reference)
+    if handle_workflow:
+        if state:
+            if not isinstance(state, (list, tuple)):
+                state = (state,)
+            params &= Any(catalog['workflow_state'], state)
+            results = list(CatalogResultSet(CatalogQuery(catalog).query(params)))
+            if results:
+                return results[0]
+        else:
+            results = list(map(get_last_version, CatalogResultSet(CatalogQuery(catalog).query(params))))
+            if results:
+                return results[0]
+    else:
+        results = list(CatalogResultSet(CatalogQuery(catalog).query(params)))
+        if results:
+            return results[0]
+
+
 @implementer(ISequentialIntIds)
 class SequentialIntIds(IntIds):
     """Sequential IntIds utility"""