Extend shift reporting and downtime analytics
This commit is contained in:
1 parent
41a5ae7a63
commit
6e8eb6f50f
74 files changed
+5397
-238
No files matched your search
@@ -0,0 +1,77 @@
|
||||
# Historical attribution reconciliation
|
||||
|
||||
Run from the repository with the existing ENLYZE, ERP, and PostgreSQL secret
|
||||
files (or use the CLI secret-file flags):
|
||||
|
||||
```sh
|
||||
production-analytics historical-reconcile --lookback-days 3 --dry-run
|
||||
production-analytics historical-reconcile --lookback-days 3
|
||||
```
|
||||
|
||||
The default window is the previous three **complete Europe/Berlin calendar days**,
|
||||
from local midnight inclusive to today's midnight exclusive. DST days can have
|
||||
23 or 25 hours. Today's live polling is excluded. Machine IDs and ERP workplaces
|
||||
come from `config/shift-report-machines.yaml`; ENLYZE order name templates are
|
||||
in `config/historical-order-formats.yaml` using the existing order formatter.
|
||||
|
||||
Apply (or reapply) `db/historical_assignment_audit.sql` before a write run; new database
|
||||
installations can use `db/schema.sql`. No schema changes happen automatically.
|
||||
|
||||
The job reads material consumption, channel consumption, and process application
|
||||
snapshots for every configured machine. It requires exactly one closed ENLYZE run
|
||||
covering the sample, plus finished-goods ERP confirmations in that run whose order
|
||||
set equals the run's order. It queries the full extent of overlapping closed runs,
|
||||
including evidence outside the selected window. No confirmation timestamp is
|
||||
interpreted as a production boundary. Missing evidence, open runs, competing runs,
|
||||
and ERP/ENLYZE disagreements are unresolved and logged with record identities.
|
||||
|
||||
Ordinary corrections change only production_order. Measured values, timestamps,
|
||||
and run IDs remain untouched. A persisted cumulative run must be entirely inside the selected data
|
||||
and every affected sample must have unambiguous corroborated evidence. Different
|
||||
parts of the same physical run may map to different closed ENLYZE runs/orders.
|
||||
Ambiguous or partial persisted runs remain unresolved; a wider lookback can
|
||||
resolve partial runs. No ERP confirmation point is used to invent a boundary.
|
||||
|
||||
Cumulative material intervals belong to the ending sample's production order.
|
||||
Order changes never establish a new baseline: each adjacent counter delta is
|
||||
counted exactly once, preserving total physical consumption. Channel material
|
||||
identity gaps are bridged only when all enclosing samples share the same order.
|
||||
|
||||
The summary retains raw row counts and additionally reports physical runs
|
||||
inspected, runs with proposed corrections, proposed/corrected order segments,
|
||||
and unresolved runs/segments. Run identities are scoped by source table, machine,
|
||||
and calculation; channel segment counts use separate extruder/channel streams.
|
||||
Segments are contiguous samples with the same target order and correction state.
|
||||
|
||||
ERP KPI efficiency snapshots and downtime attribution are outside this job's
|
||||
scope: they have separate derivation/reconciliation semantics. Live report
|
||||
reconstruction is unchanged; no final reports are persisted or regenerated.
|
||||
|
||||
Updates use compare-and-set predicates and one serializable transaction per
|
||||
machine, with an advisory lock for concurrent jobs. For application snapshots only,
|
||||
an existing corrected-key row is retained and the stale row deleted when their
|
||||
application_g_m2 values are exactly equal and the target run ID matches the
|
||||
corroborated ENLYZE run. A different value or run ID fails and rolls back the
|
||||
machine. Concurrent modifications also fail. The same transaction inserts audit
|
||||
rows recording the action, machine, table, full record key, old/new order, source
|
||||
run ID, retained target run ID for deduplication, evidence reason, and database
|
||||
timestamp. Already-correct rows
|
||||
produce neither updates nor audit entries. Dry-run runs the same evidence and
|
||||
whole-run checks but writes nothing, including audit rows.
|
||||
|
||||
Any required source/database failure is reported per machine and results in a
|
||||
nonzero exit status; other machines can complete. Invalid configuration fails
|
||||
before processing. Inspect unresolved counts as well as the exit status: lack of
|
||||
unambiguous evidence is distinct from a source outage.
|
||||
|
||||
Deployment examples (not installed or enabled automatically):
|
||||
|
||||
- `deploy/systemd/production-analytics-historical-reconcile.service`
|
||||
- `deploy/systemd/production-analytics-historical-reconcile.timer`
|
||||
|
||||
Review deployment paths, credentials and service user for the host; apply the audit
|
||||
DDL and review a dry-run before installing/enabling the timer. The timer uses
|
||||
`OnCalendar=*-*-* 04:30:00 Europe/Berlin` after ERP at approximately 00:00 and DB1 at
|
||||
approximately 02:30. `Persistent=true` catches a missed run after reboot. The
|
||||
lookback is relative to actual execution time, so long outages require an explicit
|
||||
larger lookback. No automatic retention or backfill beyond that window is implied.
|
||||
+139
-7
@@ -4,17 +4,35 @@
|
||||
speed services sequentially. It performs no database or HTTP reads itself and
|
||||
adds no quantity or interval aggregation. Its frozen `ShiftReport` reuses all
|
||||
four immutable summary models directly, preserving source metadata and items
|
||||
for later PDF or SSR rendering. Neither renderer is implemented here.
|
||||
for PDF output and the live web UI. Presentation lives separately in
|
||||
`presentation.shift_report`; report composition remains output-independent.
|
||||
|
||||
## Configuration and API
|
||||
|
||||
`config/shift-report-machines.yaml` is self-contained for composition:
|
||||
|
||||
```yaml
|
||||
sites:
|
||||
espelkamp:
|
||||
display_name: Espelkamp
|
||||
timezone: Europe/Berlin
|
||||
adorf:
|
||||
display_name: Adorf
|
||||
timezone: Europe/Berlin
|
||||
malaysia:
|
||||
display_name: Malaysia
|
||||
timezone: Asia/Kuala_Lumpur
|
||||
machines:
|
||||
B1:
|
||||
display_name: B1
|
||||
site: espelkamp
|
||||
machine_id: 5f42a4f6-9ca0-4f6f-9786-40d50a35b230
|
||||
erp_workplace: BENTO 1
|
||||
capabilities:
|
||||
production: true
|
||||
downtime: true
|
||||
material: true
|
||||
speed: true
|
||||
material:
|
||||
mode: cumulative
|
||||
calculation_ids:
|
||||
@@ -27,9 +45,20 @@ machines:
|
||||
production_gate_m_min: 0.3
|
||||
```
|
||||
|
||||
Every machine requires a display name, configured site, ERP workplace, and all four
|
||||
boolean capability flags; at least one capability must be enabled. A machine ID is
|
||||
required for downtime, material, or speed, but may be absent for production-only
|
||||
machines. Material and speed configuration are required
|
||||
exactly when their capability is enabled. Material modes remain `cumulative` and
|
||||
`channel`; optional `allocation` is `none` (default) or `erp_fiber_share`. K7 selects
|
||||
the latter through configuration. `load_shift_report_config()` exposes immutable
|
||||
site and machine mappings; `load_shift_report_machines()` retains the machine-only
|
||||
view used by historical reconciliation.
|
||||
|
||||
The loader returns `ShiftReportMachineConfig` values with frozen material and
|
||||
speed configurations. Speed-only consumers now use `machines[name].speed`.
|
||||
Missing/unknown fields, duplicate YAML keys or machine IDs, unsupported material
|
||||
Missing/unknown fields, duplicate YAML keys or non-null machine IDs, invalid site
|
||||
timezones, unsupported material
|
||||
modes, empty/duplicate calculation IDs, and invalid speed metadata are rejected.
|
||||
No unrelated YAML configuration is loaded at runtime.
|
||||
|
||||
@@ -45,16 +74,16 @@ service = ShiftReportService(
|
||||
channel_materials=channel_material_service,
|
||||
speed=speed_service,
|
||||
)
|
||||
start, end = shift_report_window(day, "early")
|
||||
start, end = shift_report_window(day, "early", machines["B1"].timezone)
|
||||
report = service.build(machine_name="B1", start=start, end=end)
|
||||
```
|
||||
|
||||
`shift_report_window` lives in `calculations.shift_report`; the loader and
|
||||
service live in `service.shift_report_config` and `service.shift_report`.
|
||||
The day is the shift's start date in Europe/Berlin. Early is 06:00–14:00, late is
|
||||
The day is the shift's start date in the machine site's timezone. Early is 06:00–14:00, late is
|
||||
14:00–22:00, and night is 22:00–06:00 on the following day. Night shifts can have
|
||||
seven or nine elapsed hours at DST transitions. Explicit windows are validated
|
||||
as aware, positive-duration instants and normalized to Berlin for all service
|
||||
as aware, positive-duration instants and normalized to the site timezone for all service
|
||||
calls. All source services retain their `[start, end)` semantics.
|
||||
|
||||
## Source semantics
|
||||
@@ -62,6 +91,9 @@ calls. All source services retain their `[start, end)` semantics.
|
||||
Production uses the existing finished-goods ERP service with workplaces B1:
|
||||
`BENTO 1`, E1: `1568705`, and K7: `K7`. Its order/article groups, m², roll counts,
|
||||
and first/last confirmation timestamps remain available in `report.production`.
|
||||
The ERP SQL query uses naive site-local `[start, end)` timestamps, and returned
|
||||
confirmations are attached to the configured IANA timezone. Historical
|
||||
reconciliation retains its Europe/Berlin default.
|
||||
|
||||
`report.downtime.non_downtime_seconds` is the elapsed shift duration minus the
|
||||
union of downtime intervals. It is a time complement and does not measure actual
|
||||
@@ -84,8 +116,108 @@ Speed is the arithmetic sample mean strictly above the configured production
|
||||
gate: average speed while running, not average speed over the full shift.
|
||||
Counts, gate, and active min/max are preserved in `report.speed`.
|
||||
|
||||
Every source is mandatory. Exceptions propagate immediately and later services
|
||||
are not called. An empty successful summary remains an empty summary; a failed
|
||||
Every enabled source is mandatory. Disabled sections are `None` in the report and
|
||||
render as unavailable; no source is queried for them. Exceptions propagate
|
||||
immediately and later services are not called. An empty successful summary remains
|
||||
an empty summary; a failed
|
||||
read is never replaced with zeros. No cross-source matching of runs or orders is
|
||||
introduced, and sequential reads are not a transactionally consistent snapshot
|
||||
across ERP, PostgreSQL, and ENLYZE.
|
||||
|
||||
## Generate an explicit shift PDF
|
||||
|
||||
Install the project with `pip install -e '.[dev]'`. Shift PDFs use the declared
|
||||
`reportlab>=4.2,<5` dependency: a direct PDF writer without an external browser
|
||||
or native HTML rendering stack. The older monthly energy report remains separate.
|
||||
|
||||
Run from the repository root, with access to the existing read-only sources:
|
||||
|
||||
```bash
|
||||
production-analytics report shift --machine E1 \
|
||||
--start '2026-10-07T06:00:00+02:00' \
|
||||
--end '2026-10-07T14:00:00+02:00' \
|
||||
--output data/reports/E1_2026-10-07_early.pdf
|
||||
```
|
||||
|
||||
The PDF is written exactly to `--output`, relative to the working directory for
|
||||
relative paths. Parent directories are created, and an existing file is replaced
|
||||
only after rendering succeeds. No sidecar HTML is written. B1, E1, and K7 are
|
||||
configured in `config/shift-report-machines.yaml`; override with `--config`.
|
||||
Start and end are mandatory ISO 8601 timestamps with offsets (or `Z`); the end
|
||||
must follow the start. There is no implicit current-shift selection.
|
||||
|
||||
Settings are read from the process environment, overlaid by these dotenv files:
|
||||
|
||||
- `secrets/enlyze.env` (`--secrets-file`): `ENLYZE_BASE_URL`, `ENLYZE_API_KEY`,
|
||||
optional `ENLYZE_HTTP_TIMEOUT_SECONDS`.
|
||||
- `secrets/erp.env` (`--erp-secrets-file`): `ERP_DB_HOST`, `ERP_DB_PORT`,
|
||||
`ERP_DB_NAME`, `ERP_DB_USER`, `ERP_DB_PASSWORD`.
|
||||
- `secrets/postgres.env` (`--db-secrets-file`): `POSTGRES_HOST`, `POSTGRES_PORT`,
|
||||
`POSTGRES_DB`, `POSTGRES_USER`, `POSTGRES_PASSWORD`.
|
||||
|
||||
PostgreSQL must already contain the existing downtime and material snapshots;
|
||||
this command performs no collection or polling. ERP supplies production and
|
||||
ENLYZE supplies speed through the existing readers. Source failures fail the
|
||||
command; empty successful summaries receive explicit German empty-state text.
|
||||
Validation/configuration errors return exit code 2; other failures return 1.
|
||||
|
||||
The A4 slip includes production, supplied totals, downtime with the top three
|
||||
reasons, material consumption including channel identities, and running speed.
|
||||
Numbers use German separators with two decimal places. Durations retain hours,
|
||||
minutes, and tenths of seconds. Times display the report site's timezone and
|
||||
numeric offsets, including across daylight-saving transitions. Missing material
|
||||
names are explicitly marked `Nicht verfügbar`; no identity is inferred. B1
|
||||
source assignments are rendered unchanged, and energy is excluded.
|
||||
|
||||
`present_report(report)` returns an immutable, deterministic presentation model;
|
||||
`render_pdf(report)` returns PDF bytes and `write_pdf(report, output)` writes them.
|
||||
Only the supplied `ShiftReport` is consumed. Fixed ReportLab invariant metadata,
|
||||
styles, fonts, and no generated-at clock make PDF bytes repeatable for the same
|
||||
input and installed ReportLab version. Bytes are not promised identical across
|
||||
library versions. Long reports paginate with repeated table headers and page
|
||||
numbers. The domain report is also the input for the live web presenter.
|
||||
|
||||
|
||||
## Live web interface
|
||||
|
||||
The website is the primary working interface; PDF is an export/archive artifact.
|
||||
Run from the repository root:
|
||||
|
||||
```bash
|
||||
.venv/bin/python -m production_analytics.web --port 8087
|
||||
```
|
||||
|
||||
Open <http://127.0.0.1:8087/>. After installing the updated project, the equivalent
|
||||
entry point is `production-analytics-web`. This lightweight standard-library WSGI
|
||||
application uses no frontend framework. `--host` defaults to loopback; `--port`
|
||||
defaults to `SHIFT_REPORT_PORT` or 8087. The bundled server is intended for local
|
||||
use; a production deployment can serve `create_app(...)` with a WSGI server.
|
||||
Machine configuration and secret-file options match the report CLI: `--config`,
|
||||
`--secrets-file`, `--erp-secrets-file`, and `--db-secrets-file`.
|
||||
|
||||
The date is always the shift **start date**, including night shifts. The default
|
||||
uses the selected machine site's local time and selects the most recent fully completed
|
||||
shift: before 06:00 yesterday's late shift; from 06:00 yesterday's night shift;
|
||||
from 14:00 today's early shift; from 22:00 today's late shift. At a boundary the
|
||||
just-completed shift becomes the default. Night windows end on the following
|
||||
calendar day; DST nights have seven or nine elapsed hours.
|
||||
|
||||
GET parameters are `date=YYYY-MM-DD`, `shift=early|late|night`, and `machine`
|
||||
(configuration key). Omitted parameters use the default selection. Every request,
|
||||
including reloads and `format=pdf`, constructs the existing source services and
|
||||
calls `ShiftReportService.build` exactly once. No final report is persisted or
|
||||
cached. Existing raw material snapshots remain source inputs. Responses use
|
||||
`Cache-Control: no-store`.
|
||||
|
||||
HTML formats `present_report(report)` blocks shared with PDF, including the
|
||||
existing material allocation explanation. `Als PDF exportieren` submits the
|
||||
selected controls and passes that request's freshly built `ShiftReport` directly
|
||||
to `render_pdf`. Export therefore reflects current data at export time; source
|
||||
corrections between viewing and exporting may change the result. It never reuses
|
||||
a stale stored report or runs a second fetch/calculation path. The HTML data-state
|
||||
time is recorded after service generation, in the machine site's timezone, and makes no
|
||||
completeness claim. Sources are still read sequentially, not transactionally.
|
||||
|
||||
Invalid selections return a German page-level error (HTTP 400). Source/settings
|
||||
or rendering failures return a generic German error (HTTP 503), retaining the
|
||||
selection controls without exposing exception text or credentials.
|
||||
+49
-49
@@ -1,59 +1,61 @@
|
||||
# Shift running-speed KPI
|
||||
|
||||
`average_line_speed_m_min` is the arithmetic mean of finite speed samples
|
||||
strictly above the configured production gate within `[start, end)`. Samples
|
||||
have equal weight regardless of spacing. Inactive time does not contribute to
|
||||
this KPI. No interpolation, carry-forward, or time weighting is applied.
|
||||
`average_line_speed_m_min` is the arithmetic mean of active, finite production-speed
|
||||
samples in `[start, end)`. Each active sample has equal weight. The calculation does
|
||||
not interpolate or weight speed by elapsed time.
|
||||
|
||||
The immutable summary includes signal, unit, gate, window, finite sample count,
|
||||
active/inactive counts, active average/minimum/maximum, and invalid sample count.
|
||||
`sample_count` counts finite numeric in-window values and equals active plus
|
||||
inactive counts. Zero, negative, and values equal to or below the gate are
|
||||
inactive. Null, non-numeric, boolean, NaN, and infinite values are invalid and
|
||||
excluded from all finite/active statistics. Invalid/missing timestamps are also
|
||||
counted separately as unavailable because window membership cannot be verified.
|
||||
Absent source rows are not synthesized or counted. Without active samples,
|
||||
average, minimum, and maximum are all `None`.
|
||||
## Activity gates
|
||||
|
||||
Window timestamps must be timezone aware and have positive elapsed duration.
|
||||
All boundary comparisons use UTC instants, including DST folds.
|
||||
The `speed` block has exactly one activity method:
|
||||
|
||||
## Configuration and service API
|
||||
- **Simple numeric:** `production_gate_m_min` selects speed samples strictly above
|
||||
the threshold. B1, E1 and K7 retain this behavior.
|
||||
- **Boolean:** `running_signal_ref` and optional `running_when` (default `true`)
|
||||
select samples whose status is exactly that Boolean. K5 uses `running_when: false`
|
||||
because its status signal is true when stopped.
|
||||
- **Numeric dwell:** `numeric_dwell_gate` has `signal_ref`, finite `threshold`,
|
||||
`comparison` (`below` or `above`), and positive integer
|
||||
`minimum_duration_seconds`. Gitter 1–4 use `below` and 150 seconds. Their
|
||||
production-speed signal holds its last value while stopped, and their PLC
|
||||
Boolean status did not reliably indicate downtime. The numeric gate follows
|
||||
the configured ENLYZE threshold and minimum duration concept.
|
||||
|
||||
Machine-specific UUIDs, signal labels, units, and gates live in
|
||||
`config/shift-report-machines.yaml`. It also contains the ERP workplace and material source references needed for
|
||||
report composition; existing material-calculation definitions are not duplicated. The configured gates are
|
||||
B1: 0.3 m/min; E1: 0.5 m/min; K7: 0.5 m/min. The config loader validates required
|
||||
fields, non-empty identifiers, unique machine IDs, m/min units, and finite
|
||||
non-negative gates. It returns frozen report machine configurations by name, each with a nested
|
||||
`ShiftSpeedConfig` in `.speed`.
|
||||
For `below`, only a gate value strictly less than the threshold satisfies the
|
||||
condition. An equal value ends a below-threshold run. Rows are ordered by their
|
||||
UTC timestamps; a condition reading remains the observed state until the next
|
||||
reading. A continuous below-threshold run qualifies when the elapsed time from
|
||||
its first below-threshold timestamp to the first non-below reading is at least
|
||||
the minimum duration. If it qualifies, **all** speed samples in that run are
|
||||
inactive, including those before the minimum duration elapsed. A short run
|
||||
bracketed by non-below readings stays active. The same rules apply to `above`.
|
||||
The interval ending at the non-satisfying reading excludes that reading.
|
||||
|
||||
```python
|
||||
from datetime import datetime
|
||||
from zoneinfo import ZoneInfo
|
||||
The service requests speed and the gate signal together from `/v2/timeseries`.
|
||||
For a dwell gate it extends the read window by one minimum duration on each side;
|
||||
only production-speed samples in the original report window enter the KPI. This
|
||||
lets a qualifying run crossing a report boundary be classified when the source
|
||||
provides enough surrounding readings. An unclosed short run, or a short run
|
||||
without a preceding non-satisfying reading, has unknown duration and is excluded
|
||||
conservatively. An invalid or non-finite gate reading breaks continuity and its
|
||||
speed row is excluded. A missing required gate column fails the read. No absent
|
||||
rows are synthesized; the result depends on the timestamps returned by ENLYZE,
|
||||
which deserves validation against live boundary cases.
|
||||
|
||||
from production_analytics.enlyze.gateway import EnlyzeApiGateway
|
||||
from production_analytics.service.shift_report_config import load_shift_report_machines
|
||||
from production_analytics.service.shift_speed import ShiftSpeedService
|
||||
Invalid speed values (including Boolean, null, non-numeric, NaN, and infinity)
|
||||
are excluded in every mode. Invalid timestamps are also excluded. In Boolean
|
||||
mode, missing or non-Boolean status is excluded. `sample_count` is the sum of
|
||||
active and inactive valid speed samples; excluded samples increment
|
||||
`invalid_sample_count`. If no active samples remain, average, minimum and maximum
|
||||
are `None`.
|
||||
|
||||
machines = load_shift_report_machines("config/shift-report-machines.yaml")
|
||||
service = ShiftSpeedService(EnlyzeApiGateway(client)) # Existing ExplorationClient
|
||||
summary = service.summarize(
|
||||
config=machines["K7"].speed,
|
||||
start=datetime(2026, 10, 7, 6, tzinfo=ZoneInfo("Europe/Berlin")),
|
||||
end=datetime(2026, 10, 7, 14, tzinfo=ZoneInfo("Europe/Berlin")),
|
||||
)
|
||||
```
|
||||
Machine UUIDs and gate settings live in `config/shift-report-machines.yaml`.
|
||||
The loader validates the gate fields and rejects overlapping Boolean and dwell
|
||||
gates. `ShiftSpeedService.summarize()` composes the gateway read with the pure
|
||||
`aggregate_shift_speed()` calculation. The calculation accepts
|
||||
`ShiftSpeedSample(timestamp, value, running, gate_value)` records. Structural
|
||||
timeseries and pagination errors fail the read instead of returning a partial KPI.
|
||||
|
||||
`aggregate_shift_speed(samples, config=..., start=..., end=...)` is the pure
|
||||
calculation API, accepting `ShiftSpeedSample(timestamp, value)` objects.
|
||||
`EnlyzeApiGateway.get_speed_samples(machine_id=..., speed_signal_ref=...,
|
||||
start=..., end=...)` requests just the configured signal from `/v2/timeseries`,
|
||||
using the existing client and cursor semantics. It tolerates unavailable sample
|
||||
values/timestamps; structural response and pagination errors fail the read,
|
||||
preventing a partial successful summary. No snapshots are persisted.
|
||||
|
||||
## Supplied live reference
|
||||
## Supplied legacy reference
|
||||
|
||||
For 2026-10-07 06:00–14:00 Europe/Berlin:
|
||||
|
||||
@@ -63,6 +65,4 @@ For 2026-10-07 06:00–14:00 Europe/Berlin:
|
||||
| E1 | 2880 | 2782 | 7.933009468249328 |
|
||||
| K7 | 2880 | 2667 | 10.078945039942955 |
|
||||
|
||||
These are the supplied validation values, not a new live read performed during
|
||||
implementation. Tests cover filtering, statistics, boundary/DST behavior,
|
||||
configuration, service composition, and gateway pagination with mocked responses.
|
||||
These are supplied validation values, not a new live read.
|
||||
Reference in new issue
Block a user