Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,21 @@ What changed in OpenBGA QM LIMS, newest first: grouped by month, then ranked by
> - New pages under `/monitoring/`: points, limits versions and their parameters, samples, readings and corrections, excursions and investigations. Signatures: `approved` on a limits version (quality), `reviewed` on a sample (reviewer) and `concluded` on an investigation (quality). Frozen content uses the schemas `oq.monitoring-limits/1`, `oq.monitoring-sample/1` and `oq.excursion-investigation/1`.
> - The reminders gain the kind `monitoring` (excursions no investigation covers); the remote lookup `monitoring-points` offers the points that take new samples.

- **Added**: Investigations and impact assessments name their nonconformance, kept by the signed conclusion · Testing · 2026-12-01 · [#92](https://github.com/openbga/qm-lims/pull/92)

An out-of-specification investigation and an impact assessment each carry the **Nonconformance** where their corrective action is followed: the quality system, its number and a link. It is offered when an investigation is escalated or concluded and when an assessment is started, and recorded or corrected from the record while it is open. A confirmed out-of-specification result, or an assessment with a record decided affected, is now concluded only with a nonconformance or the **Reason no nonconformance is needed**, and the signed conclusion keeps it.

In the application: **Testing: investigations**

> **Technical notes**
>
> - New app `nonconformances` (table `Nonconformance`, one per investigation or assessment) with migrations `nonconformances.0001_initial` and `nonconformances.0002_nonconformance_guards`: a reference is never deleted, is written only while its investigation or assessment is open, and every correction advances its revision.
> - Migration `analytical.0015_investigation_nonconformance` adds `Investigation.nonconformance` (what the conclusion keeps; it has a database default) and extends the investigation guard: a confirmed result is not closed without a nonconformance or a reason. Migration `impact.0003_assessment_nonconformance` extends the assessment guard: a conclusion with a record affected carries `nonconformance` in its evidence, which stays `oq.impact-assessment/1` and gains the key only when there is one.
> - New pages `analytical:investigation_nonconformance` and `impact:nonconformance`. Audit actions `nonconformance.recorded` and `nonconformance.corrected`.
> - The lot record export has a **Nonconformances** section, and the product review data's investigation and impact-assessment tables have the columns **Nonconformance**, **Nonconformance link** and **Why no nonconformance is needed**.
> - Callers of `analytical.services.conclude` with a confirmed outcome, and of `impact.services.conclude` for an assessment with a record affected, pass `nonconformance` or `no_nonconformance_reason`.
> - Upgrade: while the migrations run and the previous release still serves, a confirmed investigation or an assessment with a record affected that is concluded on the previous release is refused by the database; sign it again once the new release serves.

- **Added**: Microbial counts calculated from plates read within their incubation window · Testing · 2026-12-01 · [#91](https://github.com/openbga/qm-lims/pull/91)

A method version can now carry a **Plate count**: the medium, the plates at each dilution, the colony limit of a plate and the incubation temperature and reading window, approved with the version. On a test of such a method, analysts record **Plates into the incubator** with the dilutions, the incubator and its temperature and the medium lot, then **Read** the plates within the window and enter each plate's colonies; the count in CFU/g or CFU/mL is calculated by the harmonised pharmacopoeial plate-count rule and shown with how it was calculated. Plates that give no count are kept with the reason, plates that cannot be read are **Set aside**, and **Correct colonies** keeps the original count.
Expand Down
32 changes: 32 additions & 0 deletions analytical/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
from django.utils.html import escape

from core.forms import SignatureIdentityForm
from nonconformances import forms as nonconformance_fields
from nonconformances import services as nonconformances

from .models import AnalyticalTest, Investigation, InvestigationEntry
from .readings import targets
Expand Down Expand Up @@ -34,6 +36,18 @@ class RevisionReasonForm(ReasonForm):
expected_revision = forms.IntegerField(widget=forms.HiddenInput)


class EscalateForm(RevisionReasonForm):
"""The escalation offers the nonconformance raised with it while none is recorded."""

def __init__(self, *args, offer_nonconformance=False, **kwargs):
super().__init__(*args, **kwargs)
if offer_nonconformance:
nonconformance_fields.offer(self, last_system=nonconformance_fields.last_system())

def clean(self):
return nonconformance_fields.clean_offered(self, super().clean())


def bench_fields(choices, method):
"""Equipment and reagent or standard lot checkboxes from the bench's choices.

Expand Down Expand Up @@ -552,3 +566,21 @@ class ConcludeForm(SigningForm):
"pin",
"expected_revision",
]

def __init__(self, *args, offer_nonconformance=False, **kwargs):
"""While no nonconformance is recorded, the conclusion offers one, or the reason none is
needed; a confirmed result needs one of them."""
super().__init__(*args, **kwargs)
if offer_nonconformance:
nonconformance_fields.offer(
self, not_needed=True, last_system=nonconformance_fields.last_system()
)
self.fields[
nonconformances.NONE_NEEDED
].help_text = "Required for a confirmed result when no nonconformance is given."

def clean(self):
data = nonconformance_fields.clean_offered(self, super().clean())
if data.get("outcome") == Investigation.Outcome.CONFIRMED:
nonconformance_fields.require_one(self, data, nonconformances.REQUIRED_INVESTIGATION)
return data
80 changes: 80 additions & 0 deletions analytical/migrations/0015_investigation_nonconformance.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
"""The nonconformance an investigation's signed conclusion keeps.

``nonconformance`` holds what the conclusion froze (the reference recorded, or the reason none
is needed) and is empty while the investigation is open (check constraint). The guard of 0002 is
kept as it was, with the column added to what a conclusion changes and two rules more: what is
kept is a reference with its number or a reason none is needed, and a confirmed result is
concluded only with one of them. The column has a database default, so an instance still
running the previous code inserts an investigation as before; a confirmed conclusion signed on
that instance during the deployment is refused (it names no nonconformance) and is signed again
once the new release serves.
"""

from django.db import migrations, models

PREVIOUS = """
CREATE OR REPLACE FUNCTION analytical_guard_investigation() RETURNS trigger AS $$
DECLARE
mutable text[] := ARRAY['phase', 'outcome', 'assignable_cause', 'conclusion', 'closed_at',
'revision'];
BEGIN
IF TG_OP = 'DELETE' THEN
RAISE EXCEPTION 'Investigations cannot be deleted';
END IF;
IF OLD.phase = 'closed' OR
(to_jsonb(OLD) - mutable) IS DISTINCT FROM (to_jsonb(NEW) - mutable) THEN
RAISE EXCEPTION 'Closed investigations and investigation identity are immutable';
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
"""
FORWARD = """
CREATE OR REPLACE FUNCTION analytical_guard_investigation() RETURNS trigger AS $$
DECLARE
mutable text[] := ARRAY['phase', 'outcome', 'assignable_cause', 'conclusion', 'closed_at',
'revision', 'nonconformance'];
BEGIN
IF TG_OP = 'DELETE' THEN
RAISE EXCEPTION 'Investigations cannot be deleted';
END IF;
IF OLD.phase = 'closed' OR
(to_jsonb(OLD) - mutable) IS DISTINCT FROM (to_jsonb(NEW) - mutable) THEN
RAISE EXCEPTION 'Closed investigations and investigation identity are immutable';
END IF;
IF NEW.nonconformance <> '{}'::jsonb AND NOT (
(COALESCE(NEW.nonconformance ->> 'kind', '') = 'reference'
AND btrim(COALESCE(NEW.nonconformance ->> 'number', '')) <> '')
OR (COALESCE(NEW.nonconformance ->> 'kind', '') = 'not_needed'
AND btrim(COALESCE(NEW.nonconformance ->> 'reason', '')) <> '')) THEN
RAISE EXCEPTION 'A kept nonconformance is a reference with its number or a reason none is needed';
END IF;
IF NEW.phase = 'closed' AND NEW.outcome = 'confirmed' AND NEW.nonconformance = '{}'::jsonb THEN
RAISE EXCEPTION 'A confirmed result is concluded with a nonconformance or the reason none is needed';
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
"""


class Migration(migrations.Migration):
dependencies = [
("analytical", "0014_plate_sets"),
]

operations = [
migrations.AddField(
model_name="investigation",
name="nonconformance",
field=models.JSONField(blank=True, db_default={}, default=dict),
),
migrations.AddConstraint(
model_name="investigation",
constraint=models.CheckConstraint(
condition=models.Q(("phase", "closed"), ("nonconformance", {}), _connector="OR"),
name="analytical_investigation_nonconformance_kept",
),
),
migrations.RunSQL(FORWARD, PREVIOUS),
]
8 changes: 8 additions & 0 deletions analytical/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -588,6 +588,10 @@ class Outcome(models.TextChoices):
opened_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
opened_at = models.DateTimeField(auto_now_add=True)
closed_at = models.DateTimeField(null=True, blank=True)
# The nonconformance as the signed conclusion keeps it (nonconformances.services.settle):
# the reference recorded, or the reason none is needed; empty until then, and when none was
# given for a result that was not confirmed.
nonconformance = models.JSONField(default=dict, db_default={}, blank=True)
revision = models.PositiveIntegerField(default=1)

class Meta:
Expand All @@ -598,6 +602,10 @@ class Meta:
| (~Q(phase="closed") & Q(outcome="") & Q(closed_at__isnull=True)),
name="analytical_investigation_closure",
),
models.CheckConstraint(
condition=Q(phase="closed") | Q(nonconformance={}),
name="analytical_investigation_nonconformance_kept",
),
]

def __str__(self):
Expand Down
59 changes: 56 additions & 3 deletions analytical/services.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
validate_approved_rules,
validate_rules,
)
from nonconformances import services as nonconformances
from quality.models import Lot, Sample

from .contracts import (
Expand Down Expand Up @@ -2105,7 +2106,9 @@ def add_entry(*, actor, investigation, kind, text, external_reference=""):
return entry


def escalate(*, actor, investigation, expected_revision, reason):
def escalate(*, actor, investigation, expected_revision, reason, nonconformance=None):
"""Escalate to a full-scale investigation; ``nonconformance`` (a
``nonconformances.services.Reference``) records the nonconformance raised with it."""
require_role(actor, REVIEWER, QUALITY)
_require_reason(reason)
with transaction.atomic():
Expand All @@ -2126,9 +2129,36 @@ def escalate(*, actor, investigation, expected_revision, reason):
after={"phase": "full"},
reason=reason,
)
if nonconformance is not None:
nonconformances.write(
actor=actor,
subject=investigation,
step=nonconformances.STEP.ESCALATION,
entered=nonconformance,
)
return investigation


def record_nonconformance(*, actor, investigation, expected_revision, entered, reason=""):
"""Record the investigation's nonconformance from its record, or correct the one recorded
(with a reason), while it is open. A reviewer or a quality person; not a signature."""
require_role(actor, REVIEWER, QUALITY)
with transaction.atomic():
investigation = Investigation.objects.select_for_update().get(pk=investigation.pk)
if not investigation.is_open:
raise ValidationError("This investigation is closed.")
_check_revision(investigation, expected_revision)
row = nonconformances.write(
actor=actor,
subject=investigation,
step=nonconformances.STEP.RECORD,
entered=entered,
reason=reason,
)
_touch(investigation)
return row


def _assessment_refusal(investigation):
if not investigation.entries.filter(kind=InvestigationEntry.Kind.ASSESSMENT).exists():
return "Record the laboratory assessment first."
Expand Down Expand Up @@ -2258,8 +2288,22 @@ def apply(locked):
)


def conclude(*, actor, pin, investigation, expected_revision, outcome, assignable_cause, reason):
"""Independent quality conclusion. Invalidation needs a cause and conforming retest data."""
def conclude(
*,
actor,
pin,
investigation,
expected_revision,
outcome,
assignable_cause,
reason,
nonconformance=None,
no_nonconformance_reason="",
):
"""Independent quality conclusion. Invalidation needs a cause and conforming retest data.
The conclusion keeps the investigation's nonconformance: the one recorded, or
``nonconformance`` entered now, or ``no_nonconformance_reason``; a confirmed result needs
one of them."""
if outcome not in Investigation.Outcome.values:
raise ValidationError("Choose an investigation outcome.")

Expand Down Expand Up @@ -2290,6 +2334,15 @@ def apply(locked):
if original.state == AnalyticalTest.State.REVIEWED:
original.state = AnalyticalTest.State.INVALIDATED
_touch(original)
locked.nonconformance = nonconformances.settle(
actor=actor,
subject=locked,
required=nonconformances.REQUIRED_INVESTIGATION
if outcome == Investigation.Outcome.CONFIRMED
else "",
entered=nonconformance,
not_needed=no_nonconformance_reason,
)
locked.outcome = outcome
locked.assignable_cause = assignable_cause
locked.conclusion = reason
Expand Down
16 changes: 16 additions & 0 deletions analytical/templates/analytical/investigation_detail.html
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,22 @@
{% fact label="Closed" %}<time datetime="{{ inv.closed_at|date:'c' }}">{{ inv.closed_at|date:"Y-m-d H:i T" }}</time>{% endfact %}
</dl>{% endpanel %}
{% endif %}
{% panel title="Nonconformance" heading_id="nonconformance-heading" class="mb-3" %}
{% fill actions %}{% if can_record_nonconformance %}<a class="btn btn-sm btn-outline-secondary" href="{% url 'analytical:investigation_nonconformance' inv.pk %}">{% if nonconformance %}Correct nonconformance{% else %}Record nonconformance{% endif %}</a>{% endif %}{% endfill %}
{% if nonconformance %}<dl class="vr-facts">
{% fact label="Quality system" value=nonconformance.system %}
{% fact label="Number" class="vr-id" %}{% if nonconformance.link %}<a href="{{ nonconformance.link }}" rel="noopener noreferrer">{{ nonconformance.number }}</a>{% else %}{{ nonconformance.number }}{% endif %}{% endfact %}
{% fact label="Recorded" %}{{ nonconformance.row.recorded_by|person }} · <time datetime="{{ nonconformance.row.recorded_at|date:'c' }}">{{ nonconformance.row.recorded_at|date:"Y-m-d H:i T" }}</time> · {{ nonconformance.row.get_step_display|lower }}{% endfact %}
{% if nonconformance.row.corrected_at %}{% fact label="Corrected" %}{{ nonconformance.row.corrected_by|person }} · <time datetime="{{ nonconformance.row.corrected_at|date:'c' }}">{{ nonconformance.row.corrected_at|date:"Y-m-d H:i T" }}</time> · revision {{ nonconformance.row.revision }}{% endfact %}{% endif %}
{% if nonconformance.kept %}{% fact label="Conclusion" value="Kept by the signed conclusion" %}{% endif %}
</dl>
{% elif inv.nonconformance.kind == "not_needed" %}<dl class="vr-facts">
{% fact label="Nonconformance" value="None needed, as signed with the conclusion" %}
{% fact label="Reason" wide=True %}{{ inv.nonconformance.reason|linebreaksbr }}{% endfact %}
</dl>
{% elif inv.is_open %}<p class="vr-muted mb-0">No nonconformance is recorded. A confirmed result is concluded with its nonconformance, or with the reason none is needed.</p>
{% else %}<p class="vr-muted mb-0">No nonconformance was recorded.</p>{% endif %}
{% endpanel %}
{% panel title="Results and lineage" heading_id="lineage-heading" table=True class="mb-3" %}
{% fill count %}{{ used }} of {{ allowed }} retests used{% endfill %}
<div class="vr-table-wrap">
Expand Down
12 changes: 12 additions & 0 deletions analytical/tests/test_admin_access.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
)
from core.models import AuditEvent, ElectronicSignature, PINCredential
from core.services import set_pin
from nonconformances.models import Nonconformance
from quality.models import Lot
from quality.services import add_sample

Expand Down Expand Up @@ -58,6 +59,7 @@
"escalate",
"authorize",
"conclude",
"investigation_nonconformance",
"raw_file_new",
"import_new",
"import_file",
Expand Down Expand Up @@ -279,6 +281,14 @@ def world(people, assigned, batch, make_lot, django_user_model):
"expected_revision": fresh(investigation).revision,
},
),
"investigation_nonconformance": (
reverse("analytical:investigation_nonconformance", args=[inv]),
{
"nonconformance_system": "Synthetic QMS",
"nonconformance_number": "NC-ADMIN-1",
"expected_revision": fresh(investigation).revision,
},
),
}
w["read_posts"] = {
"lot_testing": (w["read"]["lot_testing"], {"sample": spare.pk, "reason": "Assign"}),
Expand All @@ -298,6 +308,7 @@ def _state():
"observations": Observation.objects.count(),
"qc": QCResult.objects.count(),
"entries": InvestigationEntry.objects.count(),
"nonconformances": Nonconformance.objects.count(),
"tests": sorted(AnalyticalTest.objects.values_list("pk", "state", "revision", "batch_id")),
"batches": sorted(QCBatch.objects.values_list("pk", "state", "revision")),
"investigations": sorted(Investigation.objects.values_list("pk", "phase", "revision")),
Expand Down Expand Up @@ -382,6 +393,7 @@ def _action_markers(w):
reverse("analytical:escalate", args=[inv]),
reverse("analytical:authorize", args=[inv]),
reverse("analytical:conclude", args=[inv]),
reverse("analytical:investigation_nonconformance", args=[inv]),
],
}
REFUSAL_NOTES.update(
Expand Down
Loading