2 import oils.event, oils.const
5 ''' Collection of general purpose org_unit utility functions '''
13 if not OrgUtil._org_tree:
14 OrgUtil.fetch_org_tree()
18 ''' Returns the whole org_unit tree '''
21 return OrgUtil._org_tree
23 tree = osrf.ses.ClientSession.atomic_request(
24 oils.const.OILS_APP_ACTOR,
25 'open-ils.actor.org_tree.retrieve')
27 oils.event.Event.parse_and_raise(tree)
28 OrgUtil._org_tree = tree
29 OrgUtil.flatten_org_tree(tree)
33 def flatten_org_tree(node):
34 ''' Creates links from an ID-based hash to the org units in the org tree '''
36 node = OrgUtil._org_tree
37 OrgUtil._flat_org_tree[node.id()] = node
38 for child in node.children():
39 OrgUtil.flatten_org_tree(child)
42 def get_org_unit(org_id):
43 OrgUtil._verify_tree()
44 if isinstance(org_id, osrf.net_obj.NetworkObject):
46 return OrgUtil._flat_org_tree[org_id]
50 def fetch_org_types():
51 ''' Returns the list of org_unit_type objects '''
53 if OrgUtil._org_types:
54 return OrgUtil._org_types
56 types = osrf.ses.ClientSession.atomic_request(
57 oils.const.OILS_APP_ACTOR, 'open-ils.actor.org_types.retrieve')
59 oils.event.Event.parse_and_raise(types)
60 OrgUtil._org_types = types
65 def get_org_type(org_unit):
66 ''' Given an org_unit, this returns the org_unit_type object it's linked to '''
67 types = OrgUtil.fetch_org_types()
68 return [t for t in types if t.id() == org_unit.ou_type()][0]
72 def get_related_tree(org_unit):
73 ''' Returns a cloned tree of orgs including all ancestors and
74 descendants of the provided org '''
76 OrgUtil._verify_tree()
77 org = org_unit = OrgUtil.get_org_unit(org_unit.id()).shallow_clone()
78 while org.parent_ou():
79 parent = org.parent_ou()
80 if not isinstance(parent, osrf.net_obj.NetworkObject):
81 parent = OrgUtil._flat_org_tree[parent]
82 parent = parent.shallow_clone()
83 parent.children([org])
88 node = node.shallow_clone()
89 children = node.children()
92 for child in children:
93 node.children().append(trim_org(child))
100 def get_union_tree(org_list):
101 ''' Returns the smallest org tree which encompases all of the orgs in org_list '''
102 main_tree = OrgUtil.get_related_tree(OrgUtil.get_org_unit(org_list.pop(0)))
104 node = OrgUtil.get_related_tree(OrgUtil.get_org_unit(org))
105 main_node = main_tree
107 while node.id() == main_node.id():
108 node = node.children()[0]
109 main_node = main_node.children()[0]
112 OrgUtil.get_org_unit(main_node.parent_ou()).children().append(node)
117 def get_related_list(org_unit):
118 ''' Returns a flat list of related org_units '''
119 OrgUtil._verify_tree()
120 tree = OrgUtil.get_related_tree(org_unit)
124 for child in node.children():
130 def debug_org(org_unit, indent=0):
131 ''' Simple function to print the tree of orgs provided '''
133 for i in range(indent):
134 sys.stdout.write('-')
135 print org_unit.shortname()
137 for child in org_unit.children():
138 OrgUtil.debug_org(child, indent)