Sep 4 - Add link relavant issues function
This commit is contained in:
+12
-2
@@ -17,6 +17,16 @@ bp = Blueprint('dashboard', __name__)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# Columns the dashboard actually reads off an issue row. The cards below need
|
||||
# counts and buckets, never a hydrated Issue — loading the full entity pulls the
|
||||
# description TEXT and three JSON photo columns for every open issue in scope,
|
||||
# on every dashboard load, and registers each one in the identity map.
|
||||
# A Row exposes the same attribute names, so the severity/handler tallies and
|
||||
# sla_status() work against these unchanged.
|
||||
_ISSUE_CARD_COLS = (Issue.id, Issue.severity, Issue.status,
|
||||
Issue.reported_at, Issue.handler_type)
|
||||
|
||||
|
||||
@bp.route('/')
|
||||
@bp.route('/dashboard')
|
||||
@login_required
|
||||
@@ -100,7 +110,7 @@ def index():
|
||||
))
|
||||
|
||||
# Single query — derive count from the list to avoid hitting the DB twice
|
||||
open_issues_all = open_issues_q.all()
|
||||
open_issues_all = open_issues_q.with_entities(*_ISSUE_CARD_COLS).all()
|
||||
open_issues = len(open_issues_all)
|
||||
severity_breakdown = {
|
||||
'critical': sum(1 for i in open_issues_all if i.severity == 'critical'),
|
||||
@@ -226,7 +236,7 @@ def index():
|
||||
elif is_customer and not customer_facility_ids:
|
||||
all_open_issues = []
|
||||
else:
|
||||
all_open_issues = sla_q.all()
|
||||
all_open_issues = sla_q.with_entities(*_ISSUE_CARD_COLS).all()
|
||||
sla_breached = sum(1 for i in all_open_issues if sla_status(i) == 'breached')
|
||||
sla_at_risk = sum(1 for i in all_open_issues if sla_status(i) == 'at_risk')
|
||||
|
||||
|
||||
@@ -254,7 +254,8 @@ def index():
|
||||
q = q.filter(Inspection.status == status_filter)
|
||||
if contract_filter.isdigit():
|
||||
_contract_fids = [
|
||||
f.id for f in Facility.query.filter_by(project_id=int(contract_filter)).all()
|
||||
fid for (fid,) in db.session.query(Facility.id)
|
||||
.filter(Facility.project_id == int(contract_filter)).all()
|
||||
]
|
||||
q = q.filter(Inspection.facility_id.in_(_contract_fids)) if _contract_fids else q.filter(False)
|
||||
if facility_filter.isdigit():
|
||||
@@ -1259,7 +1260,8 @@ def export_list_pdf():
|
||||
q = q.filter(Inspection.status == status_filter)
|
||||
if contract_filter.isdigit():
|
||||
_contract_fids = [
|
||||
f.id for f in Facility.query.filter_by(project_id=int(contract_filter)).all()
|
||||
fid for (fid,) in db.session.query(Facility.id)
|
||||
.filter(Facility.project_id == int(contract_filter)).all()
|
||||
]
|
||||
q = q.filter(Inspection.facility_id.in_(_contract_fids)) if _contract_fids else q.filter(False)
|
||||
if facility_filter.isdigit():
|
||||
|
||||
+263
-20
@@ -6,7 +6,7 @@ from flask import (Blueprint, render_template, redirect, url_for,
|
||||
flash, request, current_app, jsonify, abort, Response)
|
||||
from flask_login import login_required, current_user
|
||||
from app import db
|
||||
from app.models.issue import Issue, IssueComment, IssueFollower
|
||||
from app.models.issue import Issue, IssueComment, IssueFollower, IssueLink
|
||||
from app.models.facility import Facility, Area
|
||||
from app.models.user import User
|
||||
from app.models.notification import (
|
||||
@@ -71,6 +71,48 @@ class _SLAFilteredPage:
|
||||
return iter([1])
|
||||
|
||||
|
||||
# ── Issue read access ─────────────────────────────────────────────────────────
|
||||
# One definition of "may this person open this issue", used by the detail view,
|
||||
# by the linked-issues panel, and by the link picker's search. They must not
|
||||
# drift: the picker is what a person searches, but the panel is what actually
|
||||
# renders another issue's description, and the POST is the real boundary.
|
||||
#
|
||||
# All three are WITHIN one tenant. Cross-tenant isolation is not their job and
|
||||
# never can be — RoutingSession has already bound the session to g.tenant's
|
||||
# database, so an id from another tenant simply does not resolve here.
|
||||
|
||||
def _viewer_facility_scope(user):
|
||||
"""Facility ids this user is confined to, or None when unrestricted.
|
||||
|
||||
Returns a LIST (possibly empty) for the two scoped role groups and None for
|
||||
everyone else. Empty list and None mean opposite things — [] is "no access
|
||||
to anything", None is "no restriction" — so callers must test `is None`
|
||||
rather than truthiness (CLAUDE.md rule 57's failure mode).
|
||||
"""
|
||||
if user.is_inspector: # rule 87 — never role == 'inspector'
|
||||
return get_inspector_scope(user) or []
|
||||
if user.role == 'customer': # rule 99 — capability check, exact match
|
||||
return get_customer_scope(user) or []
|
||||
return None
|
||||
|
||||
|
||||
def _issue_in_scope(issue, scope_ids):
|
||||
"""Whether one issue falls inside an already-resolved facility scope.
|
||||
|
||||
Takes the scope rather than the user so a caller filtering a list of issues
|
||||
resolves it once instead of re-querying the assignment tables per row.
|
||||
"""
|
||||
if scope_ids is None:
|
||||
return True
|
||||
facility = issue.resolved_facility
|
||||
return facility is not None and facility.id in scope_ids
|
||||
|
||||
|
||||
def _issue_readable_by(issue, user):
|
||||
"""Single-issue convenience wrapper around the two helpers above."""
|
||||
return _issue_in_scope(issue, _viewer_facility_scope(user))
|
||||
|
||||
|
||||
def _assignee_label(user):
|
||||
"""Dropdown label for an assignee.
|
||||
|
||||
@@ -146,13 +188,14 @@ def export_list_pdf():
|
||||
date_to_filter = ''
|
||||
if contract_filter.isdigit():
|
||||
_contract_fids = [
|
||||
f.id for f in Facility.query.filter_by(project_id=int(contract_filter)).all()
|
||||
fid for (fid,) in db.session.query(Facility.id)
|
||||
.filter(Facility.project_id == int(contract_filter)).all()
|
||||
]
|
||||
q = q.filter(db.or_(
|
||||
Issue.facility_id.in_(_contract_fids),
|
||||
Area.facility_id.in_(_contract_fids),
|
||||
)) if _contract_fids else q.filter(False)
|
||||
if facility_filter:
|
||||
if facility_filter.isdigit():
|
||||
fid = int(facility_filter)
|
||||
q = q.filter(db.or_(Issue.facility_id == fid, Area.facility_id == fid))
|
||||
if reporter_filter.isdigit():
|
||||
@@ -181,7 +224,7 @@ def export_list_pdf():
|
||||
p = db.session.get(Project, int(contract_filter))
|
||||
if p:
|
||||
filter_parts.append(f'Contract: {p.name}')
|
||||
if facility_filter:
|
||||
if facility_filter.isdigit():
|
||||
f = db.session.get(Facility, int(facility_filter))
|
||||
if f:
|
||||
filter_parts.append(f'Facility: {f.name}')
|
||||
@@ -279,7 +322,8 @@ def index():
|
||||
date_to_filter = ''
|
||||
if contract_filter.isdigit():
|
||||
_contract_fids = [
|
||||
f.id for f in Facility.query.filter_by(project_id=int(contract_filter)).all()
|
||||
fid for (fid,) in db.session.query(Facility.id)
|
||||
.filter(Facility.project_id == int(contract_filter)).all()
|
||||
]
|
||||
q = q.filter(db.or_(
|
||||
Issue.facility_id.in_(_contract_fids),
|
||||
@@ -287,7 +331,7 @@ def index():
|
||||
)) if _contract_fids else q.filter(False)
|
||||
if reporter_filter.isdigit():
|
||||
q = q.filter(Issue.reported_by == int(reporter_filter))
|
||||
if facility_filter:
|
||||
if facility_filter.isdigit():
|
||||
fid = int(facility_filter)
|
||||
q = q.filter(
|
||||
db.or_(
|
||||
@@ -325,8 +369,9 @@ def index():
|
||||
# can render the following badge and inline unfollow button without an
|
||||
# additional query per row.
|
||||
followed_ids = {
|
||||
f.issue_id
|
||||
for f in IssueFollower.query.filter_by(user_id=current_user.id).all()
|
||||
iid for (iid,) in
|
||||
db.session.query(IssueFollower.issue_id)
|
||||
.filter(IssueFollower.user_id == current_user.id).all()
|
||||
}
|
||||
|
||||
# Facilities for the filter dropdown — scoped for inspectors/customers,
|
||||
@@ -398,18 +443,14 @@ def view(issue_id):
|
||||
if issue is None:
|
||||
abort(404)
|
||||
|
||||
if current_user.is_inspector:
|
||||
fids = get_inspector_scope(current_user)
|
||||
facility = issue.resolved_facility
|
||||
if not fids or not facility or facility.id not in fids:
|
||||
flash('Access denied.', 'danger')
|
||||
return redirect(url_for('issues.index'))
|
||||
# Scope gate — see _issue_readable_by(). This was two inline blocks that the
|
||||
# linked-issues panel would have had to reproduce a third time; it is now
|
||||
# one definition so the panel cannot end up more permissive than the page.
|
||||
if not _issue_readable_by(issue, current_user):
|
||||
flash('Access denied.', 'danger')
|
||||
return redirect(url_for('issues.index'))
|
||||
|
||||
if current_user.role == 'customer':
|
||||
cids = get_customer_scope(current_user) or []
|
||||
facility = issue.resolved_facility
|
||||
if not facility or facility.id not in cids:
|
||||
flash('Access denied.', 'danger')
|
||||
return redirect(url_for('issues.index'))
|
||||
if request.method == 'POST':
|
||||
# Customers may only add a comment, and only on issues they follow or reported
|
||||
can_comment = (issue.is_followed_by(current_user) or issue.reported_by == current_user.id)
|
||||
@@ -686,7 +727,209 @@ def view(issue_id):
|
||||
form=form,
|
||||
comments=comments,
|
||||
comments_open=comments_open,
|
||||
is_following=is_following)
|
||||
is_following=is_following,
|
||||
# Already filtered to links whose far end this viewer
|
||||
# may open — see _readable_links().
|
||||
issue_links=_readable_links(issue, current_user),
|
||||
link_types=IssueLink.TYPE_CHOICES,
|
||||
can_manage_links=_can_manage_links(issue, current_user))
|
||||
|
||||
|
||||
# ── Issue links ───────────────────────────────────────────────────────────────
|
||||
# Connect a duplicate to its original, or two issues about the same thing, so
|
||||
# whoever picks one up can reach the other. Links are purely navigational: they
|
||||
# never touch status, SLA, assignee or followers on either issue.
|
||||
|
||||
def _can_manage_links(issue, user):
|
||||
"""Who may add or remove a link on this issue.
|
||||
|
||||
Deliberately the SAME set as the page's `can_edit` (the Update Issue panel):
|
||||
admin / director / auditor, or the person the issue is assigned to. Keeping
|
||||
the two identical means the panel's buttons and this gate cannot disagree —
|
||||
the alternative is a second, slightly different rule that nobody remembers.
|
||||
Widening it (to project_manager, or to the reporter) is a one-line change
|
||||
here, but change `can_edit` in issues/view.html at the same time.
|
||||
"""
|
||||
return (user.role in ('admin', 'director', 'auditor')
|
||||
or issue.assigned_to == user.id)
|
||||
|
||||
|
||||
def _readable_links(issue, user):
|
||||
"""Links on this issue whose FAR END the viewer may also open.
|
||||
|
||||
A link is a pointer to another issue's id, description and facility, so an
|
||||
unfiltered panel would let a customer read an issue at a facility they have
|
||||
no assignment to simply because one of our staff linked it. The scope is
|
||||
resolved once for the whole list rather than per row.
|
||||
|
||||
Returns a list of (link, other_issue, label) ready for the template.
|
||||
"""
|
||||
scope = _viewer_facility_scope(user)
|
||||
visible = []
|
||||
for link in issue.all_links():
|
||||
other = link.other_issue(issue.id)
|
||||
if other is None or not _issue_in_scope(other, scope):
|
||||
continue
|
||||
visible.append((link, other, link.label_for(issue.id)))
|
||||
return visible
|
||||
|
||||
|
||||
@bp.route('/<int:issue_id>/links', methods=['POST'])
|
||||
@login_required
|
||||
def add_link(issue_id):
|
||||
"""Link this issue to another one."""
|
||||
issue = db.session.get(Issue, issue_id)
|
||||
if issue is None:
|
||||
abort(404)
|
||||
if not _issue_readable_by(issue, current_user):
|
||||
abort(403)
|
||||
if not _can_manage_links(issue, current_user):
|
||||
abort(403)
|
||||
|
||||
link_type = request.form.get('link_type', '')
|
||||
if link_type not in (IssueLink.TYPE_DUPLICATE, IssueLink.TYPE_RELATED):
|
||||
flash('Choose how the two issues are related.', 'warning')
|
||||
return redirect(_view_url(issue_id))
|
||||
|
||||
raw_target = (request.form.get('linked_issue_id') or '').strip().lstrip('#')
|
||||
if not raw_target.isdigit():
|
||||
flash('Enter the number of the issue to link, e.g. 412.', 'warning')
|
||||
return redirect(_view_url(issue_id))
|
||||
target_id = int(raw_target)
|
||||
|
||||
if target_id == issue.id:
|
||||
flash('An issue cannot be linked to itself.', 'warning')
|
||||
return redirect(_view_url(issue_id))
|
||||
|
||||
target = db.session.get(Issue, target_id)
|
||||
# A 404 and a 403 are the same message here on purpose: whether an issue
|
||||
# outside your scope EXISTS is not something the link box should confirm.
|
||||
if target is None or not _issue_readable_by(target, current_user):
|
||||
flash(f'Issue #{target_id} was not found.', 'warning')
|
||||
return redirect(_view_url(issue_id))
|
||||
|
||||
if IssueLink.exists_between(issue.id, target.id):
|
||||
flash(f'Issue #{issue.id} and #{target.id} are already linked.', 'info')
|
||||
return redirect(_view_url(issue_id))
|
||||
|
||||
link = IssueLink(
|
||||
issue_id = issue.id,
|
||||
linked_issue_id = target.id,
|
||||
link_type = link_type,
|
||||
created_by = current_user.id,
|
||||
)
|
||||
db.session.add(link)
|
||||
db.session.commit()
|
||||
|
||||
log_action(ACTION_UPDATE, 'Issue', issue.id, f'#{issue.id}',
|
||||
f'linked to #{target.id} as {link_type}')
|
||||
current_app.logger.info(
|
||||
'ISSUE LINK | issue_id=%s | linked_issue_id=%s | type=%s | user=%s',
|
||||
issue.id, target.id, link_type, current_user.username,
|
||||
)
|
||||
flash(f'Issue #{issue.id} is now linked to #{target.id}.', 'success')
|
||||
return redirect(_view_url(issue_id))
|
||||
|
||||
|
||||
@bp.route('/<int:issue_id>/links/<int:link_id>/delete', methods=['POST'])
|
||||
@login_required
|
||||
def remove_link(issue_id, link_id):
|
||||
"""Remove a link. Either end of it may do this."""
|
||||
issue = db.session.get(Issue, issue_id)
|
||||
if issue is None:
|
||||
abort(404)
|
||||
if not _issue_readable_by(issue, current_user):
|
||||
abort(403)
|
||||
if not _can_manage_links(issue, current_user):
|
||||
abort(403)
|
||||
|
||||
link = db.session.get(IssueLink, link_id)
|
||||
# The link must actually touch THIS issue. Without the check, anyone able to
|
||||
# manage links on any one issue could delete a link between two others by
|
||||
# posting its id here.
|
||||
if link is None or issue.id not in (link.issue_id, link.linked_issue_id):
|
||||
flash('That link no longer exists.', 'info')
|
||||
return redirect(_view_url(issue_id))
|
||||
|
||||
other_id = link.linked_issue_id if link.issue_id == issue.id else link.issue_id
|
||||
db.session.delete(link)
|
||||
db.session.commit()
|
||||
|
||||
log_action(ACTION_UPDATE, 'Issue', issue.id, f'#{issue.id}',
|
||||
f'unlinked from #{other_id}')
|
||||
current_app.logger.info(
|
||||
'ISSUE UNLINK | issue_id=%s | linked_issue_id=%s | user=%s',
|
||||
issue.id, other_id, current_user.username,
|
||||
)
|
||||
flash(f'Removed the link to issue #{other_id}.', 'info')
|
||||
return redirect(_view_url(issue_id))
|
||||
|
||||
|
||||
@bp.route('/<int:issue_id>/link-search')
|
||||
@login_required
|
||||
def link_search(issue_id):
|
||||
"""JSON candidates for the link picker.
|
||||
|
||||
Scoped exactly like the issue list, so an inspector or customer can only
|
||||
find issues they could already open — searching must not become a way to
|
||||
enumerate another contract's issues. The results are a convenience; the POST
|
||||
in add_link() re-checks access and is the real boundary.
|
||||
"""
|
||||
issue = db.session.get(Issue, issue_id)
|
||||
if issue is None:
|
||||
abort(404)
|
||||
if not _issue_readable_by(issue, current_user):
|
||||
abort(403)
|
||||
|
||||
term = (request.args.get('q') or '').strip().lstrip('#')
|
||||
if len(term) < 1:
|
||||
return jsonify({'results': []})
|
||||
|
||||
q = (
|
||||
Issue.query
|
||||
.outerjoin(Area, Issue.area_id == Area.id)
|
||||
.options(joinedload(Issue.facility), contains_eager(Issue.area))
|
||||
.filter(Issue.id != issue.id)
|
||||
)
|
||||
|
||||
scope = _viewer_facility_scope(current_user)
|
||||
if scope is not None:
|
||||
if not scope:
|
||||
return jsonify({'results': []})
|
||||
q = q.filter(db.or_(
|
||||
Issue.facility_id.in_(scope),
|
||||
db.and_(Issue.area_id.isnot(None), Area.facility_id.in_(scope)),
|
||||
))
|
||||
|
||||
# Exclude issues already linked in either direction — offering them only
|
||||
# produces an "already linked" flash.
|
||||
linked_ids = {other.id for _l, other, _lbl in _readable_links(issue, current_user)}
|
||||
if linked_ids:
|
||||
q = q.filter(Issue.id.notin_(linked_ids))
|
||||
|
||||
if term.isdigit():
|
||||
# A number is almost always an issue number, so match the id first and
|
||||
# fall back to the description for things like "Room 204".
|
||||
q = q.filter(db.or_(Issue.id == int(term),
|
||||
Issue.description.ilike(f'%{term}%')))
|
||||
else:
|
||||
q = q.filter(Issue.description.ilike(f'%{term}%'))
|
||||
|
||||
matches = q.order_by(Issue.reported_at.desc()).limit(10).all()
|
||||
|
||||
return jsonify({'results': [
|
||||
{
|
||||
'id': i.id,
|
||||
'description': (i.description or '')[:110],
|
||||
'status': (i.status or '').replace('_', ' ').title(),
|
||||
'severity': (i.severity or '').title(),
|
||||
'location': (i.area.name if i.area
|
||||
else i.resolved_facility.name if i.resolved_facility
|
||||
else '—'),
|
||||
'reported_at': i.reported_at.strftime('%Y-%m-%d') if i.reported_at else '',
|
||||
}
|
||||
for i in matches
|
||||
]})
|
||||
|
||||
|
||||
# ── Follow ────────────────────────────────────────────────────────────────────
|
||||
|
||||
+19
-19
@@ -74,23 +74,29 @@ def index():
|
||||
if current_user.role in ('admin', 'director', 'project_manager'):
|
||||
inspector_filter = request.args.get('inspector_id', type=int) or None
|
||||
|
||||
# Pre-compute inspection ID sets used by _scope_issue to avoid join conflicts.
|
||||
inspector_inspection_ids = [] # own inspections (inspector role)
|
||||
filter_inspection_ids = None # filtered inspector's inspections (admin/dir/PM)
|
||||
# Scope issues by the relevant inspector's inspections, as a SUBQUERY rather
|
||||
# than a materialised id list. The previous form pulled every inspection id
|
||||
# that inspector had ever performed into Python and sent them straight back
|
||||
# as a literal IN (1, 2, 3, ... N): the round trip is wasted, the statement
|
||||
# grows without bound with the inspector's history, and a long enough list
|
||||
# eventually trips max_allowed_packet. A subquery is also still a single
|
||||
# statement, so the "avoid join conflicts" reason for pre-computing holds.
|
||||
#
|
||||
# IN (empty subquery) already matches nothing, so the explicit empty-list
|
||||
# guards the old code needed are gone rather than merely moved.
|
||||
inspector_insp_subq = None
|
||||
if is_inspector:
|
||||
inspector_inspection_ids = [
|
||||
row[0] for row in
|
||||
inspector_insp_subq = (
|
||||
db.session.query(Inspection.id)
|
||||
.filter(Inspection.inspector_id == current_user.id)
|
||||
.all()
|
||||
]
|
||||
.scalar_subquery()
|
||||
)
|
||||
elif inspector_filter:
|
||||
filter_inspection_ids = [
|
||||
row[0] for row in
|
||||
inspector_insp_subq = (
|
||||
db.session.query(Inspection.id)
|
||||
.filter(Inspection.inspector_id == inspector_filter)
|
||||
.all()
|
||||
]
|
||||
.scalar_subquery()
|
||||
)
|
||||
|
||||
def _scope_insp(q):
|
||||
if is_inspector:
|
||||
@@ -104,14 +110,8 @@ def index():
|
||||
return q
|
||||
|
||||
def _scope_issue(q):
|
||||
if is_inspector:
|
||||
if not inspector_inspection_ids:
|
||||
return q.filter(False)
|
||||
return q.filter(Issue.inspection_id.in_(inspector_inspection_ids))
|
||||
if filter_inspection_ids is not None:
|
||||
if not filter_inspection_ids:
|
||||
return q.filter(False)
|
||||
return q.filter(Issue.inspection_id.in_(filter_inspection_ids))
|
||||
if inspector_insp_subq is not None:
|
||||
return q.filter(Issue.inspection_id.in_(inspector_insp_subq))
|
||||
if customer_facility_ids is not None:
|
||||
if not customer_facility_ids:
|
||||
return q.filter(False)
|
||||
|
||||
Reference in New Issue
Block a user