velocity-python 0.5.1__py3-none-any.whl → 0.6.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
velocity/__init__.py CHANGED
@@ -1,4 +1,4 @@
1
- __version__ = version = "0.5.1"
1
+ __version__ = version = "0.6.0"
2
2
 
3
3
  import importlib as _importlib
4
4
 
@@ -19,6 +19,9 @@ in ``client_actions`` (``client_actions = MINE | WORKFLOW_ACTIONS``)::
19
19
  workflow-handover {to, stations?, route?} -> {ok, moved, kept}
20
20
  workflow-flow {route?, entity?} -> {flows, as_of}
21
21
  workflow-graph {docket, depth?} -> Graph
22
+ workflow-operator {route?, entity?} -> Console
23
+ workflow-operator-act {docket, position, verb, comment?, request_key}
24
+ -> {ok, replayed?}
22
25
 
23
26
  and :class:`WorkflowQueueMixin` to its queue handler (never reachable over
24
27
  HTTP): ``workflow-program`` (a program station's job), ``workflow-drain``
@@ -48,6 +51,17 @@ and ``workflow.docket.assign`` / ``workflow.docket.prioritize`` (a route
48
51
  owner, the station's lead, or ``workflow.position.assign`` for the docket's
49
52
  entity); a hand-over moves only the caller's own positions, to a receiver
50
53
  seated at their stations.
54
+
55
+ **The Operator console** (:mod:`velocity.workflow.operator`) opens for a
56
+ holder of ``workflow.operate`` (anywhere) or a route owner
57
+ (``workflow.operator``), over the routes and entities
58
+ :func:`velocity.workflow.access.operator_scope` gives; its site-wide
59
+ sections (integrations, scheduled jobs) only with ``workflow.operate``
60
+ granted site-wide. ``workflow-operator-act`` retries, skips or takes over a
61
+ problem-tray position: the viewer must see the docket and be allowed
62
+ ``workflow.problem.resolve`` (its problem owner, or ``workflow.operate`` for
63
+ its entity — recorded), and the engine's own problem action decides the rest
64
+ (skip and take-over only where the station is skippable).
51
65
  """
52
66
 
53
67
  from __future__ import annotations
@@ -207,18 +221,21 @@ class WorkflowMixin:
207
221
  def _wf_masquerading(self, principal) -> bool:
208
222
  return principal.real_user is not None
209
223
 
210
- def _wf_decider(self, context):
224
+ def _wf_decider(self, context, accept=frozenset()):
211
225
  """The viewer's ``may_view``: the site's authz decision on
212
226
  ``workflow.docket.view`` for one docket (a forbid rule hides it from
213
227
  trays and links too). A privileged permit (``view_any``) is not
214
- used here: listing is never a recorded use."""
228
+ used here: listing is never a recorded use. ``accept`` names the
229
+ audited rules a listing may still show (never recorded here): the
230
+ Operator console lists its problem dockets under
231
+ ``workflow.operator_view``."""
215
232
  wf = _workflow()
216
233
 
217
234
  def decide(docket, relations):
218
235
  decision = authz.decide(
219
236
  self, wf.access.VIEW, wf.access.resource(docket, relations), context
220
237
  )
221
- return decision.allowed and not decision.audit
238
+ return decision.allowed and (not decision.audit or decision.rule in accept)
222
239
 
223
240
  return decide
224
241
 
@@ -564,7 +581,7 @@ class WorkflowMixin:
564
581
  decision = authz.decide(self, wf.access.FLOW, resource, context)
565
582
  if not decision.allowed or decision.audit:
566
583
  return None
567
- scope = wf.access.flow_scope(seats, principal, route)
584
+ scope = wf.access.flow_scope(seats, principal, route, tx=tx)
568
585
  if entity is not None:
569
586
  scope = scope.narrowed(entity)
570
587
  if scope.empty:
@@ -790,6 +807,211 @@ class WorkflowMixin:
790
807
 
791
808
  self._wf_guarded(tx, context, work)
792
809
 
810
+ # ── the Operator console ───────────────────────────────────────────────
811
+
812
+ def _wf_can_resolve(self, tx, context, principal, seats):
813
+ """Whether ``workflow.problem.resolve`` would be allowed on a
814
+ problem position (display only: never recorded; nothing under
815
+ masquerade)."""
816
+ wf = _workflow()
817
+ masquerading = self._wf_masquerading(principal)
818
+
819
+ def can_resolve(docket, route, position, verb):
820
+ if masquerading:
821
+ return False
822
+ relations = wf.access.problem_relations(tx, docket, route, seats, position)
823
+ if not relations:
824
+ return False
825
+ decision = authz.decide(
826
+ self,
827
+ wf.access.RESOLVE,
828
+ wf.access.resource(docket, relations),
829
+ context,
830
+ )
831
+ if not decision.allowed:
832
+ return False
833
+ if verb == "take_over":
834
+ return authz.decide(
835
+ self,
836
+ wf.access.TAKE_OVER,
837
+ wf.access.resource(docket, ()),
838
+ context,
839
+ ).allowed
840
+ return True
841
+
842
+ return can_resolve
843
+
844
+ def OnActionWorkflowOperator(self, tx, context):
845
+ wf = _workflow()
846
+ payload = context.payload() or {}
847
+ principal = self._wf_principal(context)
848
+ seats = self._wf_seats(tx, context, principal)
849
+
850
+ def work():
851
+ entity = self._wf_entity(payload, seats)
852
+ truncated = False
853
+ named = payload.get("route") is not None
854
+ if named:
855
+ candidates = [self._wf_route(tx, payload.get("route"), entity, seats)]
856
+ else:
857
+ codes, truncated = wf.operator.route_codes(tx, seats, principal)
858
+ candidates = []
859
+ for code in codes:
860
+ try:
861
+ candidates.append(
862
+ wf.views.route_for(tx, code, entity=entity, seats=seats)
863
+ )
864
+ except wf.WorkflowError:
865
+ continue
866
+ self._wf_require_seat(
867
+ tx,
868
+ context,
869
+ wf.access.CONSOLE,
870
+ wf.access.console_resource(
871
+ wf.access.console_relations(seats, candidates)
872
+ ),
873
+ )
874
+ scopes = {}
875
+ for route in candidates:
876
+ scope = wf.access.operator_scope(seats, principal, route, tx=tx)
877
+ if entity is not None:
878
+ scope = scope.narrowed(entity)
879
+ if not scope.empty:
880
+ scopes[route.code] = scope
881
+ if named and not scopes:
882
+ # a route this viewer may not operate: refused like one that
883
+ # does not exist
884
+ raise AccessError(authz.REFUSED)
885
+ viewer = wf.contract.Viewer(
886
+ seats=seats,
887
+ principal=principal,
888
+ view_decider=self._wf_decider(
889
+ context,
890
+ accept=frozenset({wf.access.OPERATOR_VIEW_RULE}),
891
+ ),
892
+ )
893
+ body = wf.operator.console(
894
+ tx,
895
+ viewer,
896
+ [r for r in candidates if r.code in scopes],
897
+ scopes,
898
+ site=wf.access.site_wide(principal, wf.access.OPERATE),
899
+ can_resolve=self._wf_can_resolve(tx, context, principal, seats),
900
+ )
901
+ if truncated:
902
+ body["truncated"] = True
903
+ context.response().set_body(body)
904
+
905
+ self._wf_guarded(tx, context, work)
906
+
907
+ def OnActionWorkflowOperatorAct(self, tx, context):
908
+ wf = _workflow()
909
+ payload = context.payload() or {}
910
+ principal = self._wf_principal(context)
911
+ seats = self._wf_seats(tx, context, principal)
912
+
913
+ def work():
914
+ verb = payload.get("verb")
915
+ if verb not in wf.engine.PROBLEM_VERBS:
916
+ raise _Refusal(
917
+ BAD_REQUEST,
918
+ [
919
+ {
920
+ "code": "verb",
921
+ "text": "verb must be retry, skip or take_over.",
922
+ }
923
+ ],
924
+ )
925
+ docket, route = self._wf_docket(tx, payload)
926
+ try:
927
+ position = wf.engine._position(tx, payload.get("position"))
928
+ except wf.WorkflowError:
929
+ raise AccessError(authz.REFUSED) from None
930
+ if position["docket_id"] != docket["sys_id"]:
931
+ raise AccessError(authz.REFUSED)
932
+ request_key = payload.get("request_key")
933
+ if isinstance(request_key, str) and request_key.strip():
934
+ mark = wf.engine.acted_mark(
935
+ tx, docket["sys_id"], wf.engine.Actor.person(seats), request_key
936
+ )
937
+ if mark is not None:
938
+ # this person's own request again: the first answer
939
+ # only if it was this very action (the position has
940
+ # usually left the problem tray since)
941
+ if (
942
+ mark.get("action") != verb
943
+ or mark.get("position_id") != position["sys_id"]
944
+ ):
945
+ raise _Refusal(
946
+ CONFLICT,
947
+ [
948
+ {
949
+ "code": "request_key",
950
+ "text": "That request key was used for "
951
+ "another action.",
952
+ }
953
+ ],
954
+ )
955
+ # nothing under masquerade, and only for someone who may
956
+ # still see the docket or operate
957
+ if self._wf_masquerading(principal):
958
+ raise AccessError(authz.REFUSED)
959
+ seen = authz.decide(
960
+ self,
961
+ wf.access.VIEW,
962
+ wf.access.resource(
963
+ docket,
964
+ wf.access.view_relations(tx, docket, route, seats),
965
+ ),
966
+ context,
967
+ ).allowed
968
+ if not seen and not principal.holds_anywhere(wf.access.OPERATE):
969
+ raise AccessError(authz.REFUSED)
970
+ context.response().set_body({"ok": True, "replayed": True})
971
+ return
972
+ relations = wf.access.view_relations(tx, docket, route, seats)
973
+ self._wf_require(tx, context, wf.access.VIEW, docket, relations)
974
+ decision = self._wf_require(
975
+ tx,
976
+ context,
977
+ wf.access.RESOLVE,
978
+ docket,
979
+ wf.access.problem_relations(tx, docket, route, seats, position),
980
+ )
981
+ if verb == "take_over":
982
+ # the work taken over is then theirs to do (workflow.use for
983
+ # the docket's entity; a site rule may refuse it)
984
+ self._wf_require(tx, context, wf.access.TAKE_OVER, docket, ())
985
+ request_key = self._wf_request_key(payload)
986
+ comment = payload.get("comment")
987
+ if comment is not None and not isinstance(comment, str):
988
+ raise _Refusal(
989
+ BAD_REQUEST, [{"code": "comment", "text": "comment must be text."}]
990
+ )
991
+ actor = wf.engine.Actor.person(
992
+ seats,
993
+ operator=decision.rule == wf.access.OPERATOR_RULE,
994
+ allows=self._wf_allows(tx, context),
995
+ )
996
+ result = wf.engine.resolve_problem(
997
+ tx,
998
+ docket["sys_id"],
999
+ position["sys_id"],
1000
+ verb,
1001
+ actor,
1002
+ request_key,
1003
+ comment=comment,
1004
+ )
1005
+ if not result.ok:
1006
+ raise _Refusal(_reasons_status(result.reasons), result.reasons)
1007
+ self._wf_after_change(tx, context, docket["sys_id"])
1008
+ body = {"ok": True}
1009
+ if result.replayed:
1010
+ body["replayed"] = True
1011
+ context.response().set_body(body)
1012
+
1013
+ self._wf_guarded(tx, context, work)
1014
+
793
1015
  # ── notices ────────────────────────────────────────────────────────────
794
1016
 
795
1017
  def OnActionWorkflowNotices(self, tx, context):
velocity/aws/ops.py CHANGED
@@ -379,6 +379,14 @@ def _overview(tx, hours, now):
379
379
  }
380
380
 
381
381
 
382
+ def schedules(tx, *, now=None):
383
+ """Every schedule in ``sys_task_triggers`` as :func:`shape_schedule`
384
+ (``health``: ok / never / overdue / disabled), by name; ``[]`` when the
385
+ table does not exist. What the dashboard's schedule section and the
386
+ workflow Operator console's scheduled jobs both read."""
387
+ return _schedules(tx, now or _utcnow())
388
+
389
+
382
390
  def _schedules(tx, now):
383
391
  if not _has(tx, TRIGGERS_TABLE):
384
392
  return []
@@ -16,8 +16,10 @@ An application supplies, in code: :func:`register_subject`,
16
16
  :func:`register_program`, :func:`register_sheet`, :func:`register_seats`
17
17
  (and optionally :func:`register_recipients`, :func:`register_contact`,
18
18
  :func:`register_person_label`, :func:`register_station_people`,
19
- :func:`register_time_zone`). :mod:`.views` draws the Station Board, the
20
- Flow map and the Dependency view. Nothing here names a business. See
19
+ :func:`register_time_zone`, :func:`register_heartbeats`,
20
+ :func:`register_role_label`). :mod:`.views` draws the Station Board, the
21
+ Flow map and the Dependency view; :mod:`.operator` the Operator console.
22
+ Nothing here names a business. See
21
23
  docs/workflow.md.
22
24
  """
23
25
 
@@ -28,6 +30,7 @@ from . import (
28
30
  engine,
29
31
  hooks,
30
32
  notices,
33
+ operator,
31
34
  outbox,
32
35
  points,
33
36
  schema,
@@ -69,6 +72,7 @@ from .engine import ( # noqa: F401
69
72
  place_hold,
70
73
  prioritize,
71
74
  release_hold,
75
+ resolve_problem,
72
76
  resume_wait,
73
77
  run_program,
74
78
  run_route_tests,
@@ -90,10 +94,12 @@ from .hooks import ( # noqa: F401
90
94
  register_calendar,
91
95
  register_contact,
92
96
  register_entity_scope,
97
+ register_heartbeats,
93
98
  register_person_label,
94
99
  register_person_seats,
95
100
  register_program,
96
101
  register_recipients,
102
+ register_role_label,
97
103
  register_seats,
98
104
  register_sheet,
99
105
  register_station_people,
@@ -148,16 +154,19 @@ __all__ = [
148
154
  "register_channel",
149
155
  "register_contact",
150
156
  "register_entity_scope",
157
+ "register_heartbeats",
151
158
  "register_person_label",
152
159
  "register_person_seats",
153
160
  "register_program",
154
161
  "register_recipients",
162
+ "register_role_label",
155
163
  "register_seats",
156
164
  "register_sheet",
157
165
  "register_station_people",
158
166
  "register_subject",
159
167
  "register_time_zone",
160
168
  "release_hold",
169
+ "resolve_problem",
161
170
  "resume_wait",
162
171
  "retire",
163
172
  "route_from",
@@ -21,6 +21,10 @@ Permissions (granted by the site, :mod:`velocity.aws.permissions` or its
21
21
  .assign`` granted in (scoped by :func:`entity_scope`)
22
22
  ``workflow.flow.view`` see the Flow map of every route, for the entities one
23
23
  has seats in (aggregates only, never a docket)
24
+ ``workflow.operate`` the Operator console for every route, in the entities
25
+ it is granted for: see dockets with a problem-tray
26
+ item and Retry / Skip / Take over them (recorded);
27
+ site-wide, also integrations and scheduled jobs
24
28
  ===================== =======================================================
25
29
 
26
30
  Actions and the rules that allow them, first match wins:
@@ -47,6 +51,22 @@ Actions and the rules that allow them, first match wins:
47
51
  and ``workflow.position.assign`` for the docket's
48
52
  entity scope
49
53
  ``workflow.handover`` ``workflow.member`` (one's own positions only)
54
+ ``workflow.operator`` ``workflow.operator_console``: ``workflow
55
+ .operate`` anywhere; ``workflow.route_operator``:
56
+ ``use`` and owns a route (the console's scope is
57
+ then :func:`operator_scope`)
58
+ ``workflow.problem ``workflow.problem_owner``: ``use`` and owns the
59
+ .resolve`` position's problem tray (its role, or the route);
60
+ ``workflow.operator``: ``workflow.operate`` for
61
+ the docket's entity and an open problem-tray
62
+ position there (audited)
63
+ ``workflow.docket.view`` also ``workflow.operator_view`` (recorded;
64
+ before ``view_any``): ``workflow.operate`` for
65
+ the docket's entity and an open problem-tray
66
+ position (``in_problem_tray``). The console's
67
+ own listing accepts it without recording.
68
+ ``workflow.problem ``workflow.problem_take_over``: ``workflow.use``
69
+ .take_over`` for the docket's entity (what take-over needs)
50
70
  ========================== ==================================================
51
71
 
52
72
  A station's lead (``"route/station"`` in ``EntitySeats.oversees``) is
@@ -68,7 +88,7 @@ from velocity.aws import authz
68
88
  from . import engine
69
89
  from . import hooks
70
90
  from .hooks import Seats
71
- from .schema import MARK, NOTICE
91
+ from .schema import DOCKET, MARK, NOTICE
72
92
 
73
93
  USE = "workflow.use"
74
94
  VIEW_ANY = "workflow.view_any"
@@ -76,6 +96,7 @@ ACT_ANY = "workflow.act_any"
76
96
 
77
97
  POSITION_ASSIGN = "workflow.position.assign"
78
98
  FLOW_VIEW = "workflow.flow.view"
99
+ OPERATE = "workflow.operate"
79
100
 
80
101
  TRAY = "workflow.tray"
81
102
  NOTICES = "workflow.notices"
@@ -89,10 +110,15 @@ PRIORITIZE = "workflow.docket.prioritize"
89
110
  BOARD = "workflow.board"
90
111
  FLOW = "workflow.flow"
91
112
  HANDOVER = "workflow.handover"
113
+ CONSOLE = "workflow.operator"
114
+ RESOLVE = "workflow.problem.resolve"
115
+ # taking a problem over makes its work the viewer's: workflow.use there
116
+ TAKE_OVER = "workflow.problem.take_over"
92
117
 
93
118
  RESOURCE_TYPE = "workflow_docket"
94
119
  STATION_RESOURCE_TYPE = "workflow_station"
95
120
  ROUTE_RESOURCE_TYPE = "workflow_route"
121
+ CONSOLE_RESOURCE_TYPE = "workflow_console"
96
122
 
97
123
  OVERSEES = "oversees"
98
124
  SEATED = "seated"
@@ -102,12 +128,18 @@ WORKS = "works"
102
128
  PROBLEM_OWNER = "problem_owner"
103
129
  HOLD_OWNER = "hold_owner"
104
130
  LEADS = "leads"
131
+ # the docket has an open problem-tray position in the viewer's entities:
132
+ # a relation only holders of workflow.operate there can use
133
+ IN_PROBLEM = "in_problem_tray"
105
134
  VIEW_RELATIONS = frozenset({OVERSEES, SEATED, WORKED, NOTIFIED, LEADS})
106
135
  LEAD_RELATIONS = frozenset({OVERSEES, LEADS})
107
136
  WORK_RELATIONS = frozenset({WORKS, PROBLEM_OWNER, HOLD_OWNER})
108
137
 
109
138
  # the rules whose use means acting beyond one's seats
110
139
  OVERRIDE_RULES = frozenset({"workflow.oversee", "workflow.act_any"})
140
+ # the rule whose use resolves a problem tray beyond one's seats
141
+ OPERATOR_RULE = "workflow.operator"
142
+ OPERATOR_VIEW_RULE = "workflow.operator_view"
111
143
  VIEW_OVERRIDE_RULES = frozenset({"workflow.view_any"})
112
144
 
113
145
 
@@ -200,6 +232,16 @@ authz.permission(
200
232
  "in your entities, not the dockets themselves.",
201
233
  group="Workflow",
202
234
  )
235
+ authz.permission(
236
+ OPERATE,
237
+ label="Operate workflow",
238
+ description="See the Operator console (problem trays, program stations, "
239
+ "late waits, failed notices) for every route in your entities, and "
240
+ "retry, skip or take over problem-tray items there. Each such write is "
241
+ "recorded. Granted site-wide, also integrations and scheduled jobs.",
242
+ group="Workflow",
243
+ privileged=True,
244
+ )
203
245
  authz.permission(
204
246
  ACT_ANY,
205
247
  label="Act on any docket",
@@ -219,6 +261,16 @@ RULES = (
219
261
  {VIEW, FLAG},
220
262
  when=authz.all_of(authz.holds(USE), related(VIEW_RELATIONS)),
221
263
  ),
264
+ authz.permit(
265
+ # an operator sees the dockets in their problem trays (the flow and
266
+ # the error; sheets and documents still need the data permissions).
267
+ # Recorded like view_any; the console's listing is recorded once per
268
+ # open (workflow.operator_console).
269
+ OPERATOR_VIEW_RULE,
270
+ {VIEW},
271
+ when=authz.all_of(related({IN_PROBLEM}), authz.holds_for(OPERATE)),
272
+ audit=True,
273
+ ),
222
274
  authz.permit(
223
275
  "workflow.view_any", {VIEW, FLAG}, when=authz.holds(VIEW_ANY), audit=True
224
276
  ),
@@ -258,6 +310,32 @@ RULES = (
258
310
  {ASSIGN, PRIORITIZE},
259
311
  when=authz.all_of(authz.holds(USE), authz.holds_for(POSITION_ASSIGN)),
260
312
  ),
313
+ authz.permit(
314
+ # an operator's console (first, so an operator who also owns a route
315
+ # is recorded too): each open is a recorded use (it lists problem
316
+ # dockets the operator does not otherwise see)
317
+ "workflow.operator_console",
318
+ {CONSOLE},
319
+ when=authz.holds_anywhere(OPERATE),
320
+ audit=True,
321
+ ),
322
+ authz.permit(
323
+ "workflow.route_operator",
324
+ {CONSOLE},
325
+ when=authz.all_of(authz.holds(USE), related({OVERSEES})),
326
+ ),
327
+ authz.permit(
328
+ "workflow.problem_owner",
329
+ {RESOLVE},
330
+ when=authz.all_of(authz.holds_for(USE), related({PROBLEM_OWNER})),
331
+ ),
332
+ authz.permit(
333
+ OPERATOR_RULE,
334
+ {RESOLVE},
335
+ when=authz.all_of(related({IN_PROBLEM}), authz.holds_for(OPERATE)),
336
+ audit=True,
337
+ ),
338
+ authz.permit("workflow.problem_take_over", {TAKE_OVER}, when=authz.holds_for(USE)),
261
339
  authz.permit(
262
340
  "workflow.data_write",
263
341
  {SHEET_WRITE, HOLD_RELEASE},
@@ -286,6 +364,8 @@ FORBID_MASQUERADE = authz.forbid(
286
364
  ASSIGN,
287
365
  PRIORITIZE,
288
366
  HANDOVER,
367
+ RESOLVE,
368
+ TAKE_OVER,
289
369
  },
290
370
  when=authz.masquerading,
291
371
  )
@@ -349,6 +429,8 @@ def view_relations_many(tx, dockets, routes, seats: Seats, positions=None) -> di
349
429
  actor, route, position
350
430
  ):
351
431
  relations.add(SEATED)
432
+ if position.get("problem"):
433
+ relations.add(IN_PROBLEM)
352
434
  if docket["sys_id"] in worked:
353
435
  relations.add(WORKED)
354
436
  if docket["sys_id"] in notified:
@@ -500,20 +582,70 @@ class FlowScope:
500
582
  return FlowScope()
501
583
 
502
584
 
503
- def flow_scope(seats: Seats, principal, route) -> FlowScope:
585
+ def flow_scope(seats: Seats, principal, route, tx=None) -> FlowScope:
504
586
  """The entities a Flow map of ``route`` counts for this viewer: those in
505
587
  which they own the route or lead a station on it, and those in which
506
588
  they hold ``workflow.flow.view`` — always among their own seat entities
507
- (``*``: every entity)."""
589
+ (``*``: every entity). See :func:`_granted_scope` for a site-wide grant
590
+ denied in some entity."""
591
+ return _granted_scope(
592
+ seats,
593
+ principal,
594
+ route,
595
+ FLOW_VIEW,
596
+ lambda key: seats.oversees_part_of(route.code, route.owner_role, entity=key),
597
+ tx,
598
+ )
599
+
600
+
601
+ ENTITY_SAMPLE_LIMIT = 500
602
+
603
+
604
+ def denied_somewhere(principal, permission) -> bool:
605
+ """Whether ``permission`` is taken away in any scope."""
606
+ return any(permission in names for names in (principal.denied or {}).values())
607
+
608
+
609
+ def site_wide(principal, permission) -> bool:
610
+ """Held site-wide and taken away nowhere (a super user always)."""
611
+ if principal is None:
612
+ return False
613
+ if principal.superuser:
614
+ return True
615
+ return principal.holds(permission) and not denied_somewhere(principal, permission)
616
+
617
+
618
+ def _granted_scope(seats, principal, route, permission, owns, tx=None) -> FlowScope:
619
+ """The entities among ``seats``' entities where ``owns(key)`` or
620
+ ``permission`` is held for the entity's scope. Under ``*`` seats a
621
+ site-wide grant covers every entity only when it is denied nowhere;
622
+ otherwise (with ``tx``) the route's docket entities are listed and each
623
+ is decided on its own, and without ``tx`` nothing beyond the explicit
624
+ seat entities is covered (fail closed)."""
508
625
  every, entities = False, set()
509
626
  for key in _seat_entities(seats):
510
- owns = seats.oversees_part_of(route.code, route.owner_role, entity=key)
511
627
  if key == hooks.ALL:
512
- if owns or (principal is not None and principal.holds(FLOW_VIEW)):
628
+ if owns(key) or site_wide(principal, permission):
513
629
  every = True
630
+ elif (
631
+ principal is not None
632
+ and principal.holds_anywhere(permission)
633
+ and tx is not None
634
+ ):
635
+ for row in tx.table(DOCKET).select(
636
+ columns=["entity"],
637
+ where={"route_code": route.code},
638
+ orderby="entity",
639
+ distinct=True,
640
+ qty=ENTITY_SAMPLE_LIMIT,
641
+ ):
642
+ entity = row.get("entity")
643
+ name = None if entity is None else str(entity)
644
+ if principal.holds_in(permission, entity_scope(name)):
645
+ entities.add(name)
514
646
  continue
515
- if owns or (
516
- principal is not None and principal.holds_in(FLOW_VIEW, entity_scope(key))
647
+ if owns(key) or (
648
+ principal is not None and principal.holds_in(permission, entity_scope(key))
517
649
  ):
518
650
  entities.add(key)
519
651
  if every:
@@ -521,6 +653,61 @@ def flow_scope(seats: Seats, principal, route) -> FlowScope:
521
653
  return FlowScope(False, frozenset(entities))
522
654
 
523
655
 
656
+ def problem_relations(tx, docket, route, seats: Seats, position) -> frozenset:
657
+ """What ``seats`` are to a problem-tray ``position`` for resolving it:
658
+ ``problem_owner`` (:func:`velocity.workflow.engine.problem_owner_of`:
659
+ the tray's role, or owning the route) and ``in_problem_tray`` (an open
660
+ problem position in one of their entities, which ``workflow.operate``
661
+ for that entity turns into a right) — never across entities."""
662
+ entity = docket.get("entity")
663
+ if (
664
+ not seats.person
665
+ or not seats.in_entity(entity)
666
+ or position is None
667
+ or position.get("docket_id") != docket["sys_id"]
668
+ or not position.get("problem")
669
+ or not engine.is_open(position)
670
+ ):
671
+ return frozenset()
672
+ out = {IN_PROBLEM}
673
+ if engine.problem_owner_of(engine.Actor.person(seats), route, position):
674
+ out.add(PROBLEM_OWNER)
675
+ return frozenset(out)
676
+
677
+
678
+ def owns_route(seats: Seats, route, entity) -> bool:
679
+ """A route owner (``Seats.oversees`` or the route's ``owner_role``) in
680
+ ``entity``; a station lead is not."""
681
+ return bool(seats.person) and seats.oversees_route(
682
+ route.code, route.owner_role, entity=entity
683
+ )
684
+
685
+
686
+ def operator_scope(seats: Seats, principal, route, tx=None) -> "FlowScope":
687
+ """The entities the Operator console covers for ``route``: among the
688
+ viewer's seat entities, those where they own the route or hold
689
+ ``workflow.operate`` for the entity's scope (``*`` seats: every entity,
690
+ with the permission site-wide and denied nowhere, or owning the route;
691
+ see :func:`_granted_scope`)."""
692
+ return _granted_scope(
693
+ seats, principal, route, OPERATE, lambda key: owns_route(seats, route, key), tx
694
+ )
695
+
696
+
697
+ def console_relations(seats: Seats, routes) -> frozenset:
698
+ """``oversees`` when ``seats`` own any of ``routes`` in any of their
699
+ entities (the route owner's way into the console)."""
700
+ for route in routes:
701
+ for key in _seat_entities(seats):
702
+ if owns_route(seats, route, key):
703
+ return frozenset({OVERSEES})
704
+ return frozenset()
705
+
706
+
707
+ def console_resource(relations) -> SeatResource:
708
+ return SeatResource(CONSOLE_RESOURCE_TYPE, id="*", relations=frozenset(relations))
709
+
710
+
524
711
  def resource(docket, relations, permission=None) -> DocketResource:
525
712
  return DocketResource(
526
713
  RESOURCE_TYPE,
@@ -538,6 +725,19 @@ __all__ = [
538
725
  "ASSIGN",
539
726
  "BOARD",
540
727
  "CLAIM",
728
+ "CONSOLE",
729
+ "IN_PROBLEM",
730
+ "OPERATE",
731
+ "OPERATOR_RULE",
732
+ "OPERATOR_VIEW_RULE",
733
+ "TAKE_OVER",
734
+ "site_wide",
735
+ "RESOLVE",
736
+ "console_relations",
737
+ "console_resource",
738
+ "operator_scope",
739
+ "owns_route",
740
+ "problem_relations",
541
741
  "DocketResource",
542
742
  "FLAG",
543
743
  "FLOW",