Compare commits
2
Commits
824b1caca7
...
41a5ae7a63
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
41a5ae7a63 | ||
|
|
1b060377aa |
No files matched your search
@@ -1,5 +1,5 @@
|
|||||||
# Supply E1's ENLYZE machine UUID before operating. Signal references are PLC
|
# Process signals use unique PLC origins. Direct material names use explicit
|
||||||
# origins, resolved uniquely by the ENLYZE gateway at poll time.
|
# ENLYZE variable UUIDs (uuid:<UUID>); null current values remain unavailable.
|
||||||
calculations:
|
calculations:
|
||||||
- id: e1-channel-material-consumption
|
- id: e1-channel-material-consumption
|
||||||
type: channel_material_consumption
|
type: channel_material_consumption
|
||||||
@@ -11,20 +11,76 @@ calculations:
|
|||||||
- id: Ex1
|
- id: Ex1
|
||||||
total_rate_signal_ref: DB107:18
|
total_rate_signal_ref: DB107:18
|
||||||
channels:
|
channels:
|
||||||
- {id: C1, status_signal_ref: DB107:122.0, percentage_signal_ref: DB107:126, screw_speed_signal_ref: DB107:170}
|
- id: C1
|
||||||
- {id: C2, status_signal_ref: DB107:222.0, percentage_signal_ref: DB107:226, screw_speed_signal_ref: DB107:270}
|
status_signal_ref: DB107:122.0
|
||||||
- {id: C3, status_signal_ref: DB107:322.0, percentage_signal_ref: DB107:326, screw_speed_signal_ref: DB107:370}
|
percentage_signal_ref: DB107:126
|
||||||
- {id: C4, status_signal_ref: DB107:422.0, percentage_signal_ref: DB107:426, screw_speed_signal_ref: DB107:470}
|
screw_speed_signal_ref: DB107:170
|
||||||
- {id: C5, status_signal_ref: DB107:522.0, percentage_signal_ref: DB107:526, screw_speed_signal_ref: DB107:570}
|
material_name_signal_ref: "uuid:d3129cf5-3b6e-486c-99e3-8ee6b6fbd7aa"
|
||||||
- {id: C6, status_signal_ref: DB107:622.0, percentage_signal_ref: DB107:626, screw_speed_signal_ref: DB107:670}
|
- id: C2
|
||||||
- {id: C7, status_signal_ref: DB107:722.0, percentage_signal_ref: DB107:726, screw_speed_signal_ref: DB107:770}
|
status_signal_ref: DB107:222.0
|
||||||
|
percentage_signal_ref: DB107:226
|
||||||
|
screw_speed_signal_ref: DB107:270
|
||||||
|
material_name_signal_ref: "uuid:b8be6b5a-0ce7-40ed-9754-107175468c8d"
|
||||||
|
- id: C3
|
||||||
|
status_signal_ref: DB107:322.0
|
||||||
|
percentage_signal_ref: DB107:326
|
||||||
|
screw_speed_signal_ref: DB107:370
|
||||||
|
material_name_signal_ref: "uuid:08e0e7e5-574a-487e-8a73-329d9cd9c2f7"
|
||||||
|
- id: C4
|
||||||
|
status_signal_ref: DB107:422.0
|
||||||
|
percentage_signal_ref: DB107:426
|
||||||
|
screw_speed_signal_ref: DB107:470
|
||||||
|
material_name_signal_ref: "uuid:de3ea4b4-9f60-4ff7-9c7f-c04a5348a8ae"
|
||||||
|
- id: C5
|
||||||
|
status_signal_ref: DB107:522.0
|
||||||
|
percentage_signal_ref: DB107:526
|
||||||
|
screw_speed_signal_ref: DB107:570
|
||||||
|
material_name_signal_ref: "uuid:fd774a7a-ff76-449a-82a6-8b7a8c9aa8af"
|
||||||
|
- id: C6
|
||||||
|
status_signal_ref: DB107:622.0
|
||||||
|
percentage_signal_ref: DB107:626
|
||||||
|
screw_speed_signal_ref: DB107:670
|
||||||
|
material_name_signal_ref: "uuid:16b8d94e-2b7f-48a4-bb46-a212554837b1"
|
||||||
|
- id: C7
|
||||||
|
status_signal_ref: DB107:722.0
|
||||||
|
percentage_signal_ref: DB107:726
|
||||||
|
screw_speed_signal_ref: DB107:770
|
||||||
|
material_name_signal_ref: "uuid:35bc651a-9e47-4a4d-bb9b-6505e08cb056"
|
||||||
- id: Ex2
|
- id: Ex2
|
||||||
total_rate_signal_ref: DB207:18
|
total_rate_signal_ref: DB207:18
|
||||||
channels:
|
channels:
|
||||||
- {id: C1, status_signal_ref: DB207:122.0, percentage_signal_ref: DB207:126, screw_speed_signal_ref: DB207:170}
|
- id: C1
|
||||||
- {id: C2, status_signal_ref: DB207:222.0, percentage_signal_ref: DB207:226, screw_speed_signal_ref: DB207:270}
|
status_signal_ref: DB207:122.0
|
||||||
- {id: C3, status_signal_ref: DB207:322.0, percentage_signal_ref: DB207:326, screw_speed_signal_ref: DB207:370}
|
percentage_signal_ref: DB207:126
|
||||||
- {id: C4, status_signal_ref: DB207:422.0, percentage_signal_ref: DB207:426, screw_speed_signal_ref: DB207:470}
|
screw_speed_signal_ref: DB207:170
|
||||||
- {id: C5, status_signal_ref: DB207:522.0, percentage_signal_ref: DB207:526, screw_speed_signal_ref: DB207:570}
|
material_name_signal_ref: "uuid:7e0b7ea0-1564-467b-aa74-d6ea48ee4a1c"
|
||||||
- {id: C6, status_signal_ref: DB207:622.0, percentage_signal_ref: DB207:626, screw_speed_signal_ref: DB207:670}
|
- id: C2
|
||||||
- {id: C7, status_signal_ref: DB207:722.0, percentage_signal_ref: DB207:726, screw_speed_signal_ref: DB207:770}
|
status_signal_ref: DB207:222.0
|
||||||
|
percentage_signal_ref: DB207:226
|
||||||
|
screw_speed_signal_ref: DB207:270
|
||||||
|
material_name_signal_ref: "uuid:25aeaf2f-cc77-4af0-8109-adf51fb86735"
|
||||||
|
- id: C3
|
||||||
|
status_signal_ref: DB207:322.0
|
||||||
|
percentage_signal_ref: DB207:326
|
||||||
|
screw_speed_signal_ref: DB207:370
|
||||||
|
material_name_signal_ref: "uuid:ed1eaa2f-31c4-4237-9b6d-8d47f74a3c83"
|
||||||
|
- id: C4
|
||||||
|
status_signal_ref: DB207:422.0
|
||||||
|
percentage_signal_ref: DB207:426
|
||||||
|
screw_speed_signal_ref: DB207:470
|
||||||
|
material_name_signal_ref: "uuid:eb6a77b6-db1a-4826-9633-9bb38fbc7720"
|
||||||
|
- id: C5
|
||||||
|
status_signal_ref: DB207:522.0
|
||||||
|
percentage_signal_ref: DB207:526
|
||||||
|
screw_speed_signal_ref: DB207:570
|
||||||
|
material_name_signal_ref: "uuid:68672e9b-aff8-47c8-980a-aa71bc6f2b2d"
|
||||||
|
- id: C6
|
||||||
|
status_signal_ref: DB207:622.0
|
||||||
|
percentage_signal_ref: DB207:626
|
||||||
|
screw_speed_signal_ref: DB207:670
|
||||||
|
material_name_signal_ref: "uuid:0955ce3e-658f-47e4-8d60-3a331ab428d1"
|
||||||
|
- id: C7
|
||||||
|
status_signal_ref: DB207:722.0
|
||||||
|
percentage_signal_ref: DB207:726
|
||||||
|
screw_speed_signal_ref: DB207:770
|
||||||
|
material_name_signal_ref: "uuid:bd833c03-3323-41f3-81cd-b624d3af555b"
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
machine_id: 8302e3d1-b1e5-42f1-8540-615eb6c73e08
|
||||||
|
erp_workplace: "1568705"
|
||||||
|
production_order_format: "E 1-{production_order}"
|
||||||
|
poll_interval_seconds: 300
|
||||||
|
lookback_hours: 48
|
||||||
|
full_reconciliation_hours: 24
|
||||||
|
completion_tolerance_m2: 0.001
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
machine_id: c220f95c-a65e-4cb7-99b7-0626d6c7508c
|
||||||
|
erp_workplace: K7
|
||||||
|
production_order_format: "K 7-{production_order}"
|
||||||
|
poll_interval_seconds: 300
|
||||||
|
lookback_hours: 48
|
||||||
|
full_reconciliation_hours: 24
|
||||||
|
completion_tolerance_m2: 0.001
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
machines:
|
||||||
|
B1:
|
||||||
|
machine_id: 5f42a4f6-9ca0-4f6f-9786-40d50a35b230
|
||||||
|
erp_workplace: BENTO 1
|
||||||
|
material:
|
||||||
|
mode: cumulative
|
||||||
|
calculation_ids:
|
||||||
|
- bento1-fresh-bentonite-consumption
|
||||||
|
- bento1-spreader3-consumption
|
||||||
|
speed:
|
||||||
|
signal_ref: fef41976-1103-4090-b780-eaeecc02fdfa
|
||||||
|
signal: Transport Auszug Geschwindigkeit Istwert
|
||||||
|
unit: m/min
|
||||||
|
production_gate_m_min: 0.3
|
||||||
|
E1:
|
||||||
|
machine_id: 8302e3d1-b1e5-42f1-8540-615eb6c73e08
|
||||||
|
erp_workplace: '1568705'
|
||||||
|
material:
|
||||||
|
mode: channel
|
||||||
|
calculation_ids:
|
||||||
|
- e1-channel-material-consumption
|
||||||
|
speed:
|
||||||
|
signal_ref: 488e28a9-79a6-44c4-9cc2-c021bb2108ec
|
||||||
|
signal: Geschwindigkeit Gesamtanlage
|
||||||
|
unit: m/min
|
||||||
|
production_gate_m_min: 0.5
|
||||||
|
K7:
|
||||||
|
machine_id: c220f95c-a65e-4cb7-99b7-0626d6c7508c
|
||||||
|
erp_workplace: K7
|
||||||
|
material:
|
||||||
|
mode: cumulative
|
||||||
|
calculation_ids:
|
||||||
|
- k7-fiber-consumption
|
||||||
|
speed:
|
||||||
|
signal_ref: 823867bb-f5d2-40eb-b875-657155addfd0
|
||||||
|
signal: Geschwindigkeit Gesamtanlage
|
||||||
|
unit: m/min
|
||||||
|
production_gate_m_min: 0.5
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
# Shift material consumption
|
||||||
|
|
||||||
|
The read-only layer uses stored cumulative machine quantities. It does not use
|
||||||
|
ERP bookings or infer material labels for B1/K7.
|
||||||
|
|
||||||
|
## API
|
||||||
|
|
||||||
|
`PostgresShiftMaterialRepository` and `PostgresShiftChannelMaterialRepository`
|
||||||
|
(in `service.postgres_shift_material`) expose
|
||||||
|
`get_snapshots(machine_id=..., calculation_ids=(...), start=..., end=...)`.
|
||||||
|
Each call executes one parameterized query: one latest valid baseline at or
|
||||||
|
before start per calculation/channel, followed by all raw rows strictly after
|
||||||
|
start and before end. Valid baselines have finite, non-negative counters. Missing
|
||||||
|
baselines do not suppress in-window rows. In-window invalid counters remain
|
||||||
|
visible to aggregation for run-boundary and reset validation.
|
||||||
|
|
||||||
|
Compose these readers with `ShiftMaterialService` or
|
||||||
|
`ShiftChannelMaterialService` (in `service.shift_material`) and call:
|
||||||
|
|
||||||
|
```python
|
||||||
|
summary = service.summarize(
|
||||||
|
machine_id="K7",
|
||||||
|
calculation_ids=("k7-fiber-consumption",),
|
||||||
|
start=start,
|
||||||
|
end=end,
|
||||||
|
include_zero=False,
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
The same keyword arguments apply to the pure functions
|
||||||
|
`aggregate_shift_material` and `aggregate_shift_channel_material` in
|
||||||
|
`calculations.shift_material`, with an iterable of snapshots as their first
|
||||||
|
argument. Results are frozen `ShiftMaterialSummary` objects containing a tuple
|
||||||
|
of frozen `ShiftMaterialItem` objects. Items retain source, calculation, machine,
|
||||||
|
production order, run, quantity, observed baseline/end timestamps, and optional
|
||||||
|
channel/material/quality metadata. Results have deterministic ordering.
|
||||||
|
`include_zero=True` preserves diagnostic zero items; false omits them.
|
||||||
|
|
||||||
|
## Boundaries and runs
|
||||||
|
|
||||||
|
All timestamps must be timezone aware. Validation, ordering, and comparisons use
|
||||||
|
UTC instants, including DST folds. The window is `[start, end)` and must have
|
||||||
|
positive elapsed duration. No interpolation or extrapolation is performed.
|
||||||
|
|
||||||
|
Each calculation stream is segmented by observed run transitions. Channel
|
||||||
|
streams additionally separate extruder and doser channel. Within the active run,
|
||||||
|
the baseline is the last valid cumulative sample at or before shift start;
|
||||||
|
the end is the last valid sample strictly before shift end or the next observed
|
||||||
|
run transition. A run without a pre-window baseline uses its first valid sample
|
||||||
|
and flags `baseline_missing=True`. Its initial counter is not counted. There is
|
||||||
|
no differencing across runs. A lone valid sample yields a diagnostic zero item;
|
||||||
|
no valid samples yield an empty summary. Neither implies source freshness.
|
||||||
|
|
||||||
|
Null and non-finite counters are skipped as quantity samples, but their rows
|
||||||
|
still establish run boundaries. Every selected consecutive valid counter pair
|
||||||
|
is checked: decreases/resets raise `ValueError`, even if the final value later
|
||||||
|
recovers. Negative counters, duplicate stream timestamps, reappearing runs, and
|
||||||
|
production-order changes within a run also raise rather than guessing.
|
||||||
|
|
||||||
|
## E1 materials
|
||||||
|
|
||||||
|
For consecutive valid samples A → B, attribute `B.counter - A.counter` to the
|
||||||
|
material number, name, and mapping status stored on **B**. Consecutive intervals
|
||||||
|
with the same identity form a segment. A → null → A remains separate segments.
|
||||||
|
Blank labels become null; historical null names remain null even if a material
|
||||||
|
number is present. There is no last-known name carry-forward or ERP lookup.
|
||||||
|
When both number and name are absent, the segment status is `UNAVAILABLE`.
|
||||||
|
Otherwise the stored mapping status is retained. Percentage validity is the
|
||||||
|
logical AND of the ending samples' flags in that segment.
|
||||||
|
|
||||||
|
If a counter is invalid between valid samples, the quantity interval bridges
|
||||||
|
those valid samples and uses the ending valid sample's identity; no intermediate
|
||||||
|
material allocation is fabricated. Run boundaries still interrupt that bridge.
|
||||||
|
|
||||||
|
Repository tests use mocked PostgreSQL connections; they do not validate query
|
||||||
|
plans or execute queries against a live database.
|
||||||
|
|
||||||
|
|
||||||
|
## PostgreSQL read performance
|
||||||
|
|
||||||
|
Machine reads use `unnest` plus a lateral `ORDER BY timestamp DESC LIMIT 1`
|
||||||
|
lookup per requested calculation ID. Equality on calculation and machine allows
|
||||||
|
the existing `(calculation_id, machine_id, timestamp)` index to seek backward
|
||||||
|
from shift start. A separate `UNION ALL` branch reads only the bounded window,
|
||||||
|
with the same calculation/machine predicates. Both branches run in one statement
|
||||||
|
and retain the existing 10-second timeout. Final ordering is deterministic.
|
||||||
|
|
||||||
|
Channel reads use `DISTINCT ON (calculation_id, extruder, doser_channel)` ordered
|
||||||
|
by descending timestamp for the baseline, plus a bounded-window branch. This
|
||||||
|
performs one filtered baseline pass for the requested calculations/machine,
|
||||||
|
instead of correlated history checks per source row or per channel. The existing
|
||||||
|
unique index can restrict calculation/machine, but its intervening
|
||||||
|
`production_order` prevents it from delivering channel timestamp ordering
|
||||||
|
without additional work. Channel baseline selection may still scan substantial
|
||||||
|
history and sort it; its live latency has not been measured here.
|
||||||
|
|
||||||
|
If E1 remains slow, inspect `EXPLAIN (ANALYZE, BUFFERS)` for each branch first.
|
||||||
|
A `(calculation_id, machine_id, timestamp)` index would help the bounded window;
|
||||||
|
a `(calculation_id, machine_id, extruder, doser_channel, timestamp DESC)` index
|
||||||
|
would help channel baseline ordering. Neither is added by this change. Choose
|
||||||
|
based on the measured plan and account for snapshot-write/storage overhead.
|
||||||
|
|
||||||
|
The supplied K7 live measurement (0.022 seconds for 2580 rows) supports the
|
||||||
|
baseline-plus-window strategy. This change was tested locally with mocked
|
||||||
|
PostgreSQL connections, without claiming a new live benchmark.
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
# Unified shift-report composition
|
||||||
|
|
||||||
|
`ShiftReportService` composes the existing production, downtime, material, and
|
||||||
|
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.
|
||||||
|
|
||||||
|
## Configuration and API
|
||||||
|
|
||||||
|
`config/shift-report-machines.yaml` is self-contained for composition:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
machines:
|
||||||
|
B1:
|
||||||
|
machine_id: 5f42a4f6-9ca0-4f6f-9786-40d50a35b230
|
||||||
|
erp_workplace: BENTO 1
|
||||||
|
material:
|
||||||
|
mode: cumulative
|
||||||
|
calculation_ids:
|
||||||
|
- bento1-fresh-bentonite-consumption
|
||||||
|
- bento1-spreader3-consumption
|
||||||
|
speed:
|
||||||
|
signal_ref: fef41976-1103-4090-b780-eaeecc02fdfa
|
||||||
|
signal: Transport Auszug Geschwindigkeit Istwert
|
||||||
|
unit: m/min
|
||||||
|
production_gate_m_min: 0.3
|
||||||
|
```
|
||||||
|
|
||||||
|
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
|
||||||
|
modes, empty/duplicate calculation IDs, and invalid speed metadata are rejected.
|
||||||
|
No unrelated YAML configuration is loaded at runtime.
|
||||||
|
|
||||||
|
Inject already constructed services:
|
||||||
|
|
||||||
|
```python
|
||||||
|
machines = load_shift_report_machines("config/shift-report-machines.yaml")
|
||||||
|
service = ShiftReportService(
|
||||||
|
machines=machines,
|
||||||
|
production=production_service,
|
||||||
|
downtime=downtime_service,
|
||||||
|
materials=material_service,
|
||||||
|
channel_materials=channel_material_service,
|
||||||
|
speed=speed_service,
|
||||||
|
)
|
||||||
|
start, end = shift_report_window(day, "early")
|
||||||
|
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
|
||||||
|
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
|
||||||
|
calls. All source services retain their `[start, end)` semantics.
|
||||||
|
|
||||||
|
## Source 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`.
|
||||||
|
|
||||||
|
`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
|
||||||
|
production time. It is never named `production_time_seconds`. The report exposes
|
||||||
|
`downtime_event_count`, all `downtime_reasons`, and `top_downtime_reasons` (at most
|
||||||
|
three). Reason views retain the original immutable reason, including duration
|
||||||
|
and metadata; null/blank names get `Ohne Stillstandsgrund`. The existing summary
|
||||||
|
provides ranking and tie ordering. Overlapping reasons can have durations whose
|
||||||
|
sum exceeds total downtime.
|
||||||
|
|
||||||
|
B1 uses cumulative fresh-bentonite and spreader3 snapshot streams; K7 uses the
|
||||||
|
cumulative fiber stream. E1 uses channel snapshots, preserving extruder/channel,
|
||||||
|
material number/name/status, calculation ID, and source in each item. Existing
|
||||||
|
counter differencing, reset failure behavior, and sample-to-sample attribution
|
||||||
|
remain unchanged. Null material names remain null; no carry-forward or report
|
||||||
|
label invents an identity. ERP raw-material booking quantities are excluded
|
||||||
|
because their timing is not synchronized with physical shift consumption.
|
||||||
|
|
||||||
|
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
|
||||||
|
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.
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
# 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.
|
||||||
|
|
||||||
|
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`.
|
||||||
|
|
||||||
|
Window timestamps must be timezone aware and have positive elapsed duration.
|
||||||
|
All boundary comparisons use UTC instants, including DST folds.
|
||||||
|
|
||||||
|
## Configuration and service API
|
||||||
|
|
||||||
|
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`.
|
||||||
|
|
||||||
|
```python
|
||||||
|
from datetime import datetime
|
||||||
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
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")),
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
`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
|
||||||
|
|
||||||
|
For 2026-10-07 06:00–14:00 Europe/Berlin:
|
||||||
|
|
||||||
|
| Machine | Samples | Active samples | Active average (m/min) |
|
||||||
|
| --- | ---: | ---: | ---: |
|
||||||
|
| B1 | 2880 | 1603 | 2.3139663284001912 |
|
||||||
|
| 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.
|
||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
import yaml
|
import yaml
|
||||||
|
|
||||||
@@ -78,6 +79,7 @@ def load_channel_material_calculation(path: str | Path) -> ChannelMaterialCalcul
|
|||||||
"percentage_signal_ref",
|
"percentage_signal_ref",
|
||||||
"screw_speed_signal_ref",
|
"screw_speed_signal_ref",
|
||||||
"material_number_signal_ref",
|
"material_number_signal_ref",
|
||||||
|
"material_name_signal_ref",
|
||||||
}
|
}
|
||||||
if (
|
if (
|
||||||
not isinstance(row, dict)
|
not isinstance(row, dict)
|
||||||
@@ -99,6 +101,20 @@ def load_channel_material_calculation(path: str | Path) -> ChannelMaterialCalcul
|
|||||||
material = row.get("material_number_signal_ref")
|
material = row.get("material_number_signal_ref")
|
||||||
if material is not None and (not isinstance(material, str) or not material.strip()):
|
if material is not None and (not isinstance(material, str) or not material.strip()):
|
||||||
raise CalculationConfigError("material signal must be a string or null")
|
raise CalculationConfigError("material signal must be a string or null")
|
||||||
|
material_name = row.get("material_name_signal_ref")
|
||||||
|
if material_name is not None:
|
||||||
|
try:
|
||||||
|
if not isinstance(material_name, str) or not material_name.startswith("uuid:"):
|
||||||
|
raise ValueError("expected uuid:<UUID>")
|
||||||
|
UUID(material_name[5:])
|
||||||
|
except ValueError as exc:
|
||||||
|
raise CalculationConfigError(
|
||||||
|
"material_name_signal_ref must be uuid:<UUID> or null"
|
||||||
|
) from exc
|
||||||
|
if material is not None and material_name is not None:
|
||||||
|
raise CalculationConfigError(
|
||||||
|
"Material number and name signals are mutually exclusive"
|
||||||
|
)
|
||||||
channels.append(
|
channels.append(
|
||||||
ChannelDefinition(
|
ChannelDefinition(
|
||||||
extruder["id"],
|
extruder["id"],
|
||||||
@@ -108,6 +124,7 @@ def load_channel_material_calculation(path: str | Path) -> ChannelMaterialCalcul
|
|||||||
row["percentage_signal_ref"],
|
row["percentage_signal_ref"],
|
||||||
row["screw_speed_signal_ref"],
|
row["screw_speed_signal_ref"],
|
||||||
material,
|
material,
|
||||||
|
material_name,
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
if len({(c.extruder, c.channel) for c in channels}) != len(channels):
|
if len({(c.extruder, c.channel) for c in channels}) != len(channels):
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ class DosingChannelSample:
|
|||||||
dosing_percentage: float
|
dosing_percentage: float
|
||||||
screw_speed: float
|
screw_speed: float
|
||||||
material_number: str | None = None
|
material_number: str | None = None
|
||||||
|
material_name: str | None = None
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True, slots=True)
|
@dataclass(frozen=True, slots=True)
|
||||||
@@ -55,9 +56,10 @@ def channel_rates(
|
|||||||
) -> tuple[ChannelRate, ...]:
|
) -> tuple[ChannelRate, ...]:
|
||||||
"""Derive rates and conservative material identity for one aligned timestamp.
|
"""Derive rates and conservative material identity for one aligned timestamp.
|
||||||
|
|
||||||
A material value which occurs on more than one channel is deliberately not
|
A material number which occurs on more than one channel is deliberately not
|
||||||
attributed to either channel: PLC assignments are not reliable enough to
|
attributed to either channel: PLC assignments are not reliable enough to
|
||||||
resolve that ambiguity from a previous sample.
|
resolve that ambiguity from a previous sample. Direct per-channel names are
|
||||||
|
already assigned and may be shared by multiple channels.
|
||||||
"""
|
"""
|
||||||
values = tuple(samples)
|
values = tuple(samples)
|
||||||
validate_active_percentage_sum(values, tolerance=percentage_tolerance)
|
validate_active_percentage_sum(values, tolerance=percentage_tolerance)
|
||||||
@@ -71,7 +73,9 @@ def channel_rates(
|
|||||||
for value in values:
|
for value in values:
|
||||||
if not isfinite(value.total_rate_kg_per_hour) or not isfinite(value.screw_speed):
|
if not isfinite(value.total_rate_kg_per_hour) or not isfinite(value.screw_speed):
|
||||||
raise ValueError("total rate and screw speed must be finite")
|
raise ValueError("total rate and screw speed must be finite")
|
||||||
if value.material_number is None:
|
if value.material_name is not None and value.material_name.strip():
|
||||||
|
number, name, status = None, value.material_name, MATERIAL_ASSIGNED
|
||||||
|
elif value.material_number is None:
|
||||||
number, name, status = None, None, MATERIAL_UNAVAILABLE
|
number, name, status = None, None, MATERIAL_UNAVAILABLE
|
||||||
elif counts[value.material_number] > 1:
|
elif counts[value.material_number] > 1:
|
||||||
number, name, status = None, None, MATERIAL_AMBIGUOUS
|
number, name, status = None, None, MATERIAL_AMBIGUOUS
|
||||||
|
|||||||
@@ -0,0 +1,173 @@
|
|||||||
|
"""Machine-independent shift downtime from raw source intervals."""
|
||||||
|
|
||||||
|
from collections import defaultdict
|
||||||
|
from collections.abc import Iterable
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import UTC, datetime
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class ShiftDowntimeEvent:
|
||||||
|
external_id: str
|
||||||
|
machine_id: str
|
||||||
|
source_start: datetime
|
||||||
|
source_end: datetime | None
|
||||||
|
reason_id: str | None
|
||||||
|
reason_name: str | None
|
||||||
|
reason_description: str | None
|
||||||
|
reason_group: str | None
|
||||||
|
category: str | None
|
||||||
|
comment: str | None
|
||||||
|
|
||||||
|
def __post_init__(self) -> None:
|
||||||
|
for name in ("external_id", "machine_id"):
|
||||||
|
value = getattr(self, name)
|
||||||
|
if not isinstance(value, str) or not value.strip() or "\x00" in value:
|
||||||
|
raise ValueError(f"{name} must be a non-empty string without NUL bytes")
|
||||||
|
_aware(self.source_start, "source_start")
|
||||||
|
if self.source_end is not None:
|
||||||
|
_aware(self.source_end, "source_end")
|
||||||
|
if self.source_end.astimezone(UTC) < self.source_start.astimezone(UTC):
|
||||||
|
raise ValueError("source_end must not precede source_start")
|
||||||
|
for name in (
|
||||||
|
"reason_id",
|
||||||
|
"reason_name",
|
||||||
|
"reason_description",
|
||||||
|
"reason_group",
|
||||||
|
"category",
|
||||||
|
"comment",
|
||||||
|
):
|
||||||
|
value = getattr(self, name)
|
||||||
|
if value is not None and not isinstance(value, str):
|
||||||
|
raise ValueError(f"{name} must be a string or null")
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class ClippedShiftDowntimeEvent:
|
||||||
|
source: ShiftDowntimeEvent
|
||||||
|
start: datetime
|
||||||
|
end: datetime
|
||||||
|
duration_seconds: float
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class ShiftDowntimeReason:
|
||||||
|
reason_id: str | None
|
||||||
|
reason_name: str | None
|
||||||
|
reason_description: str | None
|
||||||
|
reason_group: str | None
|
||||||
|
category: str | None
|
||||||
|
duration_seconds: float
|
||||||
|
event_count: int
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class ShiftDowntimeSummary:
|
||||||
|
machine_id: str
|
||||||
|
start: datetime
|
||||||
|
end: datetime
|
||||||
|
shift_duration_seconds: float
|
||||||
|
total_downtime_seconds: float
|
||||||
|
non_downtime_seconds: float
|
||||||
|
events: tuple[ClippedShiftDowntimeEvent, ...]
|
||||||
|
reasons: tuple[ShiftDowntimeReason, ...]
|
||||||
|
|
||||||
|
|
||||||
|
def validate_downtime_window(*, machine_id: str, start: datetime, end: datetime) -> None:
|
||||||
|
if not isinstance(machine_id, str) or not machine_id.strip() or "\x00" in machine_id:
|
||||||
|
raise ValueError("machine_id must be a non-empty string without NUL bytes")
|
||||||
|
_aware(start, "start")
|
||||||
|
_aware(end, "end")
|
||||||
|
if end.astimezone(UTC) <= start.astimezone(UTC):
|
||||||
|
raise ValueError("end must follow start")
|
||||||
|
|
||||||
|
|
||||||
|
def aggregate_shift_downtime(
|
||||||
|
events: Iterable[ShiftDowntimeEvent], *, machine_id: str, start: datetime, end: datetime
|
||||||
|
) -> ShiftDowntimeSummary:
|
||||||
|
"""Clip source intervals to [start, end); open events end at the shift end.
|
||||||
|
|
||||||
|
Total downtime is the union of intervals. Each reason also uses a union within
|
||||||
|
its full metadata group. Different reasons may overlap, so their durations need
|
||||||
|
not sum to total downtime. Non-downtime is a time complement, not measured output.
|
||||||
|
No production-order attribution fields participate in this calculation.
|
||||||
|
"""
|
||||||
|
validate_downtime_window(machine_id=machine_id, start=start, end=end)
|
||||||
|
lower, upper = start.astimezone(UTC), end.astimezone(UTC)
|
||||||
|
clipped = []
|
||||||
|
for event in events:
|
||||||
|
if event.machine_id != machine_id:
|
||||||
|
continue
|
||||||
|
event_start = event.source_start.astimezone(UTC)
|
||||||
|
event_end = upper if event.source_end is None else event.source_end.astimezone(UTC)
|
||||||
|
if event_start >= upper or event_end <= lower:
|
||||||
|
continue
|
||||||
|
clipped_start = start if event_start < lower else event.source_start
|
||||||
|
clipped_end = end if event.source_end is None or event_end > upper else event.source_end
|
||||||
|
duration = (clipped_end.astimezone(UTC) - clipped_start.astimezone(UTC)).total_seconds()
|
||||||
|
if duration > 0:
|
||||||
|
clipped.append(ClippedShiftDowntimeEvent(event, clipped_start, clipped_end, duration))
|
||||||
|
clipped.sort(key=lambda value: (value.start.astimezone(UTC), value.source.external_id))
|
||||||
|
groups = defaultdict(list)
|
||||||
|
for value in clipped:
|
||||||
|
source = value.source
|
||||||
|
groups[
|
||||||
|
(
|
||||||
|
source.reason_id,
|
||||||
|
source.reason_name,
|
||||||
|
source.reason_description,
|
||||||
|
source.reason_group,
|
||||||
|
source.category,
|
||||||
|
)
|
||||||
|
].append(value)
|
||||||
|
reasons = [
|
||||||
|
ShiftDowntimeReason(*key, _union_seconds(values), len(values))
|
||||||
|
for key, values in groups.items()
|
||||||
|
]
|
||||||
|
reasons.sort(
|
||||||
|
key=lambda value: (
|
||||||
|
-value.duration_seconds,
|
||||||
|
tuple(
|
||||||
|
(field is not None, field or "")
|
||||||
|
for field in (
|
||||||
|
value.reason_id,
|
||||||
|
value.reason_name,
|
||||||
|
value.reason_description,
|
||||||
|
value.reason_group,
|
||||||
|
value.category,
|
||||||
|
)
|
||||||
|
),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
shift_seconds = (upper - lower).total_seconds()
|
||||||
|
downtime_seconds = _union_seconds(clipped)
|
||||||
|
return ShiftDowntimeSummary(
|
||||||
|
machine_id=machine_id,
|
||||||
|
start=start,
|
||||||
|
end=end,
|
||||||
|
shift_duration_seconds=shift_seconds,
|
||||||
|
total_downtime_seconds=downtime_seconds,
|
||||||
|
non_downtime_seconds=max(0.0, shift_seconds - downtime_seconds),
|
||||||
|
events=tuple(clipped),
|
||||||
|
reasons=tuple(reasons),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _union_seconds(events: Iterable[ClippedShiftDowntimeEvent]) -> float:
|
||||||
|
intervals = sorted((event.start.astimezone(UTC), event.end.astimezone(UTC)) for event in events)
|
||||||
|
if not intervals:
|
||||||
|
return 0.0
|
||||||
|
start, end = intervals[0]
|
||||||
|
total = 0.0
|
||||||
|
for next_start, next_end in intervals[1:]:
|
||||||
|
if next_start <= end:
|
||||||
|
end = max(end, next_end)
|
||||||
|
else:
|
||||||
|
total += (end - start).total_seconds()
|
||||||
|
start, end = next_start, next_end
|
||||||
|
return total + (end - start).total_seconds()
|
||||||
|
|
||||||
|
|
||||||
|
def _aware(value: datetime, name: str) -> None:
|
||||||
|
if not isinstance(value, datetime) or value.tzinfo is None or value.utcoffset() is None:
|
||||||
|
raise ValueError(f"{name} must be a timezone-aware datetime")
|
||||||
@@ -0,0 +1,304 @@
|
|||||||
|
"""Shift deltas from cumulative counters; no material identity is inferred."""
|
||||||
|
|
||||||
|
from collections import defaultdict
|
||||||
|
from collections.abc import Iterable
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import UTC, datetime
|
||||||
|
from math import fsum, isfinite
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class ShiftMaterialSnapshot:
|
||||||
|
timestamp: datetime
|
||||||
|
calculation_id: str
|
||||||
|
machine_id: str
|
||||||
|
production_order: str
|
||||||
|
run_id: str
|
||||||
|
consumption_kg: float | None
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class ShiftChannelMaterialSnapshot:
|
||||||
|
timestamp: datetime
|
||||||
|
calculation_id: str
|
||||||
|
machine_id: str
|
||||||
|
extruder: str
|
||||||
|
doser_channel: str
|
||||||
|
production_order: str
|
||||||
|
run_id: str
|
||||||
|
cumulative_consumption_kg: float | None
|
||||||
|
material_number: str | None
|
||||||
|
material_name: str | None
|
||||||
|
material_mapping_status: str
|
||||||
|
percentage_sum_valid: bool
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class ShiftMaterialItem:
|
||||||
|
source: str
|
||||||
|
calculation_id: str
|
||||||
|
machine_id: str
|
||||||
|
production_order: str
|
||||||
|
run_id: str
|
||||||
|
consumption_kg: float
|
||||||
|
baseline_timestamp: datetime
|
||||||
|
end_timestamp: datetime
|
||||||
|
baseline_missing: bool
|
||||||
|
extruder: str | None = None
|
||||||
|
doser_channel: str | None = None
|
||||||
|
material_number: str | None = None
|
||||||
|
material_name: str | None = None
|
||||||
|
material_mapping_status: str | None = None
|
||||||
|
percentage_sum_valid: bool | None = None
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class ShiftMaterialSummary:
|
||||||
|
machine_id: str
|
||||||
|
start: datetime
|
||||||
|
end: datetime
|
||||||
|
total_consumption_kg: float
|
||||||
|
items: tuple[ShiftMaterialItem, ...]
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(slots=True)
|
||||||
|
class _ChannelSegment:
|
||||||
|
identity: tuple[str | None, str | None, str]
|
||||||
|
first: ShiftChannelMaterialSnapshot
|
||||||
|
last: ShiftChannelMaterialSnapshot
|
||||||
|
deltas: list[float]
|
||||||
|
quality: bool
|
||||||
|
|
||||||
|
|
||||||
|
def validate_material_window(
|
||||||
|
*, machine_id: str, calculation_ids: tuple[str, ...], start: datetime, end: datetime
|
||||||
|
) -> None:
|
||||||
|
_identifier(machine_id, "machine_id")
|
||||||
|
if not isinstance(calculation_ids, tuple) or not calculation_ids:
|
||||||
|
raise ValueError("calculation_ids must be a non-empty tuple")
|
||||||
|
for calculation_id in calculation_ids:
|
||||||
|
_identifier(calculation_id, "calculation_id")
|
||||||
|
if len(set(calculation_ids)) != len(calculation_ids):
|
||||||
|
raise ValueError("calculation_ids must be unique")
|
||||||
|
if _instant(end) <= _instant(start):
|
||||||
|
raise ValueError("end must follow start")
|
||||||
|
|
||||||
|
|
||||||
|
def aggregate_shift_material(
|
||||||
|
snapshots: Iterable[ShiftMaterialSnapshot],
|
||||||
|
*,
|
||||||
|
machine_id: str,
|
||||||
|
calculation_ids: tuple[str, ...],
|
||||||
|
start: datetime,
|
||||||
|
end: datetime,
|
||||||
|
include_zero: bool = True,
|
||||||
|
) -> ShiftMaterialSummary:
|
||||||
|
"""Difference each observed run independently, never counters from different runs.
|
||||||
|
|
||||||
|
Use the last valid sample at/before start and samples strictly before end.
|
||||||
|
If a run has no baseline at/before start, its first observed sample establishes
|
||||||
|
a baseline (baseline_missing=True); its existing counter is never counted.
|
||||||
|
Null/non-finite counters are not valid samples and are skipped. Negative
|
||||||
|
counters are rejected. A lone baseline produces a diagnostic zero item; it
|
||||||
|
makes no claim about source freshness or completeness.
|
||||||
|
There is no interpolation or extrapolation at either boundary. Any within-run
|
||||||
|
decrease raises ValueError, even if the final counter exceeds the baseline.
|
||||||
|
"""
|
||||||
|
validate_material_window(
|
||||||
|
machine_id=machine_id, calculation_ids=calculation_ids, start=start, end=end
|
||||||
|
)
|
||||||
|
streams = defaultdict(list)
|
||||||
|
for row in snapshots:
|
||||||
|
if row.machine_id == machine_id and row.calculation_id in calculation_ids:
|
||||||
|
if _instant(row.timestamp) < _instant(end):
|
||||||
|
streams[(row.calculation_id,)].append(row)
|
||||||
|
items = []
|
||||||
|
for rows in streams.values():
|
||||||
|
for run in _runs(rows, start, channel=False):
|
||||||
|
first, last = run[0], run[-1]
|
||||||
|
_check_deltas(run, channel=False)
|
||||||
|
items.append(
|
||||||
|
ShiftMaterialItem(
|
||||||
|
source="material_consumption_snapshots",
|
||||||
|
calculation_id=first.calculation_id,
|
||||||
|
machine_id=machine_id,
|
||||||
|
production_order=first.production_order,
|
||||||
|
run_id=first.run_id,
|
||||||
|
consumption_kg=last.consumption_kg - first.consumption_kg,
|
||||||
|
baseline_timestamp=first.timestamp,
|
||||||
|
end_timestamp=last.timestamp,
|
||||||
|
baseline_missing=_instant(first.timestamp) > _instant(start),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return _summary(items, machine_id, start, end, include_zero)
|
||||||
|
|
||||||
|
|
||||||
|
def aggregate_shift_channel_material(
|
||||||
|
snapshots: Iterable[ShiftChannelMaterialSnapshot],
|
||||||
|
*,
|
||||||
|
machine_id: str,
|
||||||
|
calculation_ids: tuple[str, ...],
|
||||||
|
start: datetime,
|
||||||
|
end: datetime,
|
||||||
|
include_zero: bool = True,
|
||||||
|
) -> ShiftMaterialSummary:
|
||||||
|
"""For A -> B, attribute B.counter - A.counter to B's stored material identity.
|
||||||
|
|
||||||
|
Null/blank names remain null: no last-known carry-forward. Consecutive intervals
|
||||||
|
with the same number/name/status form one material segment. A -> null -> A
|
||||||
|
remains three segments. Counters and run boundaries follow the generic rules.
|
||||||
|
"""
|
||||||
|
validate_material_window(
|
||||||
|
machine_id=machine_id, calculation_ids=calculation_ids, start=start, end=end
|
||||||
|
)
|
||||||
|
streams = defaultdict(list)
|
||||||
|
for row in snapshots:
|
||||||
|
if row.machine_id == machine_id and row.calculation_id in calculation_ids:
|
||||||
|
if _instant(row.timestamp) < _instant(end):
|
||||||
|
streams[(row.calculation_id, row.extruder, row.doser_channel)].append(row)
|
||||||
|
items = []
|
||||||
|
for rows in streams.values():
|
||||||
|
for run in _runs(rows, start, channel=True):
|
||||||
|
_check_deltas(run, channel=True)
|
||||||
|
missing = _instant(run[0].timestamp) > _instant(start)
|
||||||
|
intervals = list(zip(run, run[1:])) or [(run[0], run[0])]
|
||||||
|
segments = []
|
||||||
|
for previous, current in intervals:
|
||||||
|
identity = _identity(current)
|
||||||
|
delta = current.cumulative_consumption_kg - previous.cumulative_consumption_kg
|
||||||
|
if segments and segments[-1].identity == identity:
|
||||||
|
segment = segments[-1]
|
||||||
|
segment.last = current
|
||||||
|
segment.deltas.append(delta)
|
||||||
|
segment.quality = segment.quality and current.percentage_sum_valid
|
||||||
|
else:
|
||||||
|
segments.append(
|
||||||
|
_ChannelSegment(
|
||||||
|
identity, previous, current, [delta], current.percentage_sum_valid
|
||||||
|
)
|
||||||
|
)
|
||||||
|
for segment in segments:
|
||||||
|
number, name, status = segment.identity
|
||||||
|
first, last = segment.first, segment.last
|
||||||
|
items.append(
|
||||||
|
ShiftMaterialItem(
|
||||||
|
source="channel_material_consumption_snapshots",
|
||||||
|
calculation_id=first.calculation_id,
|
||||||
|
machine_id=machine_id,
|
||||||
|
production_order=first.production_order,
|
||||||
|
run_id=first.run_id,
|
||||||
|
consumption_kg=fsum(segment.deltas),
|
||||||
|
baseline_timestamp=first.timestamp,
|
||||||
|
end_timestamp=last.timestamp,
|
||||||
|
baseline_missing=missing,
|
||||||
|
extruder=first.extruder,
|
||||||
|
doser_channel=first.doser_channel,
|
||||||
|
material_number=number,
|
||||||
|
material_name=name,
|
||||||
|
material_mapping_status=status,
|
||||||
|
percentage_sum_valid=segment.quality,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return _summary(items, machine_id, start, end, include_zero)
|
||||||
|
|
||||||
|
|
||||||
|
def _runs(rows, start, *, channel):
|
||||||
|
ordered = sorted(rows, key=lambda row: _instant(row.timestamp))
|
||||||
|
if any(_instant(a.timestamp) == _instant(b.timestamp) for a, b in zip(ordered, ordered[1:])):
|
||||||
|
raise ValueError("Ambiguous snapshots at the same stream timestamp")
|
||||||
|
# Invalid counters still establish run boundaries. Retain the active run's
|
||||||
|
# history until its valid baseline has been selected below.
|
||||||
|
before = [i for i, row in enumerate(ordered) if _instant(row.timestamp) <= _instant(start)]
|
||||||
|
active = before[-1] if before else 0
|
||||||
|
while active > 0 and ordered[active - 1].run_id == ordered[active].run_id:
|
||||||
|
active -= 1
|
||||||
|
selected = ordered[active:]
|
||||||
|
runs = []
|
||||||
|
seen = set()
|
||||||
|
for row in selected:
|
||||||
|
_identifier(row.run_id, "run_id")
|
||||||
|
_identifier(row.production_order, "production_order")
|
||||||
|
if not runs or runs[-1][-1].run_id != row.run_id:
|
||||||
|
if row.run_id in seen:
|
||||||
|
raise ValueError("Run reappeared after a different run in the same stream")
|
||||||
|
seen.add(row.run_id)
|
||||||
|
runs.append([])
|
||||||
|
if runs[-1] and runs[-1][-1].production_order != row.production_order:
|
||||||
|
raise ValueError("Production order changed within a run")
|
||||||
|
runs[-1].append(row)
|
||||||
|
for run in runs:
|
||||||
|
valid = [
|
||||||
|
row for row in run
|
||||||
|
if _valid_counter(row.cumulative_consumption_kg if channel else row.consumption_kg)
|
||||||
|
]
|
||||||
|
baseline = [row for row in valid if _instant(row.timestamp) <= _instant(start)]
|
||||||
|
selected = baseline[-1:] + [
|
||||||
|
row for row in valid if _instant(row.timestamp) > _instant(start)
|
||||||
|
]
|
||||||
|
if selected:
|
||||||
|
yield selected
|
||||||
|
|
||||||
|
|
||||||
|
def _check_deltas(run, *, channel):
|
||||||
|
for previous, current in zip(run, run[1:]):
|
||||||
|
a = previous.cumulative_consumption_kg if channel else previous.consumption_kg
|
||||||
|
b = current.cumulative_consumption_kg if channel else current.consumption_kg
|
||||||
|
if b < a:
|
||||||
|
raise ValueError("Cumulative counter decreased/reset within a run")
|
||||||
|
|
||||||
|
|
||||||
|
def _identity(row: ShiftChannelMaterialSnapshot) -> tuple[str | None, str | None, str]:
|
||||||
|
number = _label(row.material_number)
|
||||||
|
name = _label(row.material_name)
|
||||||
|
status = (
|
||||||
|
row.material_mapping_status if number is not None or name is not None else "UNAVAILABLE"
|
||||||
|
)
|
||||||
|
return number, name, status
|
||||||
|
|
||||||
|
|
||||||
|
def _label(value: str | None) -> str | None:
|
||||||
|
if value is not None and not isinstance(value, str):
|
||||||
|
raise ValueError("Material labels must be strings or null")
|
||||||
|
return value.strip() or None if value is not None else None
|
||||||
|
|
||||||
|
|
||||||
|
def _valid_counter(value: float | None) -> bool:
|
||||||
|
if value is None:
|
||||||
|
return False
|
||||||
|
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
||||||
|
raise ValueError("Cumulative counter must be numeric or null")
|
||||||
|
if not isfinite(value):
|
||||||
|
return False
|
||||||
|
if value < 0:
|
||||||
|
raise ValueError("Cumulative counter must be non-negative")
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def _summary(items, machine_id, start, end, include_zero):
|
||||||
|
items = [item for item in items if include_zero or item.consumption_kg != 0]
|
||||||
|
items.sort(
|
||||||
|
key=lambda item: (
|
||||||
|
item.calculation_id,
|
||||||
|
item.extruder or "",
|
||||||
|
item.doser_channel or "",
|
||||||
|
_instant(item.baseline_timestamp),
|
||||||
|
item.run_id,
|
||||||
|
item.production_order,
|
||||||
|
item.material_number or "",
|
||||||
|
item.material_name or "",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return ShiftMaterialSummary(
|
||||||
|
machine_id, start, end, fsum(item.consumption_kg for item in items), tuple(items)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _instant(value: datetime) -> datetime:
|
||||||
|
if not isinstance(value, datetime) or value.tzinfo is None or value.utcoffset() is None:
|
||||||
|
raise ValueError("Snapshot and window timestamps must be timezone-aware")
|
||||||
|
return value.astimezone(UTC)
|
||||||
|
|
||||||
|
|
||||||
|
def _identifier(value: str, name: str) -> None:
|
||||||
|
if not isinstance(value, str) or not value.strip() or "\x00" in value:
|
||||||
|
raise ValueError(f"{name} must be a non-empty string without NUL bytes")
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
"""Pure finished-production aggregation for an explicit workplace and shift window."""
|
||||||
|
|
||||||
|
from collections import defaultdict
|
||||||
|
from collections.abc import Iterable
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import datetime
|
||||||
|
from math import fsum, isfinite
|
||||||
|
|
||||||
|
from production_analytics.erp import ProductionConfirmation
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class ShiftProductionItem:
|
||||||
|
production_order: str
|
||||||
|
article_number: str | None
|
||||||
|
article_description: str | None
|
||||||
|
produced_m2: float
|
||||||
|
roll_count: int
|
||||||
|
first_confirmation_at: datetime
|
||||||
|
last_confirmation_at: datetime
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class ShiftProductionSummary:
|
||||||
|
start: datetime
|
||||||
|
end: datetime
|
||||||
|
workplace: str
|
||||||
|
total_produced_m2: float
|
||||||
|
total_roll_count: int
|
||||||
|
items: tuple[ShiftProductionItem, ...]
|
||||||
|
|
||||||
|
|
||||||
|
def validate_shift_window(*, workplace: str, start: datetime, end: datetime) -> str:
|
||||||
|
"""Validate inputs and return the exact workplace with surrounding padding removed."""
|
||||||
|
if not isinstance(workplace, str) or not workplace.strip() or "\x00" in workplace:
|
||||||
|
raise ValueError("workplace must be a non-empty string without NUL bytes")
|
||||||
|
_aware(start, "start")
|
||||||
|
_aware(end, "end")
|
||||||
|
# Compare instants, including distinct folds of the same local DST hour.
|
||||||
|
if end.timestamp() <= start.timestamp():
|
||||||
|
raise ValueError("end must follow start")
|
||||||
|
return workplace.strip()
|
||||||
|
|
||||||
|
|
||||||
|
def aggregate_shift_production(
|
||||||
|
confirmations: Iterable[ProductionConfirmation],
|
||||||
|
*,
|
||||||
|
workplace: str,
|
||||||
|
start: datetime,
|
||||||
|
end: datetime,
|
||||||
|
) -> ShiftProductionSummary:
|
||||||
|
"""Sum positive ERP feedback in [start, end), preserving supplied timezones.
|
||||||
|
|
||||||
|
Only rows for the exact workplace and window contribute. Every finished-goods
|
||||||
|
row contributes its feedback m²; only roll counts are deduplicated, within each
|
||||||
|
order/article/description group. Missing or blank roll numbers count as no roll.
|
||||||
|
"""
|
||||||
|
workplace = validate_shift_window(workplace=workplace, start=start, end=end)
|
||||||
|
groups: dict[tuple[str, str | None, str | None], list[ProductionConfirmation]] = defaultdict(
|
||||||
|
list
|
||||||
|
)
|
||||||
|
for confirmation in confirmations:
|
||||||
|
_aware(confirmation.timestamp, "confirmation timestamp")
|
||||||
|
if confirmation.workplace != workplace or not (
|
||||||
|
start.timestamp() <= confirmation.timestamp.timestamp() < end.timestamp()
|
||||||
|
):
|
||||||
|
continue
|
||||||
|
quantity = confirmation.feedback_quantity_m2
|
||||||
|
if quantity is not None and (isinstance(quantity, bool) or not isfinite(quantity)):
|
||||||
|
raise ValueError("feedback quantity must be finite")
|
||||||
|
if not confirmation.is_finished_goods:
|
||||||
|
continue
|
||||||
|
groups[
|
||||||
|
(
|
||||||
|
confirmation.production_order,
|
||||||
|
confirmation.article_number,
|
||||||
|
confirmation.article_description,
|
||||||
|
)
|
||||||
|
].append(confirmation)
|
||||||
|
items = []
|
||||||
|
for (order, article, description), rows in groups.items():
|
||||||
|
produced = fsum(row.feedback_quantity_m2 for row in rows)
|
||||||
|
if not isfinite(produced):
|
||||||
|
raise ValueError("produced quantity must be finite")
|
||||||
|
items.append(
|
||||||
|
ShiftProductionItem(
|
||||||
|
production_order=order,
|
||||||
|
article_number=article,
|
||||||
|
article_description=description,
|
||||||
|
produced_m2=produced,
|
||||||
|
roll_count=len(
|
||||||
|
{
|
||||||
|
row.roll_number.strip()
|
||||||
|
for row in rows
|
||||||
|
if row.roll_number is not None and row.roll_number.strip()
|
||||||
|
}
|
||||||
|
),
|
||||||
|
first_confirmation_at=min(
|
||||||
|
rows, key=lambda row: row.timestamp.timestamp()
|
||||||
|
).timestamp,
|
||||||
|
last_confirmation_at=max(rows, key=lambda row: row.timestamp.timestamp()).timestamp,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
items.sort(
|
||||||
|
key=lambda item: (
|
||||||
|
item.first_confirmation_at.timestamp(),
|
||||||
|
item.production_order,
|
||||||
|
(item.article_number is not None, item.article_number or ""),
|
||||||
|
(item.article_description is not None, item.article_description or ""),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return ShiftProductionSummary(
|
||||||
|
start=start,
|
||||||
|
end=end,
|
||||||
|
workplace=workplace,
|
||||||
|
total_produced_m2=fsum(item.produced_m2 for item in items),
|
||||||
|
total_roll_count=sum(item.roll_count for item in items),
|
||||||
|
items=tuple(items),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _aware(value: datetime, name: str) -> None:
|
||||||
|
if not isinstance(value, datetime) or value.tzinfo is None or value.utcoffset() is None:
|
||||||
|
raise ValueError(f"{name} must be a timezone-aware datetime")
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
"""Immutable shift-report composition models, independent of output format."""
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import date, datetime, time, timedelta
|
||||||
|
from typing import Literal
|
||||||
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
|
from production_analytics.calculations.shift_downtime import (
|
||||||
|
ShiftDowntimeReason,
|
||||||
|
ShiftDowntimeSummary,
|
||||||
|
)
|
||||||
|
from production_analytics.calculations.shift_material import ShiftMaterialSummary
|
||||||
|
from production_analytics.calculations.shift_production import ShiftProductionSummary
|
||||||
|
from production_analytics.calculations.shift_speed import ShiftSpeedSummary
|
||||||
|
|
||||||
|
SHIFT_TIMEZONE = ZoneInfo("Europe/Berlin")
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class ShiftReportDowntimeReason:
|
||||||
|
reason: ShiftDowntimeReason
|
||||||
|
display_name: str
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class ShiftReport:
|
||||||
|
machine_name: str
|
||||||
|
machine_id: str
|
||||||
|
start: datetime
|
||||||
|
end: datetime
|
||||||
|
production: ShiftProductionSummary
|
||||||
|
downtime: ShiftDowntimeSummary
|
||||||
|
materials: ShiftMaterialSummary
|
||||||
|
speed: ShiftSpeedSummary
|
||||||
|
|
||||||
|
@property
|
||||||
|
def downtime_event_count(self) -> int:
|
||||||
|
return len(self.downtime.events)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def downtime_reasons(self) -> tuple[ShiftReportDowntimeReason, ...]:
|
||||||
|
return tuple(
|
||||||
|
ShiftReportDowntimeReason(
|
||||||
|
reason=reason,
|
||||||
|
display_name=reason.reason_name
|
||||||
|
if reason.reason_name and reason.reason_name.strip()
|
||||||
|
else "Ohne Stillstandsgrund",
|
||||||
|
)
|
||||||
|
for reason in self.downtime.reasons
|
||||||
|
)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def top_downtime_reasons(self) -> tuple[ShiftReportDowntimeReason, ...]:
|
||||||
|
# Preserve the source summary's validated duration ranking and tie order.
|
||||||
|
return self.downtime_reasons[:3]
|
||||||
|
|
||||||
|
|
||||||
|
def shift_report_window(
|
||||||
|
day: date, shift: Literal["early", "late", "night"],
|
||||||
|
) -> tuple[datetime, datetime]:
|
||||||
|
"""Berlin wall-clock shifts; day denotes the shift's start date.
|
||||||
|
|
||||||
|
A night shift ends on the following calendar day, so elapsed duration may
|
||||||
|
be seven or nine hours across DST. No fixed-duration arithmetic is used.
|
||||||
|
"""
|
||||||
|
if not isinstance(day, date) or isinstance(day, datetime):
|
||||||
|
raise ValueError("day must be a calendar date")
|
||||||
|
hours = {"early": (6, 14), "late": (14, 22), "night": (22, 6)}
|
||||||
|
if shift not in hours:
|
||||||
|
raise ValueError("shift must be early, late, or night")
|
||||||
|
start_hour, end_hour = hours[shift]
|
||||||
|
end_day = day + timedelta(days=1) if shift == "night" else day
|
||||||
|
return (
|
||||||
|
datetime.combine(day, time(start_hour), tzinfo=SHIFT_TIMEZONE),
|
||||||
|
datetime.combine(end_day, time(end_hour), tzinfo=SHIFT_TIMEZONE),
|
||||||
|
)
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
"""Arithmetic sample mean of line speed while running, without time weighting."""
|
||||||
|
|
||||||
|
from collections.abc import Iterable
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import UTC, datetime
|
||||||
|
from math import isfinite
|
||||||
|
from statistics import mean
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class ShiftSpeedConfig:
|
||||||
|
machine_id: str
|
||||||
|
speed_signal_ref: str
|
||||||
|
production_gate_m_min: float
|
||||||
|
unit: str = "m/min"
|
||||||
|
signal: str = ""
|
||||||
|
|
||||||
|
def __post_init__(self) -> None:
|
||||||
|
for name in ("machine_id", "speed_signal_ref"):
|
||||||
|
value = getattr(self, name)
|
||||||
|
if not isinstance(value, str) or not value.strip() or "\x00" in value:
|
||||||
|
raise ValueError(f"{name} must be a non-empty string without NUL bytes")
|
||||||
|
gate = finite_speed(self.production_gate_m_min)
|
||||||
|
if gate is None or gate < 0:
|
||||||
|
raise ValueError("production_gate_m_min must be finite and non-negative")
|
||||||
|
if self.unit != "m/min":
|
||||||
|
raise ValueError("Shift speed requires unit m/min")
|
||||||
|
if not isinstance(self.signal, str):
|
||||||
|
raise ValueError("signal must be a string")
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class ShiftSpeedSample:
|
||||||
|
timestamp: datetime | None
|
||||||
|
value: object
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class ShiftSpeedSummary:
|
||||||
|
machine_id: str
|
||||||
|
start: datetime
|
||||||
|
end: datetime
|
||||||
|
speed_signal_ref: str
|
||||||
|
unit: str
|
||||||
|
production_gate_m_min: float
|
||||||
|
sample_count: int
|
||||||
|
active_sample_count: int
|
||||||
|
inactive_sample_count: int
|
||||||
|
average_line_speed_m_min: float | None
|
||||||
|
minimum_active_speed_m_min: float | None
|
||||||
|
maximum_active_speed_m_min: float | None
|
||||||
|
invalid_sample_count: int
|
||||||
|
|
||||||
|
|
||||||
|
def validate_speed_window(start: datetime, end: datetime) -> None:
|
||||||
|
if _instant(end) <= _instant(start):
|
||||||
|
raise ValueError("end must follow start")
|
||||||
|
|
||||||
|
|
||||||
|
def aggregate_shift_speed(
|
||||||
|
samples: Iterable[ShiftSpeedSample], *, config: ShiftSpeedConfig,
|
||||||
|
start: datetime, end: datetime,
|
||||||
|
) -> ShiftSpeedSummary:
|
||||||
|
"""Count finite in-window samples; active iff value is strictly above gate.
|
||||||
|
|
||||||
|
sample_count = active_sample_count + inactive_sample_count. Invalid values
|
||||||
|
are counted separately, never converted to zero. Out-of-window samples are
|
||||||
|
ignored. Missing/invalid timestamps are unavailable and counted as invalid.
|
||||||
|
Each active sample has equal weight; this is not a full-shift/time mean.
|
||||||
|
"""
|
||||||
|
validate_speed_window(start, end)
|
||||||
|
first, last = _instant(start), _instant(end)
|
||||||
|
active = []
|
||||||
|
count = invalid = 0
|
||||||
|
for sample in samples:
|
||||||
|
try:
|
||||||
|
timestamp = _instant(sample.timestamp)
|
||||||
|
except ValueError:
|
||||||
|
invalid += 1
|
||||||
|
continue
|
||||||
|
if not first <= timestamp < last:
|
||||||
|
continue
|
||||||
|
value = finite_speed(sample.value)
|
||||||
|
if value is None:
|
||||||
|
invalid += 1
|
||||||
|
continue
|
||||||
|
count += 1
|
||||||
|
if value > config.production_gate_m_min:
|
||||||
|
active.append(value)
|
||||||
|
return ShiftSpeedSummary(
|
||||||
|
machine_id=config.machine_id, start=start, end=end,
|
||||||
|
speed_signal_ref=config.speed_signal_ref, unit=config.unit,
|
||||||
|
production_gate_m_min=config.production_gate_m_min,
|
||||||
|
sample_count=count, active_sample_count=len(active),
|
||||||
|
inactive_sample_count=count - len(active),
|
||||||
|
average_line_speed_m_min=mean(active) if active else None,
|
||||||
|
minimum_active_speed_m_min=min(active) if active else None,
|
||||||
|
maximum_active_speed_m_min=max(active) if active else None,
|
||||||
|
invalid_sample_count=invalid,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def finite_speed(value: object) -> float | None:
|
||||||
|
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
number = float(value)
|
||||||
|
except (ValueError, OverflowError):
|
||||||
|
return None
|
||||||
|
return number if isfinite(number) else None
|
||||||
|
|
||||||
|
|
||||||
|
def _instant(value: datetime | None) -> datetime:
|
||||||
|
if not isinstance(value, datetime) or value.tzinfo is None or value.utcoffset() is None:
|
||||||
|
raise ValueError("Shift speed timestamps must be timezone-aware")
|
||||||
|
return value.astimezone(UTC)
|
||||||
@@ -4,6 +4,7 @@ from dataclasses import dataclass
|
|||||||
from datetime import UTC, datetime
|
from datetime import UTC, datetime
|
||||||
from math import isfinite
|
from math import isfinite
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
from production_analytics.calculations.channel_material import DosingChannelSample
|
from production_analytics.calculations.channel_material import DosingChannelSample
|
||||||
from production_analytics.calculations.material_consumption import (
|
from production_analytics.calculations.material_consumption import (
|
||||||
@@ -11,6 +12,7 @@ from production_analytics.calculations.material_consumption import (
|
|||||||
area_application_rate_kg_per_hour,
|
area_application_rate_kg_per_hour,
|
||||||
rotational_discharge_rate_kg_per_hour,
|
rotational_discharge_rate_kg_per_hour,
|
||||||
)
|
)
|
||||||
|
from production_analytics.calculations.shift_speed import ShiftSpeedSample, validate_speed_window
|
||||||
from production_analytics.enlyze.exploration import ExplorationClient
|
from production_analytics.enlyze.exploration import ExplorationClient
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
@@ -152,6 +154,63 @@ class EnlyzeApiGateway:
|
|||||||
except (KeyError, TypeError, ValueError) as exc:
|
except (KeyError, TypeError, ValueError) as exc:
|
||||||
raise ValueError(f"Invalid downtime response on page {page}: {exc}") from exc
|
raise ValueError(f"Invalid downtime response on page {page}: {exc}") from exc
|
||||||
|
|
||||||
|
def get_speed_samples(
|
||||||
|
self, *, machine_id: str, speed_signal_ref: str, start: datetime, end: datetime,
|
||||||
|
) -> list[ShiftSpeedSample]:
|
||||||
|
"""Retrieve one bounded signal using the existing timeseries cursor contract.
|
||||||
|
|
||||||
|
Invalid/missing sample values remain unavailable for domain aggregation.
|
||||||
|
Malformed timestamps/rows become invalid samples, while structural response
|
||||||
|
and pagination errors still fail the read instead of returning partial KPIs.
|
||||||
|
"""
|
||||||
|
validate_speed_window(start, end)
|
||||||
|
for name, value in (("machine_id", machine_id), ("speed_signal_ref", speed_signal_ref)):
|
||||||
|
if not isinstance(value, str) or not value.strip() or "\x00" in value:
|
||||||
|
raise ValueError(f"{name} must be a non-empty string without NUL bytes")
|
||||||
|
body = {
|
||||||
|
"machine": machine_id,
|
||||||
|
"start": start.astimezone(UTC).isoformat(),
|
||||||
|
"end": end.astimezone(UTC).isoformat(),
|
||||||
|
"variables": [{"uuid": speed_signal_ref}],
|
||||||
|
}
|
||||||
|
samples = []
|
||||||
|
cursors: set[str] = set()
|
||||||
|
page = 1
|
||||||
|
while True:
|
||||||
|
response = self._client.post_json("/v2/timeseries", body)
|
||||||
|
try:
|
||||||
|
data = response.body["data"]
|
||||||
|
columns = data["columns"]
|
||||||
|
if not isinstance(columns, list) or any(
|
||||||
|
columns.count(column) != 1 for column in ("time", speed_signal_ref)
|
||||||
|
):
|
||||||
|
raise ValueError("required columns must occur exactly once")
|
||||||
|
records = data["records"]
|
||||||
|
if not isinstance(records, list):
|
||||||
|
raise ValueError("records must be a list")
|
||||||
|
time_index, speed_index = columns.index("time"), columns.index(speed_signal_ref)
|
||||||
|
for record in records:
|
||||||
|
if not isinstance(record, list) or len(record) != len(columns):
|
||||||
|
samples.append(ShiftSpeedSample(None, None))
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
timestamp = _parse_timestamp(record[time_index])
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
timestamp = None
|
||||||
|
samples.append(ShiftSpeedSample(timestamp, record[speed_index]))
|
||||||
|
cursor = _next_cursor(response.body)
|
||||||
|
if cursor is None:
|
||||||
|
return samples
|
||||||
|
if cursor in cursors:
|
||||||
|
raise ValueError("next_cursor has already been followed")
|
||||||
|
cursors.add(cursor)
|
||||||
|
body = {**body, "cursor": cursor}
|
||||||
|
page += 1
|
||||||
|
except (KeyError, TypeError, ValueError) as exc:
|
||||||
|
raise ValueError(
|
||||||
|
f"Invalid speed timeseries response on page {page}: {exc}"
|
||||||
|
) from exc
|
||||||
|
|
||||||
def get_material_samples(
|
def get_material_samples(
|
||||||
self,
|
self,
|
||||||
*,
|
*,
|
||||||
@@ -308,8 +367,8 @@ class EnlyzeApiGateway:
|
|||||||
) -> dict[str, list[DosingChannelSample]]:
|
) -> dict[str, list[DosingChannelSample]]:
|
||||||
"""Read configured dosing channels through the gateway only.
|
"""Read configured dosing channels through the gateway only.
|
||||||
|
|
||||||
Configurations name stable PLC origins; ENLYZE UUIDs are resolved at poll
|
Process and material-number refs name stable PLC origins resolved uniquely
|
||||||
time and must be unique, preventing a silently stale variable mapping.
|
at poll time. Direct material-name refs explicitly name machine variable UUIDs.
|
||||||
"""
|
"""
|
||||||
if (
|
if (
|
||||||
start.tzinfo is None
|
start.tzinfo is None
|
||||||
@@ -355,9 +414,17 @@ class EnlyzeApiGateway:
|
|||||||
if not isinstance(row, list) or len(row) != len(columns):
|
if not isinstance(row, list) or len(row) != len(columns):
|
||||||
raise ValueError("record must match columns")
|
raise ValueError("record must match columns")
|
||||||
timestamp = _parse_timestamp(row[columns.index("time")])
|
timestamp = _parse_timestamp(row[columns.index("time")])
|
||||||
for key, (total, status, percentage, screw, material) in resolved.items():
|
for key, (total, status, percentage, screw, material, name) in resolved.items():
|
||||||
sample = self._dosing_sample(
|
sample = self._dosing_sample(
|
||||||
row, columns, timestamp, total, status, percentage, screw, material
|
row,
|
||||||
|
columns,
|
||||||
|
timestamp,
|
||||||
|
total,
|
||||||
|
status,
|
||||||
|
percentage,
|
||||||
|
screw,
|
||||||
|
material,
|
||||||
|
name,
|
||||||
)
|
)
|
||||||
if sample is not None:
|
if sample is not None:
|
||||||
result[key].append(sample)
|
result[key].append(sample)
|
||||||
@@ -376,10 +443,11 @@ class EnlyzeApiGateway:
|
|||||||
*,
|
*,
|
||||||
machine_id: str,
|
machine_id: str,
|
||||||
channels: tuple["ChannelDefinition", ...],
|
channels: tuple["ChannelDefinition", ...],
|
||||||
) -> dict[str, tuple[str, str, str, str, str | None]]:
|
) -> dict[str, tuple[str, str, str, str, str | None, str | None]]:
|
||||||
"""Resolve configured PLC origins without reading samples or writing state."""
|
"""Resolve unique PLC origins and explicit machine variable UUID references."""
|
||||||
origins = self._variables_by_origin(machine_id)
|
variable_ids: set[str] = set()
|
||||||
resolved: dict[str, tuple[str, str, str, str, str | None]] = {}
|
origins = self._variables_by_origin(machine_id, variable_ids=variable_ids)
|
||||||
|
resolved: dict[str, tuple[str, str, str, str, str | None, str | None]] = {}
|
||||||
for channel in channels:
|
for channel in channels:
|
||||||
refs = (
|
refs = (
|
||||||
channel.total_rate_signal_ref,
|
channel.total_rate_signal_ref,
|
||||||
@@ -394,7 +462,17 @@ class EnlyzeApiGateway:
|
|||||||
else None
|
else None
|
||||||
)
|
)
|
||||||
key = channel.channel + "\0" + channel.extruder
|
key = channel.channel + "\0" + channel.extruder
|
||||||
resolved[key] = (*ids, material)
|
name = None
|
||||||
|
if channel.material_name_signal_ref is not None:
|
||||||
|
if material is not None:
|
||||||
|
raise ValueError("Material number and name signals are mutually exclusive")
|
||||||
|
ref = channel.material_name_signal_ref
|
||||||
|
if not ref.startswith("uuid:"):
|
||||||
|
raise ValueError("material_name_signal_ref must be uuid:<UUID>")
|
||||||
|
name = str(UUID(ref[5:]))
|
||||||
|
if name not in variable_ids:
|
||||||
|
raise ValueError(f"Configured material-name UUID {name!r} is unavailable")
|
||||||
|
resolved[key] = (*ids, material, name)
|
||||||
return resolved
|
return resolved
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@@ -407,6 +485,7 @@ class EnlyzeApiGateway:
|
|||||||
percentage: str,
|
percentage: str,
|
||||||
screw: str,
|
screw: str,
|
||||||
material: str | None,
|
material: str | None,
|
||||||
|
name: str | None = None,
|
||||||
) -> DosingChannelSample | None:
|
) -> DosingChannelSample | None:
|
||||||
def numeric(variable: str) -> float:
|
def numeric(variable: str) -> float:
|
||||||
value = row[columns.index(variable)]
|
value = row[columns.index(variable)]
|
||||||
@@ -438,6 +517,9 @@ class EnlyzeApiGateway:
|
|||||||
material_value = None if material is None else row[columns.index(material)]
|
material_value = None if material is None else row[columns.index(material)]
|
||||||
if material_value is not None and not isinstance(material_value, (str, int, float)):
|
if material_value is not None and not isinstance(material_value, (str, int, float)):
|
||||||
raise ValueError("material assignment must be scalar or null")
|
raise ValueError("material assignment must be scalar or null")
|
||||||
|
name_value = None if name is None else row[columns.index(name)]
|
||||||
|
if name_value is not None and not isinstance(name_value, str):
|
||||||
|
raise ValueError("material name must be a string or null")
|
||||||
return DosingChannelSample(
|
return DosingChannelSample(
|
||||||
timestamp,
|
timestamp,
|
||||||
numeric(total),
|
numeric(total),
|
||||||
@@ -445,9 +527,12 @@ class EnlyzeApiGateway:
|
|||||||
numeric(percentage),
|
numeric(percentage),
|
||||||
numeric(screw),
|
numeric(screw),
|
||||||
None if material_value is None else str(material_value),
|
None if material_value is None else str(material_value),
|
||||||
|
name_value if name_value is not None and name_value.strip() else None,
|
||||||
)
|
)
|
||||||
|
|
||||||
def _variables_by_origin(self, machine_id: str) -> dict[str, list[str]]:
|
def _variables_by_origin(
|
||||||
|
self, machine_id: str, *, variable_ids: set[str] | None = None
|
||||||
|
) -> dict[str, list[str]]:
|
||||||
params = {"machine": machine_id}
|
params = {"machine": machine_id}
|
||||||
result: dict[str, list[str]] = {}
|
result: dict[str, list[str]] = {}
|
||||||
cursors: set[str] = set()
|
cursors: set[str] = set()
|
||||||
@@ -461,6 +546,10 @@ class EnlyzeApiGateway:
|
|||||||
uuid = item["uuid"]
|
uuid = item["uuid"]
|
||||||
if not isinstance(uuid, str):
|
if not isinstance(uuid, str):
|
||||||
raise ValueError("variable uuid must be a string")
|
raise ValueError("variable uuid must be a string")
|
||||||
|
if variable_ids is not None:
|
||||||
|
if uuid in variable_ids:
|
||||||
|
raise ValueError("variable UUID must be unique")
|
||||||
|
variable_ids.add(uuid)
|
||||||
details = item.get("details")
|
details = item.get("details")
|
||||||
if not isinstance(details, dict):
|
if not isinstance(details, dict):
|
||||||
raise ValueError("variable details must be an object")
|
raise ValueError("variable details must be an object")
|
||||||
|
|||||||
@@ -1,10 +1,19 @@
|
|||||||
"""Read-only ERP current workplace context."""
|
"""Read-only ERP workplace context and historical production confirmations."""
|
||||||
|
|
||||||
from production_analytics.erp.gateway import (
|
from production_analytics.erp.gateway import (
|
||||||
CurrentWorkplaceStatus,
|
CurrentWorkplaceStatus,
|
||||||
|
ErpProductionConfirmationGateway,
|
||||||
ErpReadError,
|
ErpReadError,
|
||||||
ErpSettings,
|
ErpSettings,
|
||||||
ErpWorkplaceStatusGateway,
|
ErpWorkplaceStatusGateway,
|
||||||
|
ProductionConfirmation,
|
||||||
)
|
)
|
||||||
|
|
||||||
__all__ = ["CurrentWorkplaceStatus", "ErpReadError", "ErpSettings", "ErpWorkplaceStatusGateway"]
|
__all__ = [
|
||||||
|
"CurrentWorkplaceStatus",
|
||||||
|
"ErpProductionConfirmationGateway",
|
||||||
|
"ErpReadError",
|
||||||
|
"ErpSettings",
|
||||||
|
"ErpWorkplaceStatusGateway",
|
||||||
|
"ProductionConfirmation",
|
||||||
|
]
|
||||||
@@ -1,11 +1,12 @@
|
|||||||
"""Focused MSSQL boundary for dbo.GRAFANA_WORKPLACE_STATUS."""
|
"""Focused read-only MSSQL boundaries for ERP status and confirmations."""
|
||||||
|
|
||||||
import os
|
import os
|
||||||
from collections.abc import Mapping
|
from collections.abc import Mapping
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from datetime import datetime
|
from datetime import UTC, datetime
|
||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
from math import isfinite
|
from math import isfinite
|
||||||
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
import pymssql
|
import pymssql
|
||||||
|
|
||||||
@@ -62,7 +63,7 @@ class ErpSettings:
|
|||||||
|
|
||||||
@dataclass(frozen=True, slots=True)
|
@dataclass(frozen=True, slots=True)
|
||||||
class CurrentWorkplaceStatus:
|
class CurrentWorkplaceStatus:
|
||||||
"""Latest ERP feedback; timestamp and timezone are preserved, with no freshness claim."""
|
"""Latest ERP feedback with an aware timestamp; no freshness claim."""
|
||||||
|
|
||||||
workplace: str
|
workplace: str
|
||||||
production_order: str
|
production_order: str
|
||||||
@@ -120,7 +121,10 @@ class ErpWorkplaceStatusGateway:
|
|||||||
workplace=_text(row[0]), production_order=_text(row[1]),
|
workplace=_text(row[0]), production_order=_text(row[1]),
|
||||||
article_number=_text(row[2], nullable=True),
|
article_number=_text(row[2], nullable=True),
|
||||||
article_description=_text(row[3], nullable=True),
|
article_description=_text(row[3], nullable=True),
|
||||||
feedback_timestamp=row[4],
|
feedback_timestamp=(
|
||||||
|
row[4].replace(tzinfo=_PLANT_TIMEZONE)
|
||||||
|
if row[4].utcoffset() is None else row[4]
|
||||||
|
),
|
||||||
order_quantity_m2=_number(row[5]), good_quantity_m2=_number(row[6]),
|
order_quantity_m2=_number(row[5]), good_quantity_m2=_number(row[6]),
|
||||||
remaining_quantity_m2=_number(row[7]), remaining_time_hours=_number(row[8]),
|
remaining_quantity_m2=_number(row[7]), remaining_time_hours=_number(row[8]),
|
||||||
remaining_rolls=_number(row[9]),
|
remaining_rolls=_number(row[9]),
|
||||||
@@ -146,3 +150,106 @@ def _number(value: object) -> float | None:
|
|||||||
if not isfinite(result):
|
if not isfinite(result):
|
||||||
raise ValueError
|
raise ValueError
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
_PLANT_TIMEZONE = ZoneInfo("Europe/Berlin")
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class ProductionConfirmation:
|
||||||
|
"""Historical ERP view row; quantities follow the view's production semantics."""
|
||||||
|
|
||||||
|
workplace: str
|
||||||
|
production_order: str
|
||||||
|
timestamp: datetime
|
||||||
|
article_number: str | None
|
||||||
|
article_description: str | None
|
||||||
|
roll_number: str | None
|
||||||
|
production_quantity_m2: float | None
|
||||||
|
feedback_quantity_m2: float | None
|
||||||
|
raw_material_number: str | None
|
||||||
|
raw_material_description: str | None
|
||||||
|
batch_number: str | None
|
||||||
|
raw_material_quantity: float | None
|
||||||
|
tenant: str | None
|
||||||
|
|
||||||
|
@property
|
||||||
|
def is_finished_goods(self) -> bool:
|
||||||
|
"""Positive feedback identifies finished production, independently of workplace."""
|
||||||
|
return self.feedback_quantity_m2 is not None and self.feedback_quantity_m2 > 0
|
||||||
|
|
||||||
|
|
||||||
|
_PRODUCTION_CONFIRMATION_SQL = """SELECT
|
||||||
|
[Mandant], [Fertigungsauftragsnummer], [Zeitstempel], [Arbeitsplatz],
|
||||||
|
[Artikelnummer], [Artikelbezeichnung], [Rollennummer], [Fertigungsmenge],
|
||||||
|
[Rohstoffnummer], [Rohstoffbezeichnung], [Chargennummer], [Rückmeldemenge], [Fasermenge]
|
||||||
|
FROM [dbo].[GRAFANA_PRODUCTION_CONFIRMATION]
|
||||||
|
WHERE [Arbeitsplatz] = %s AND [Zeitstempel] >= %s AND [Zeitstempel] < %s
|
||||||
|
ORDER BY [Zeitstempel], [Mandant], [Fertigungsauftragsnummer], [Rollennummer],
|
||||||
|
[Artikelnummer], [Rohstoffnummer], [Chargennummer], [Fertigungsmenge],
|
||||||
|
[Rückmeldemenge], [Fasermenge], [Artikelbezeichnung], [Rohstoffbezeichnung]"""
|
||||||
|
|
||||||
|
|
||||||
|
class ErpProductionConfirmationGateway:
|
||||||
|
"""Read complete view rows for an exact workplace and a plant-local [start, end).
|
||||||
|
|
||||||
|
SQL datetime stores no offset or fold. Ambiguous autumn timestamps are attached
|
||||||
|
with fold=0 (the first occurrence); the source cannot identify their actual fold.
|
||||||
|
Windows whose local end does not follow their local start cannot be expressed
|
||||||
|
by this SQL predicate and are rejected. Repeated hours cannot be queried separately.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, settings: ErpSettings) -> None:
|
||||||
|
self._settings = settings
|
||||||
|
|
||||||
|
def get_confirmations(
|
||||||
|
self, *, workplace: str, start: datetime, end: datetime
|
||||||
|
) -> list[ProductionConfirmation]:
|
||||||
|
if not isinstance(workplace, str) or not workplace.strip() or "\x00" in workplace:
|
||||||
|
raise ValueError("workplace must be a non-empty string without NUL bytes")
|
||||||
|
for name, value in (("start", start), ("end", end)):
|
||||||
|
if not isinstance(value, datetime) or value.tzinfo is None or value.utcoffset() is None:
|
||||||
|
raise ValueError(f"{name} must be a timezone-aware datetime")
|
||||||
|
if end.astimezone(UTC) <= start.astimezone(UTC):
|
||||||
|
raise ValueError("end must follow start")
|
||||||
|
local_start = start.astimezone(_PLANT_TIMEZONE).replace(tzinfo=None)
|
||||||
|
local_end = end.astimezone(_PLANT_TIMEZONE).replace(tzinfo=None)
|
||||||
|
if local_end <= local_start:
|
||||||
|
raise ValueError("end must follow start in plant-local SQL time")
|
||||||
|
try:
|
||||||
|
with pymssql.connect(
|
||||||
|
server=self._settings.host, port=self._settings.port,
|
||||||
|
database=self._settings.database, user=self._settings.user,
|
||||||
|
password=self._settings.password, login_timeout=10, timeout=10,
|
||||||
|
) as connection:
|
||||||
|
with connection.cursor() as cursor:
|
||||||
|
cursor.execute(
|
||||||
|
_PRODUCTION_CONFIRMATION_SQL, (workplace.strip(), local_start, local_end)
|
||||||
|
)
|
||||||
|
rows = cursor.fetchall()
|
||||||
|
except Exception:
|
||||||
|
raise ErpReadError("ERP production confirmation read failed") from None
|
||||||
|
try:
|
||||||
|
return [_production_confirmation(row) for row in rows]
|
||||||
|
except Exception:
|
||||||
|
raise ErpReadError("ERP production confirmation returned an invalid row") from None
|
||||||
|
|
||||||
|
|
||||||
|
def _production_confirmation(row: tuple[object, ...]) -> ProductionConfirmation:
|
||||||
|
if len(row) != 13 or not isinstance(row[2], datetime) or row[2].tzinfo is not None:
|
||||||
|
raise ValueError
|
||||||
|
return ProductionConfirmation(
|
||||||
|
workplace=_text(row[3]),
|
||||||
|
production_order=_text(row[1]),
|
||||||
|
timestamp=row[2].replace(tzinfo=_PLANT_TIMEZONE, fold=0),
|
||||||
|
article_number=_text(row[4], nullable=True),
|
||||||
|
article_description=_text(row[5], nullable=True),
|
||||||
|
roll_number=_text(row[6], nullable=True),
|
||||||
|
production_quantity_m2=_number(row[7]),
|
||||||
|
feedback_quantity_m2=_number(row[11]),
|
||||||
|
raw_material_number=_text(row[8], nullable=True),
|
||||||
|
raw_material_description=_text(row[9], nullable=True),
|
||||||
|
batch_number=_text(row[10], nullable=True),
|
||||||
|
raw_material_quantity=_number(row[12]),
|
||||||
|
tenant=_text(row[0], nullable=True),
|
||||||
|
)
|
||||||
@@ -28,6 +28,7 @@ class ChannelDefinition:
|
|||||||
percentage_signal_ref: str
|
percentage_signal_ref: str
|
||||||
screw_speed_signal_ref: str
|
screw_speed_signal_ref: str
|
||||||
material_number_signal_ref: str | None = None
|
material_number_signal_ref: str | None = None
|
||||||
|
material_name_signal_ref: str | None = None
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True, slots=True)
|
@dataclass(frozen=True, slots=True)
|
||||||
|
|||||||
@@ -1,9 +1,19 @@
|
|||||||
"""PostgreSQL persistence for reconciled ENLYZE downtime events."""
|
"""PostgreSQL persistence for reconciled ENLYZE downtime events."""
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from production_analytics.calculations.shift_downtime import (
|
||||||
|
ShiftDowntimeEvent,
|
||||||
|
validate_downtime_window,
|
||||||
|
)
|
||||||
from production_analytics.service.downtime import ProductionDowntimeEvent, ProductionOrderBoundary
|
from production_analytics.service.downtime import ProductionDowntimeEvent, ProductionOrderBoundary
|
||||||
from production_analytics.service.postgres_material import PostgresSettings
|
from production_analytics.service.postgres_material import PostgresSettings
|
||||||
|
|
||||||
|
|
||||||
|
class DowntimeReadError(RuntimeError):
|
||||||
|
"""Safe operator-facing error for persisted downtime reads."""
|
||||||
|
|
||||||
|
|
||||||
class PostgresDowntimeRepository:
|
class PostgresDowntimeRepository:
|
||||||
def __init__(self, settings: PostgresSettings) -> None:
|
def __init__(self, settings: PostgresSettings) -> None:
|
||||||
self.settings = settings
|
self.settings = settings
|
||||||
@@ -21,6 +31,30 @@ class PostgresDowntimeRepository:
|
|||||||
options="-c statement_timeout=10000",
|
options="-c statement_timeout=10000",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
def get_events(
|
||||||
|
self, *, machine_id: str, start: datetime, end: datetime
|
||||||
|
) -> list[ShiftDowntimeEvent]:
|
||||||
|
"""Read raw machine intervals intersecting [start, end), independent of orders."""
|
||||||
|
validate_downtime_window(machine_id=machine_id, start=start, end=end)
|
||||||
|
try:
|
||||||
|
with self._connect() as connection:
|
||||||
|
rows = connection.execute(
|
||||||
|
"""SELECT external_id, machine_id, source_start, source_end,
|
||||||
|
reason_id, reason_name, reason_description, reason_group,
|
||||||
|
category, comment
|
||||||
|
FROM production_downtime_events
|
||||||
|
WHERE machine_id = %s AND source_start < %s
|
||||||
|
AND (source_end IS NULL OR source_end > %s)
|
||||||
|
ORDER BY source_start, external_id""",
|
||||||
|
(machine_id, end, start),
|
||||||
|
).fetchall()
|
||||||
|
except Exception:
|
||||||
|
raise DowntimeReadError("PostgreSQL shift downtime read failed") from None
|
||||||
|
try:
|
||||||
|
return [ShiftDowntimeEvent(*row) for row in rows]
|
||||||
|
except Exception:
|
||||||
|
raise DowntimeReadError("PostgreSQL shift downtime returned an invalid row") from None
|
||||||
|
|
||||||
def current_boundary(self, machine_id: str) -> ProductionOrderBoundary | None:
|
def current_boundary(self, machine_id: str) -> ProductionOrderBoundary | None:
|
||||||
with self._connect() as connection:
|
with self._connect() as connection:
|
||||||
row = connection.execute(
|
row = connection.execute(
|
||||||
|
|||||||
@@ -0,0 +1,136 @@
|
|||||||
|
"""Read-only baseline plus bounded-window queries for shift material deltas.
|
||||||
|
|
||||||
|
One valid baseline per calculation/channel, followed by every raw in-window
|
||||||
|
row. Missing baselines leave window rows intact for aggregation's fallback.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from production_analytics.calculations.shift_material import (
|
||||||
|
ShiftChannelMaterialSnapshot,
|
||||||
|
ShiftMaterialSnapshot,
|
||||||
|
validate_material_window,
|
||||||
|
)
|
||||||
|
from production_analytics.service.postgres_material import PostgresSettings
|
||||||
|
|
||||||
|
|
||||||
|
class ShiftMaterialReadError(RuntimeError):
|
||||||
|
"""Safe operator-facing cumulative snapshot read/result error."""
|
||||||
|
|
||||||
|
|
||||||
|
# A backward index scan per requested calculation stops at its first valid
|
||||||
|
# baseline. The other branch reads only the bounded shift, without filtering
|
||||||
|
# counters (invalid samples can mark run transitions).
|
||||||
|
_MATERIAL_SQL = """WITH request AS (
|
||||||
|
SELECT %s::text AS machine_id, %s::text[] AS calculation_ids,
|
||||||
|
%s::timestamptz AS start_time, %s::timestamptz AS end_time
|
||||||
|
), baseline AS (
|
||||||
|
SELECT sample.*
|
||||||
|
FROM request r
|
||||||
|
CROSS JOIN LATERAL unnest(r.calculation_ids) AS ids(calculation_id)
|
||||||
|
CROSS JOIN LATERAL (
|
||||||
|
SELECT timestamp, calculation_id, machine_id, production_order, run_id, consumption_kg
|
||||||
|
FROM material_consumption_snapshots
|
||||||
|
WHERE calculation_id = ids.calculation_id AND machine_id = r.machine_id
|
||||||
|
AND timestamp <= r.start_time
|
||||||
|
AND consumption_kg >= 0 AND consumption_kg < 'Infinity'::double precision
|
||||||
|
ORDER BY timestamp DESC, run_id, production_order
|
||||||
|
LIMIT 1
|
||||||
|
) sample
|
||||||
|
)
|
||||||
|
SELECT * FROM baseline
|
||||||
|
UNION ALL
|
||||||
|
SELECT timestamp, s.calculation_id, s.machine_id, production_order, run_id, consumption_kg
|
||||||
|
FROM material_consumption_snapshots s CROSS JOIN request r
|
||||||
|
WHERE s.machine_id = r.machine_id AND s.calculation_id = ANY(r.calculation_ids)
|
||||||
|
AND timestamp > r.start_time AND timestamp < r.end_time
|
||||||
|
ORDER BY calculation_id, timestamp, run_id, production_order"""
|
||||||
|
|
||||||
|
# The channel index has production_order between channel and timestamp, so it
|
||||||
|
# cannot directly support a backward timestamp seek per channel. DISTINCT ON
|
||||||
|
# selects all channel baselines in one filtered pass rather than rescanning
|
||||||
|
# pre-shift history separately for every channel. See the performance notes.
|
||||||
|
_CHANNEL_SQL = """WITH request AS (
|
||||||
|
SELECT %s::text AS machine_id, %s::text[] AS calculation_ids,
|
||||||
|
%s::timestamptz AS start_time, %s::timestamptz AS end_time
|
||||||
|
), baseline AS (
|
||||||
|
SELECT DISTINCT ON (s.calculation_id, extruder, doser_channel)
|
||||||
|
timestamp, s.calculation_id, s.machine_id, extruder, doser_channel,
|
||||||
|
production_order, run_id, cumulative_consumption_kg, material_number,
|
||||||
|
material_name, material_mapping_status, percentage_sum_valid
|
||||||
|
FROM channel_material_consumption_snapshots s CROSS JOIN request r
|
||||||
|
WHERE s.machine_id = r.machine_id AND s.calculation_id = ANY(r.calculation_ids)
|
||||||
|
AND timestamp <= r.start_time
|
||||||
|
AND cumulative_consumption_kg >= 0
|
||||||
|
AND cumulative_consumption_kg < 'Infinity'::double precision
|
||||||
|
ORDER BY s.calculation_id, extruder, doser_channel, timestamp DESC, run_id, production_order
|
||||||
|
)
|
||||||
|
SELECT * FROM baseline
|
||||||
|
UNION ALL
|
||||||
|
SELECT timestamp, s.calculation_id, s.machine_id, extruder, doser_channel,
|
||||||
|
production_order, run_id, cumulative_consumption_kg, material_number,
|
||||||
|
material_name, material_mapping_status, percentage_sum_valid
|
||||||
|
FROM channel_material_consumption_snapshots s CROSS JOIN request r
|
||||||
|
WHERE s.machine_id = r.machine_id AND s.calculation_id = ANY(r.calculation_ids)
|
||||||
|
AND timestamp > r.start_time AND timestamp < r.end_time
|
||||||
|
ORDER BY calculation_id, extruder, doser_channel, timestamp, run_id, production_order"""
|
||||||
|
|
||||||
|
|
||||||
|
class PostgresShiftMaterialRepository:
|
||||||
|
def __init__(self, settings: PostgresSettings) -> None:
|
||||||
|
self.settings = settings
|
||||||
|
|
||||||
|
def get_snapshots(
|
||||||
|
self, *, machine_id: str, calculation_ids: tuple[str, ...], start: datetime, end: datetime
|
||||||
|
) -> list[ShiftMaterialSnapshot]:
|
||||||
|
validate_material_window(
|
||||||
|
machine_id=machine_id, calculation_ids=calculation_ids, start=start, end=end
|
||||||
|
)
|
||||||
|
rows = _read(
|
||||||
|
self.settings, _MATERIAL_SQL, (machine_id, list(calculation_ids), start, end)
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
return [ShiftMaterialSnapshot(*row) for row in rows]
|
||||||
|
except Exception:
|
||||||
|
raise ShiftMaterialReadError(
|
||||||
|
"PostgreSQL shift material returned an invalid row"
|
||||||
|
) from None
|
||||||
|
|
||||||
|
|
||||||
|
class PostgresShiftChannelMaterialRepository:
|
||||||
|
def __init__(self, settings: PostgresSettings) -> None:
|
||||||
|
self.settings = settings
|
||||||
|
|
||||||
|
def get_snapshots(
|
||||||
|
self, *, machine_id: str, calculation_ids: tuple[str, ...], start: datetime, end: datetime
|
||||||
|
) -> list[ShiftChannelMaterialSnapshot]:
|
||||||
|
validate_material_window(
|
||||||
|
machine_id=machine_id, calculation_ids=calculation_ids, start=start, end=end
|
||||||
|
)
|
||||||
|
rows = _read(
|
||||||
|
self.settings, _CHANNEL_SQL, (machine_id, list(calculation_ids), start, end)
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
return [ShiftChannelMaterialSnapshot(*row) for row in rows]
|
||||||
|
except Exception:
|
||||||
|
raise ShiftMaterialReadError(
|
||||||
|
"PostgreSQL shift material returned an invalid row"
|
||||||
|
) from None
|
||||||
|
|
||||||
|
|
||||||
|
def _read(settings: PostgresSettings, sql: str, parameters: tuple) -> list[tuple]:
|
||||||
|
import psycopg
|
||||||
|
|
||||||
|
try:
|
||||||
|
with psycopg.connect(
|
||||||
|
host=settings.host,
|
||||||
|
port=settings.port,
|
||||||
|
dbname=settings.dbname,
|
||||||
|
user=settings.user,
|
||||||
|
password=settings.password,
|
||||||
|
connect_timeout=10,
|
||||||
|
options="-c statement_timeout=10000",
|
||||||
|
) as connection:
|
||||||
|
return connection.execute(sql, parameters).fetchall()
|
||||||
|
except Exception:
|
||||||
|
raise ShiftMaterialReadError("PostgreSQL shift material read failed") from None
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
"""Compose persisted source downtime reads with pure shift aggregation."""
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Protocol
|
||||||
|
|
||||||
|
from production_analytics.calculations.shift_downtime import (
|
||||||
|
ShiftDowntimeEvent,
|
||||||
|
ShiftDowntimeSummary,
|
||||||
|
aggregate_shift_downtime,
|
||||||
|
validate_downtime_window,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class ShiftDowntimeReader(Protocol):
|
||||||
|
def get_events(
|
||||||
|
self, *, machine_id: str, start: datetime, end: datetime
|
||||||
|
) -> list[ShiftDowntimeEvent]: ...
|
||||||
|
|
||||||
|
|
||||||
|
class ShiftDowntimeService:
|
||||||
|
def __init__(self, repository: ShiftDowntimeReader) -> None:
|
||||||
|
self.repository = repository
|
||||||
|
|
||||||
|
def summarize(self, *, machine_id: str, start: datetime, end: datetime) -> ShiftDowntimeSummary:
|
||||||
|
validate_downtime_window(machine_id=machine_id, start=start, end=end)
|
||||||
|
events = self.repository.get_events(machine_id=machine_id, start=start, end=end)
|
||||||
|
return aggregate_shift_downtime(events, machine_id=machine_id, start=start, end=end)
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
"""Thin services composing explicit snapshot sources with pure shift aggregation."""
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Protocol
|
||||||
|
|
||||||
|
from production_analytics.calculations.shift_material import (
|
||||||
|
ShiftChannelMaterialSnapshot,
|
||||||
|
ShiftMaterialSnapshot,
|
||||||
|
ShiftMaterialSummary,
|
||||||
|
aggregate_shift_channel_material,
|
||||||
|
aggregate_shift_material,
|
||||||
|
validate_material_window,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class ShiftMaterialReader(Protocol):
|
||||||
|
def get_snapshots(
|
||||||
|
self, *, machine_id: str, calculation_ids: tuple[str, ...], start: datetime, end: datetime
|
||||||
|
) -> list[ShiftMaterialSnapshot]: ...
|
||||||
|
|
||||||
|
|
||||||
|
class ShiftChannelMaterialReader(Protocol):
|
||||||
|
def get_snapshots(
|
||||||
|
self, *, machine_id: str, calculation_ids: tuple[str, ...], start: datetime, end: datetime
|
||||||
|
) -> list[ShiftChannelMaterialSnapshot]: ...
|
||||||
|
|
||||||
|
|
||||||
|
class ShiftMaterialService:
|
||||||
|
def __init__(self, repository: ShiftMaterialReader) -> None:
|
||||||
|
self.repository = repository
|
||||||
|
|
||||||
|
def summarize(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
machine_id: str,
|
||||||
|
calculation_ids: tuple[str, ...],
|
||||||
|
start: datetime,
|
||||||
|
end: datetime,
|
||||||
|
include_zero: bool = True,
|
||||||
|
) -> ShiftMaterialSummary:
|
||||||
|
validate_material_window(
|
||||||
|
machine_id=machine_id, calculation_ids=calculation_ids, start=start, end=end
|
||||||
|
)
|
||||||
|
snapshots = self.repository.get_snapshots(
|
||||||
|
machine_id=machine_id, calculation_ids=calculation_ids, start=start, end=end
|
||||||
|
)
|
||||||
|
return aggregate_shift_material(
|
||||||
|
snapshots,
|
||||||
|
machine_id=machine_id,
|
||||||
|
calculation_ids=calculation_ids,
|
||||||
|
start=start,
|
||||||
|
end=end,
|
||||||
|
include_zero=include_zero,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class ShiftChannelMaterialService:
|
||||||
|
def __init__(self, repository: ShiftChannelMaterialReader) -> None:
|
||||||
|
self.repository = repository
|
||||||
|
|
||||||
|
def summarize(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
machine_id: str,
|
||||||
|
calculation_ids: tuple[str, ...],
|
||||||
|
start: datetime,
|
||||||
|
end: datetime,
|
||||||
|
include_zero: bool = True,
|
||||||
|
) -> ShiftMaterialSummary:
|
||||||
|
validate_material_window(
|
||||||
|
machine_id=machine_id, calculation_ids=calculation_ids, start=start, end=end
|
||||||
|
)
|
||||||
|
snapshots = self.repository.get_snapshots(
|
||||||
|
machine_id=machine_id, calculation_ids=calculation_ids, start=start, end=end
|
||||||
|
)
|
||||||
|
return aggregate_shift_channel_material(
|
||||||
|
snapshots,
|
||||||
|
machine_id=machine_id,
|
||||||
|
calculation_ids=calculation_ids,
|
||||||
|
start=start,
|
||||||
|
end=end,
|
||||||
|
include_zero=include_zero,
|
||||||
|
)
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
"""Compose historical ERP reads with pure shift-production aggregation."""
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Protocol
|
||||||
|
|
||||||
|
from production_analytics.calculations.shift_production import (
|
||||||
|
ShiftProductionSummary,
|
||||||
|
aggregate_shift_production,
|
||||||
|
validate_shift_window,
|
||||||
|
)
|
||||||
|
from production_analytics.erp import ProductionConfirmation
|
||||||
|
|
||||||
|
|
||||||
|
class ProductionConfirmationReader(Protocol):
|
||||||
|
def get_confirmations(
|
||||||
|
self, *, workplace: str, start: datetime, end: datetime
|
||||||
|
) -> list[ProductionConfirmation]: ...
|
||||||
|
|
||||||
|
|
||||||
|
class ShiftProductionService:
|
||||||
|
def __init__(self, gateway: ProductionConfirmationReader) -> None:
|
||||||
|
self.gateway = gateway
|
||||||
|
|
||||||
|
def summarize(
|
||||||
|
self, *, workplace: str, start: datetime, end: datetime
|
||||||
|
) -> ShiftProductionSummary:
|
||||||
|
workplace = validate_shift_window(workplace=workplace, start=start, end=end)
|
||||||
|
confirmations = self.gateway.get_confirmations(workplace=workplace, start=start, end=end)
|
||||||
|
return aggregate_shift_production(confirmations, workplace=workplace, start=start, end=end)
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
"""Sequential composition of validated services; mandatory failures propagate."""
|
||||||
|
|
||||||
|
from collections.abc import Mapping
|
||||||
|
from datetime import datetime
|
||||||
|
from types import MappingProxyType
|
||||||
|
|
||||||
|
from production_analytics.calculations.shift_report import SHIFT_TIMEZONE, ShiftReport
|
||||||
|
from production_analytics.calculations.shift_speed import validate_speed_window
|
||||||
|
from production_analytics.service.shift_downtime import ShiftDowntimeService
|
||||||
|
from production_analytics.service.shift_material import (
|
||||||
|
ShiftChannelMaterialService,
|
||||||
|
ShiftMaterialService,
|
||||||
|
)
|
||||||
|
from production_analytics.service.shift_production import ShiftProductionService
|
||||||
|
from production_analytics.service.shift_report_config import ShiftReportMachineConfig
|
||||||
|
from production_analytics.service.shift_speed import ShiftSpeedService
|
||||||
|
|
||||||
|
|
||||||
|
class ShiftReportService:
|
||||||
|
def __init__(
|
||||||
|
self, *, machines: Mapping[str, ShiftReportMachineConfig],
|
||||||
|
production: ShiftProductionService, downtime: ShiftDowntimeService,
|
||||||
|
materials: ShiftMaterialService, channel_materials: ShiftChannelMaterialService,
|
||||||
|
speed: ShiftSpeedService,
|
||||||
|
) -> None:
|
||||||
|
self.machines = MappingProxyType(dict(machines))
|
||||||
|
self.production = production
|
||||||
|
self.downtime = downtime
|
||||||
|
self.materials = materials
|
||||||
|
self.channel_materials = channel_materials
|
||||||
|
self.speed = speed
|
||||||
|
|
||||||
|
def build(self, *, machine_name: str, start: datetime, end: datetime) -> ShiftReport:
|
||||||
|
validate_speed_window(start, end)
|
||||||
|
if not isinstance(machine_name, str) or machine_name not in self.machines:
|
||||||
|
raise ValueError("Unknown shift-report machine")
|
||||||
|
config = self.machines[machine_name]
|
||||||
|
start, end = start.astimezone(SHIFT_TIMEZONE), end.astimezone(SHIFT_TIMEZONE)
|
||||||
|
production = self.production.summarize(
|
||||||
|
workplace=config.erp_workplace, start=start, end=end,
|
||||||
|
)
|
||||||
|
downtime = self.downtime.summarize(machine_id=config.machine_id, start=start, end=end)
|
||||||
|
material_service = (
|
||||||
|
self.channel_materials if config.material.mode == "channel" else self.materials
|
||||||
|
)
|
||||||
|
materials = material_service.summarize(
|
||||||
|
machine_id=config.machine_id, calculation_ids=config.material.calculation_ids,
|
||||||
|
start=start, end=end,
|
||||||
|
)
|
||||||
|
speed = self.speed.summarize(config=config.speed, start=start, end=end)
|
||||||
|
return ShiftReport(
|
||||||
|
machine_name=machine_name, machine_id=config.machine_id, start=start, end=end,
|
||||||
|
production=production, downtime=downtime, materials=materials, speed=speed,
|
||||||
|
)
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
"""Strict, self-contained configuration for shift-report composition."""
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Literal
|
||||||
|
|
||||||
|
import yaml
|
||||||
|
|
||||||
|
from production_analytics.calculations.shift_speed import ShiftSpeedConfig
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class ShiftReportMaterialConfig:
|
||||||
|
mode: Literal["cumulative", "channel"]
|
||||||
|
calculation_ids: tuple[str, ...]
|
||||||
|
|
||||||
|
def __post_init__(self) -> None:
|
||||||
|
if self.mode not in ("cumulative", "channel"):
|
||||||
|
raise ValueError("material.mode must be cumulative or channel")
|
||||||
|
if not isinstance(self.calculation_ids, tuple) or not self.calculation_ids:
|
||||||
|
raise ValueError("material.calculation_ids must be a non-empty tuple")
|
||||||
|
for calculation_id in self.calculation_ids:
|
||||||
|
_text(calculation_id, "material.calculation_ids")
|
||||||
|
if len(set(self.calculation_ids)) != len(self.calculation_ids):
|
||||||
|
raise ValueError("material.calculation_ids must be unique")
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class ShiftReportMachineConfig:
|
||||||
|
machine_id: str
|
||||||
|
erp_workplace: str
|
||||||
|
material: ShiftReportMaterialConfig
|
||||||
|
speed: ShiftSpeedConfig
|
||||||
|
|
||||||
|
def __post_init__(self) -> None:
|
||||||
|
_text(self.machine_id, "machine_id")
|
||||||
|
_text(self.erp_workplace, "erp_workplace")
|
||||||
|
if not isinstance(self.material, ShiftReportMaterialConfig):
|
||||||
|
raise ValueError("material must be a ShiftReportMaterialConfig")
|
||||||
|
if not isinstance(self.speed, ShiftSpeedConfig) or self.speed.machine_id != self.machine_id:
|
||||||
|
raise ValueError("speed configuration must refer to the report machine")
|
||||||
|
_text(self.speed.signal, "speed.signal")
|
||||||
|
|
||||||
|
|
||||||
|
class _StrictLoader(yaml.SafeLoader):
|
||||||
|
"""Reject duplicate YAML keys instead of silently replacing configuration."""
|
||||||
|
|
||||||
|
|
||||||
|
def _mapping(loader, node):
|
||||||
|
result = {}
|
||||||
|
for key_node, value_node in node.value:
|
||||||
|
key = loader.construct_object(key_node)
|
||||||
|
if not isinstance(key, str) or key in result:
|
||||||
|
raise ValueError("Configuration mapping keys must be unique strings")
|
||||||
|
result[key] = loader.construct_object(value_node)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
_StrictLoader.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, _mapping)
|
||||||
|
|
||||||
|
|
||||||
|
def _text(value: object, name: str) -> None:
|
||||||
|
if not isinstance(value, str) or not value.strip() or "\x00" in value:
|
||||||
|
raise ValueError(f"{name} must be a non-empty string without NUL bytes")
|
||||||
|
|
||||||
|
|
||||||
|
def _fields(value: object, expected: set[str], name: str) -> dict:
|
||||||
|
if not isinstance(value, dict) or set(value) != expected:
|
||||||
|
raise ValueError(f"{name} has missing or unknown fields")
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def load_shift_report_machines(path: str | Path) -> dict[str, ShiftReportMachineConfig]:
|
||||||
|
try:
|
||||||
|
with Path(path).open(encoding="utf-8") as stream:
|
||||||
|
document = yaml.load(stream, Loader=_StrictLoader)
|
||||||
|
except (OSError, UnicodeError, yaml.YAMLError) as exc:
|
||||||
|
raise ValueError("Cannot read shift-report machine configuration") from exc
|
||||||
|
document = _fields(document, {"machines"}, "Shift-report configuration")
|
||||||
|
machines = document["machines"]
|
||||||
|
if not isinstance(machines, dict) or not machines:
|
||||||
|
raise ValueError("machines must be a non-empty mapping")
|
||||||
|
result = {}
|
||||||
|
for name, entry in machines.items():
|
||||||
|
_text(name, "machine name")
|
||||||
|
entry = _fields(entry, {"machine_id", "erp_workplace", "material", "speed"}, name)
|
||||||
|
material = _fields(entry["material"], {"mode", "calculation_ids"}, "material")
|
||||||
|
ids = material["calculation_ids"]
|
||||||
|
if not isinstance(ids, list):
|
||||||
|
raise ValueError("material.calculation_ids must be a list")
|
||||||
|
speed = _fields(
|
||||||
|
entry["speed"], {"signal_ref", "signal", "unit", "production_gate_m_min"}, "speed",
|
||||||
|
)
|
||||||
|
result[name] = ShiftReportMachineConfig(
|
||||||
|
machine_id=entry["machine_id"], erp_workplace=entry["erp_workplace"],
|
||||||
|
material=ShiftReportMaterialConfig(material["mode"], tuple(ids)),
|
||||||
|
speed=ShiftSpeedConfig(
|
||||||
|
machine_id=entry["machine_id"], speed_signal_ref=speed["signal_ref"],
|
||||||
|
signal=speed["signal"], unit=speed["unit"],
|
||||||
|
production_gate_m_min=speed["production_gate_m_min"],
|
||||||
|
),
|
||||||
|
)
|
||||||
|
if len({config.machine_id for config in result.values()}) != len(result):
|
||||||
|
raise ValueError("Shift-report machine IDs must be unique")
|
||||||
|
return result
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
"""Compose bounded ENLYZE speed reads with the pure running-speed KPI."""
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Protocol
|
||||||
|
|
||||||
|
from production_analytics.calculations.shift_speed import (
|
||||||
|
ShiftSpeedConfig,
|
||||||
|
ShiftSpeedSample,
|
||||||
|
ShiftSpeedSummary,
|
||||||
|
aggregate_shift_speed,
|
||||||
|
validate_speed_window,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class ShiftSpeedReader(Protocol):
|
||||||
|
def get_speed_samples(
|
||||||
|
self, *, machine_id: str, speed_signal_ref: str, start: datetime, end: datetime,
|
||||||
|
) -> list[ShiftSpeedSample]: ...
|
||||||
|
|
||||||
|
|
||||||
|
class ShiftSpeedService:
|
||||||
|
def __init__(self, gateway: ShiftSpeedReader) -> None:
|
||||||
|
self.gateway = gateway
|
||||||
|
|
||||||
|
def summarize(
|
||||||
|
self, *, config: ShiftSpeedConfig, start: datetime, end: datetime,
|
||||||
|
) -> ShiftSpeedSummary:
|
||||||
|
validate_speed_window(start, end)
|
||||||
|
samples = self.gateway.get_speed_samples(
|
||||||
|
machine_id=config.machine_id, speed_signal_ref=config.speed_signal_ref,
|
||||||
|
start=start, end=end,
|
||||||
|
)
|
||||||
|
return aggregate_shift_speed(samples, config=config, start=start, end=end)
|
||||||
@@ -54,6 +54,10 @@ def test_e1_config_dry_run_resolves_every_signal_through_gateway_without_samplin
|
|||||||
}
|
}
|
||||||
for index, origin in enumerate(sorted(origins))
|
for index, origin in enumerate(sorted(origins))
|
||||||
]
|
]
|
||||||
|
+ [
|
||||||
|
{"uuid": channel.material_name_signal_ref[5:], "details": {"origin_identifier": None}}
|
||||||
|
for channel in config.channels
|
||||||
|
]
|
||||||
}
|
}
|
||||||
|
|
||||||
resolved = EnlyzeApiGateway(client).resolve_dosing_channel_signal_refs(
|
resolved = EnlyzeApiGateway(client).resolve_dosing_channel_signal_refs(
|
||||||
@@ -65,7 +69,13 @@ def test_e1_config_dry_run_resolves_every_signal_through_gateway_without_samplin
|
|||||||
assert len(config.channels) == 14
|
assert len(config.channels) == 14
|
||||||
assert len(origins) == 44
|
assert len(origins) == 44
|
||||||
assert len(resolved) == 14
|
assert len(resolved) == 14
|
||||||
assert all(len(refs) == 5 and refs[-1] is None for refs in resolved.values())
|
for channel in config.channels:
|
||||||
|
refs = resolved[channel.channel + "\0" + channel.extruder]
|
||||||
|
assert len(refs) == 6 and refs[-2] is None
|
||||||
|
assert refs[-1] == channel.material_name_signal_ref[5:]
|
||||||
|
assert config.channels[1].material_name_signal_ref == (
|
||||||
|
"uuid:b8be6b5a-0ce7-40ed-9754-107175468c8d"
|
||||||
|
)
|
||||||
client.get.assert_called_once_with("/v2/variables", {"machine": config.machine_ref})
|
client.get.assert_called_once_with("/v2/variables", {"machine": config.machine_ref})
|
||||||
client.post_json.assert_not_called()
|
client.post_json.assert_not_called()
|
||||||
|
|
||||||
@@ -156,3 +166,195 @@ def test_bootstrap_replays_closed_runs_without_integrating_the_inter_run_gap(tmp
|
|||||||
).poll_once(now=NOW + timedelta(seconds=30))
|
).poll_once(now=NOW + timedelta(seconds=30))
|
||||||
assert result is not None
|
assert result is not None
|
||||||
assert result[0].state.cumulative_consumption_kg == pytest.approx(20 / 30)
|
assert result[0].state.cumulative_consumption_kg == pytest.approx(20 / 30)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("name", ["TR 131", None, "", " "])
|
||||||
|
def test_direct_name_samples_and_assignment(name):
|
||||||
|
columns = ["rate", "on", "pct", "rpm", "name"]
|
||||||
|
value = EnlyzeApiGateway._dosing_sample(
|
||||||
|
[120, True, 100, 10, name], columns, NOW, "rate", "on", "pct", "rpm", None, "name"
|
||||||
|
)
|
||||||
|
assert value is not None
|
||||||
|
expected = name if name and name.strip() else None
|
||||||
|
assert value.material_name == expected
|
||||||
|
assert value.material_number is None
|
||||||
|
rate = channel_rates((value,), material_names={"123": "Other"})[0]
|
||||||
|
assert rate.material_name == expected
|
||||||
|
assert rate.material_number is None
|
||||||
|
assert rate.material_mapping_status == ("ASSIGNED" if expected else "UNAVAILABLE")
|
||||||
|
|
||||||
|
|
||||||
|
def test_duplicate_direct_names_remain_assigned():
|
||||||
|
value = DosingChannelSample(NOW, 120, True, 50, 10, material_name="TR 131")
|
||||||
|
assert all(rate.material_mapping_status == "ASSIGNED" for rate in channel_rates((value, value)))
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("value", [123, True, [], {}])
|
||||||
|
def test_direct_name_rejects_non_string(value):
|
||||||
|
with pytest.raises(ValueError, match="material name must be a string or null"):
|
||||||
|
EnlyzeApiGateway._dosing_sample(
|
||||||
|
[120, True, 100, 10, value],
|
||||||
|
["rate", "on", "pct", "rpm", "name"],
|
||||||
|
NOW,
|
||||||
|
"rate",
|
||||||
|
"on",
|
||||||
|
"pct",
|
||||||
|
"rpm",
|
||||||
|
None,
|
||||||
|
"name",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_numeric_material_mapping_is_unchanged():
|
||||||
|
value = EnlyzeApiGateway._dosing_sample(
|
||||||
|
[120, True, 100, 10, 123],
|
||||||
|
["rate", "on", "pct", "rpm", "number"],
|
||||||
|
NOW,
|
||||||
|
"rate",
|
||||||
|
"on",
|
||||||
|
"pct",
|
||||||
|
"rpm",
|
||||||
|
"number",
|
||||||
|
)
|
||||||
|
assert value.material_number == "123"
|
||||||
|
mapped = channel_rates((value,), material_names={"123": "Mapped"})[0]
|
||||||
|
assert (mapped.material_number, mapped.material_name, mapped.material_mapping_status) == (
|
||||||
|
"123",
|
||||||
|
"Mapped",
|
||||||
|
"ASSIGNED",
|
||||||
|
)
|
||||||
|
assert channel_rates((value,), material_names={"456": "Other"})[0].material_mapping_status == (
|
||||||
|
"UNMAPPED"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("ref", ["exa_c1_material", "uuid:bad", "", 123])
|
||||||
|
def test_config_rejects_invalid_direct_name_ref(tmp_path, ref):
|
||||||
|
import yaml
|
||||||
|
|
||||||
|
from production_analytics.calculations.config import CalculationConfigError
|
||||||
|
|
||||||
|
document = yaml.safe_load(E1_CONFIG.read_text())
|
||||||
|
document["calculations"][0]["extruders"][0]["channels"][0]["material_name_signal_ref"] = ref
|
||||||
|
path = tmp_path / "config.yaml"
|
||||||
|
path.write_text(yaml.safe_dump(document))
|
||||||
|
with pytest.raises(CalculationConfigError, match="material_name_signal_ref"):
|
||||||
|
load_channel_material_calculation(path)
|
||||||
|
|
||||||
|
|
||||||
|
def test_config_preserves_number_mode_and_rejects_both_modes(tmp_path):
|
||||||
|
import yaml
|
||||||
|
|
||||||
|
from production_analytics.calculations.config import CalculationConfigError
|
||||||
|
|
||||||
|
document = yaml.safe_load(E1_CONFIG.read_text())
|
||||||
|
row = document["calculations"][0]["extruders"][0]["channels"][0]
|
||||||
|
row["material_number_signal_ref"] = "DB107:100"
|
||||||
|
path = tmp_path / "config.yaml"
|
||||||
|
path.write_text(yaml.safe_dump(document))
|
||||||
|
with pytest.raises(CalculationConfigError, match="mutually exclusive"):
|
||||||
|
load_channel_material_calculation(path)
|
||||||
|
del row["material_name_signal_ref"]
|
||||||
|
path.write_text(yaml.safe_dump(document))
|
||||||
|
channel = load_channel_material_calculation(path).channels[0]
|
||||||
|
assert channel.material_number_signal_ref == "DB107:100"
|
||||||
|
assert channel.material_name_signal_ref is None
|
||||||
|
|
||||||
|
|
||||||
|
def dosing_client(*, include_name=True):
|
||||||
|
name_id = "b8be6b5a-0ce7-40ed-9754-107175468c8d"
|
||||||
|
client = Mock()
|
||||||
|
client.get.return_value.body = {
|
||||||
|
"data": [
|
||||||
|
{"uuid": ref, "details": {"origin_identifier": {"code": ref}}}
|
||||||
|
for ref in ("rate", "on", "pct", "rpm", "number")
|
||||||
|
]
|
||||||
|
+ ([{"uuid": name_id, "details": {"origin_identifier": None}}] if include_name else [])
|
||||||
|
}
|
||||||
|
return client, name_id
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("problem", ["missing_name", "missing_origin", "duplicate_origin"])
|
||||||
|
def test_resolver_preserves_availability_and_origin_uniqueness(problem):
|
||||||
|
client, name_id = dosing_client(include_name=problem != "missing_name")
|
||||||
|
items = client.get.return_value.body["data"]
|
||||||
|
if problem == "missing_origin":
|
||||||
|
items.pop(0)
|
||||||
|
elif problem == "duplicate_origin":
|
||||||
|
items.append({"uuid": "duplicate", "details": {"origin_identifier": {"code": "rate"}}})
|
||||||
|
channel = ChannelDefinition(
|
||||||
|
"Ex1", "C2", "rate", "on", "pct", "rpm", material_name_signal_ref=f"uuid:{name_id}"
|
||||||
|
)
|
||||||
|
with pytest.raises(ValueError, match="unavailable|ambiguous"):
|
||||||
|
EnlyzeApiGateway(client).resolve_dosing_channel_signal_refs(
|
||||||
|
machine_id="m", channels=(channel,)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_number_signal_still_resolves_by_origin():
|
||||||
|
client, _ = dosing_client()
|
||||||
|
channel = ChannelDefinition("Ex1", "C1", "rate", "on", "pct", "rpm", "number")
|
||||||
|
refs = EnlyzeApiGateway(client).resolve_dosing_channel_signal_refs(
|
||||||
|
machine_id="m", channels=(channel,)
|
||||||
|
)
|
||||||
|
assert refs["C1\0Ex1"] == ("rate", "on", "pct", "rpm", "number", None)
|
||||||
|
|
||||||
|
|
||||||
|
def test_direct_name_changes_and_null_reach_postgres_without_carry_forward(tmp_path):
|
||||||
|
import io
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
from production_analytics.service.channel_material_runner import ChannelMaterialPollingRunner
|
||||||
|
from production_analytics.service.postgres_channel_material import (
|
||||||
|
PostgresChannelMaterialSnapshotWriter,
|
||||||
|
)
|
||||||
|
from production_analytics.service.postgres_material import PostgresSettings
|
||||||
|
|
||||||
|
client, name_id = dosing_client()
|
||||||
|
gateway = EnlyzeApiGateway(client)
|
||||||
|
gateway.get_open_production_run = Mock(
|
||||||
|
return_value=EnlyzeProductionRun("run", "m", None, "order", NOW, None)
|
||||||
|
)
|
||||||
|
gateway.get_production_runs = Mock(return_value=[])
|
||||||
|
channel = ChannelDefinition(
|
||||||
|
"Ex1", "C2", "rate", "on", "pct", "rpm", material_name_signal_ref=f"uuid:{name_id}"
|
||||||
|
)
|
||||||
|
service = ChannelMaterialPollingService(
|
||||||
|
gateway=gateway,
|
||||||
|
state_store=JsonChannelMaterialStateStore(tmp_path),
|
||||||
|
machine_id="m",
|
||||||
|
channels=(channel,),
|
||||||
|
max_sample_gap_seconds=20,
|
||||||
|
)
|
||||||
|
writer = PostgresChannelMaterialSnapshotWriter(
|
||||||
|
PostgresSettings("localhost", 5432, "db", "user", "pw")
|
||||||
|
)
|
||||||
|
runner = ChannelMaterialPollingRunner(
|
||||||
|
service,
|
||||||
|
machine_id="m",
|
||||||
|
calculation_id="calc",
|
||||||
|
snapshot_writer=writer,
|
||||||
|
poll_interval_seconds=10,
|
||||||
|
stdout=io.StringIO(),
|
||||||
|
clock=lambda: NOW,
|
||||||
|
)
|
||||||
|
with patch("psycopg.connect") as connect:
|
||||||
|
connection = connect.return_value.__enter__.return_value
|
||||||
|
for index, name in enumerate(("TR 131", "New material", None)):
|
||||||
|
timestamp = NOW + timedelta(seconds=index * 10)
|
||||||
|
client.post_json.return_value.body = {
|
||||||
|
"data": {
|
||||||
|
"columns": ["time", "rate", "on", "pct", "rpm", name_id],
|
||||||
|
"records": [[timestamp.isoformat(), 120, True, 100, 10, name]],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
runner.clock = lambda: timestamp
|
||||||
|
assert runner.run_once()
|
||||||
|
parameters = connection.execute.call_args.args[1]
|
||||||
|
assert parameters[8:11] == (None, name, "ASSIGNED" if name else "UNAVAILABLE")
|
||||||
|
assert parameters[7] == pytest.approx(index / 3)
|
||||||
|
request = client.post_json.call_args.args
|
||||||
|
assert request[0] == "/v2/timeseries"
|
||||||
|
assert request[1]["variables"] == [
|
||||||
|
{"uuid": ref} for ref in ("rate", "on", "pct", "rpm", name_id)
|
||||||
|
]
|
||||||
@@ -1,9 +1,10 @@
|
|||||||
import re
|
import re
|
||||||
import traceback
|
import traceback
|
||||||
from dataclasses import FrozenInstanceError, replace
|
from dataclasses import FrozenInstanceError, replace
|
||||||
from datetime import UTC, datetime
|
from datetime import UTC, datetime, timedelta
|
||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
from unittest.mock import MagicMock
|
from unittest.mock import MagicMock
|
||||||
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
@@ -90,8 +91,9 @@ def test_valid_row_and_resource_lifecycle(db):
|
|||||||
assert status.production_order == '12026000815'
|
assert status.production_order == '12026000815'
|
||||||
assert status.article_number == '212520'
|
assert status.article_number == '212520'
|
||||||
assert status.article_description == 'Stex R 1501 C (PR) 5,80 x 50 m'
|
assert status.article_description == 'Stex R 1501 C (PR) 5,80 x 50 m'
|
||||||
assert status.feedback_timestamp is NOW
|
assert status.feedback_timestamp.isoformat() == '2026-09-04T21:20:50+02:00'
|
||||||
assert status.feedback_timestamp.tzinfo is None
|
assert status.feedback_timestamp.tzinfo == ZoneInfo('Europe/Berlin')
|
||||||
|
assert status.feedback_timestamp.utcoffset() == timedelta(hours=2)
|
||||||
assert (status.order_quantity_m2, status.good_quantity_m2, status.remaining_quantity_m2,
|
assert (status.order_quantity_m2, status.good_quantity_m2, status.remaining_quantity_m2,
|
||||||
status.remaining_time_hours, status.remaining_rolls) == (
|
status.remaining_time_hours, status.remaining_rolls) == (
|
||||||
80040., 69281., 10759., 17., 38.,
|
80040., 69281., 10759., 17., 38.,
|
||||||
@@ -117,6 +119,8 @@ def test_leading_whitespace_and_timezone_preserved(db):
|
|||||||
assert (status.workplace, status.production_order, status.article_number,
|
assert (status.workplace, status.production_order, status.article_number,
|
||||||
status.article_description) == (' K7', ' K 7-001', ' 001', ' description')
|
status.article_description) == (' K7', ' K 7-001', ' 001', ' description')
|
||||||
assert status.feedback_timestamp is row[4]
|
assert status.feedback_timestamp is row[4]
|
||||||
|
assert status.feedback_timestamp.tzinfo is UTC
|
||||||
|
assert status.feedback_timestamp.isoformat() == '2026-09-04T21:20:50+00:00'
|
||||||
|
|
||||||
|
|
||||||
def test_nullable_fields(db):
|
def test_nullable_fields(db):
|
||||||
@@ -185,3 +189,13 @@ def test_driver_errors_are_safe(db, stage):
|
|||||||
assert 'private-password' not in rendered
|
assert 'private-password' not in rendered
|
||||||
if stage != 'connect':
|
if stage != 'connect':
|
||||||
connect.return_value.__exit__.assert_called_once()
|
connect.return_value.__exit__.assert_called_once()
|
||||||
|
|
||||||
|
|
||||||
|
def test_naive_winter_timestamp_uses_berlin_standard_time(db):
|
||||||
|
row = list(ROW)
|
||||||
|
row[4] = datetime(2026, 1, 4, 21, 20, 50)
|
||||||
|
db[2].fetchmany.return_value = [row]
|
||||||
|
status = read().get_current_workplace_status('K7')
|
||||||
|
assert status.feedback_timestamp.isoformat() == '2026-01-04T21:20:50+01:00'
|
||||||
|
assert status.feedback_timestamp.tzinfo == ZoneInfo('Europe/Berlin')
|
||||||
|
assert status.feedback_timestamp.utcoffset() == timedelta(hours=1)
|
||||||
@@ -0,0 +1,302 @@
|
|||||||
|
import re
|
||||||
|
import traceback
|
||||||
|
from dataclasses import FrozenInstanceError
|
||||||
|
from datetime import UTC, datetime, timedelta
|
||||||
|
from decimal import Decimal
|
||||||
|
from unittest.mock import MagicMock
|
||||||
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from production_analytics.erp import (
|
||||||
|
ErpProductionConfirmationGateway,
|
||||||
|
ErpReadError,
|
||||||
|
ErpSettings,
|
||||||
|
ProductionConfirmation,
|
||||||
|
)
|
||||||
|
|
||||||
|
BERLIN = ZoneInfo("Europe/Berlin")
|
||||||
|
START = datetime(2026, 9, 4, 6, tzinfo=BERLIN)
|
||||||
|
END = START + timedelta(hours=8)
|
||||||
|
DB_TIME = datetime(2026, 9, 4, 8, 20)
|
||||||
|
ROW = (
|
||||||
|
"tenant ",
|
||||||
|
"order-001 ",
|
||||||
|
DB_TIME,
|
||||||
|
"BENTO 1 ",
|
||||||
|
"article-001 ",
|
||||||
|
"4.85 x 40 m ",
|
||||||
|
"roll-001 ",
|
||||||
|
Decimal("194.0000"),
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
Decimal("194.0000"),
|
||||||
|
Decimal("0"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def db(monkeypatch):
|
||||||
|
connect = MagicMock()
|
||||||
|
monkeypatch.setattr("production_analytics.erp.gateway.pymssql.connect", connect)
|
||||||
|
connection = connect.return_value.__enter__.return_value
|
||||||
|
cursor = connection.cursor.return_value.__enter__.return_value
|
||||||
|
cursor.fetchall.return_value = [ROW]
|
||||||
|
return connect, connection, cursor
|
||||||
|
|
||||||
|
|
||||||
|
def gateway():
|
||||||
|
return ErpProductionConfirmationGateway(
|
||||||
|
ErpSettings("localhost", 49601, "NV_DWH", "private-user", "private-password")
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def read(**kwargs):
|
||||||
|
return gateway().get_confirmations(
|
||||||
|
**{"workplace": "BENTO 1", "start": START, "end": END, **kwargs}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_finished_goods_mapping_and_connection_lifecycle(db):
|
||||||
|
connect, connection, cursor = db
|
||||||
|
confirmation = read()[0]
|
||||||
|
assert isinstance(confirmation, ProductionConfirmation)
|
||||||
|
assert confirmation.workplace == "BENTO 1"
|
||||||
|
assert confirmation.production_order == "order-001"
|
||||||
|
assert confirmation.tenant == "tenant"
|
||||||
|
assert confirmation.article_number == "article-001"
|
||||||
|
assert confirmation.article_description == "4.85 x 40 m"
|
||||||
|
assert confirmation.roll_number == "roll-001"
|
||||||
|
assert confirmation.production_quantity_m2 == confirmation.feedback_quantity_m2 == 194.0
|
||||||
|
assert type(confirmation.feedback_quantity_m2) is float
|
||||||
|
assert confirmation.raw_material_quantity == 0.0
|
||||||
|
assert confirmation.raw_material_number is None
|
||||||
|
assert confirmation.raw_material_description is None
|
||||||
|
assert confirmation.batch_number is None
|
||||||
|
assert confirmation.is_finished_goods
|
||||||
|
assert confirmation.timestamp == DB_TIME.replace(tzinfo=BERLIN)
|
||||||
|
assert confirmation.timestamp.tzinfo is BERLIN
|
||||||
|
assert confirmation.timestamp.astimezone(UTC) == datetime(2026, 9, 4, 6, 20, tzinfo=UTC)
|
||||||
|
with pytest.raises(FrozenInstanceError):
|
||||||
|
confirmation.workplace = "other"
|
||||||
|
connect.assert_called_once_with(
|
||||||
|
server="localhost",
|
||||||
|
port=49601,
|
||||||
|
database="NV_DWH",
|
||||||
|
user="private-user",
|
||||||
|
password="private-password",
|
||||||
|
login_timeout=10,
|
||||||
|
timeout=10,
|
||||||
|
)
|
||||||
|
cursor.fetchall.assert_called_once_with()
|
||||||
|
connection.cursor.return_value.__exit__.assert_called_once()
|
||||||
|
connect.return_value.__exit__.assert_called_once()
|
||||||
|
connection.commit.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
def test_exact_parameterized_workplace_and_half_open_window(db):
|
||||||
|
workplace = " BENTO 1'; DELETE FROM anything; -- "
|
||||||
|
read(workplace=workplace, start=START.astimezone(UTC), end=END.astimezone(UTC))
|
||||||
|
sql, params = db[2].execute.call_args.args
|
||||||
|
assert params == (workplace.strip(), START.replace(tzinfo=None), END.replace(tzinfo=None))
|
||||||
|
assert workplace.strip() not in sql
|
||||||
|
assert "WHERE [Arbeitsplatz] = %s AND [Zeitstempel] >= %s AND [Zeitstempel] < %s" in sql
|
||||||
|
assert re.findall(r"FROM\s+(\S+)", sql) == ["[dbo].[GRAFANA_PRODUCTION_CONFIRMATION]"]
|
||||||
|
assert "ORDER BY [Zeitstempel], [Mandant], [Fertigungsauftragsnummer], [Rollennummer]" in sql
|
||||||
|
assert not re.search(r"\b(INSERT|UPDATE|DELETE|MERGE|EXEC|TOP|LIKE)\b", sql, re.I)
|
||||||
|
assert "[Rückmeldemenge] >" not in sql
|
||||||
|
|
||||||
|
|
||||||
|
def test_half_open_boundaries_with_query_simulation(db):
|
||||||
|
rows = [
|
||||||
|
tuple([*ROW[:2], timestamp, *ROW[3:]])
|
||||||
|
for timestamp in (
|
||||||
|
START.replace(tzinfo=None) - timedelta(seconds=1),
|
||||||
|
START.replace(tzinfo=None),
|
||||||
|
END.replace(tzinfo=None) - timedelta(seconds=1),
|
||||||
|
END.replace(tzinfo=None),
|
||||||
|
)
|
||||||
|
]
|
||||||
|
|
||||||
|
def execute(sql, params):
|
||||||
|
assert "[Zeitstempel] >= %s AND [Zeitstempel] < %s" in sql
|
||||||
|
db[2].fetchall.return_value = [row for row in rows if params[1] <= row[2] < params[2]]
|
||||||
|
|
||||||
|
db[2].execute.side_effect = execute
|
||||||
|
assert [value.timestamp for value in read()] == [START, END - timedelta(seconds=1)]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("workplace", [None, 123, "", " ", "BENTO\x00 1"])
|
||||||
|
def test_invalid_workplace_before_connect(db, workplace):
|
||||||
|
with pytest.raises(ValueError, match="workplace"):
|
||||||
|
read(workplace=workplace)
|
||||||
|
db[0].assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("field", ["start", "end"])
|
||||||
|
@pytest.mark.parametrize("value", [DB_TIME, None, "2026-09-04"])
|
||||||
|
def test_requires_aware_datetimes(db, field, value):
|
||||||
|
with pytest.raises(ValueError, match=f"{field} must be a timezone-aware datetime"):
|
||||||
|
read(**{field: value})
|
||||||
|
db[0].assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("end", [START, START - timedelta(seconds=1)])
|
||||||
|
def test_end_must_follow_start(db, end):
|
||||||
|
with pytest.raises(ValueError, match="end must follow start"):
|
||||||
|
read(end=end)
|
||||||
|
db[0].assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
def test_raw_material_row_returned_without_finished_goods_filter(db):
|
||||||
|
row = list(ROW)
|
||||||
|
row[6:13] = [
|
||||||
|
None,
|
||||||
|
Decimal("0"),
|
||||||
|
"raw-001 ",
|
||||||
|
"Raw material ",
|
||||||
|
"batch-001 ",
|
||||||
|
Decimal("0"),
|
||||||
|
Decimal("123.1250"),
|
||||||
|
]
|
||||||
|
db[2].fetchall.return_value = [ROW, row]
|
||||||
|
finished, material = read()
|
||||||
|
assert finished.is_finished_goods
|
||||||
|
assert not material.is_finished_goods
|
||||||
|
assert material.production_quantity_m2 == material.feedback_quantity_m2 == 0.0
|
||||||
|
assert material.raw_material_quantity == 123.125
|
||||||
|
assert (
|
||||||
|
material.raw_material_number,
|
||||||
|
material.raw_material_description,
|
||||||
|
material.batch_number,
|
||||||
|
) == ("raw-001", "Raw material", "batch-001")
|
||||||
|
assert material.roll_number is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_nullable_fields_and_empty_result(db):
|
||||||
|
db[2].fetchall.return_value = [(None, "order", DB_TIME, "K7", *([None] * 9))]
|
||||||
|
value = read(workplace="K7")[0]
|
||||||
|
assert not value.is_finished_goods
|
||||||
|
assert all(
|
||||||
|
getattr(value, field) is None
|
||||||
|
for field in (
|
||||||
|
"tenant",
|
||||||
|
"article_number",
|
||||||
|
"article_description",
|
||||||
|
"roll_number",
|
||||||
|
"production_quantity_m2",
|
||||||
|
"feedback_quantity_m2",
|
||||||
|
"raw_material_number",
|
||||||
|
"raw_material_description",
|
||||||
|
"batch_number",
|
||||||
|
"raw_material_quantity",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
db[2].fetchall.return_value = []
|
||||||
|
assert read() == []
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("index", [7, 11, 12])
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"value",
|
||||||
|
[
|
||||||
|
Decimal("NaN"),
|
||||||
|
Decimal("Infinity"),
|
||||||
|
Decimal("1e999"),
|
||||||
|
float("nan"),
|
||||||
|
float("-inf"),
|
||||||
|
True,
|
||||||
|
"private-password",
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_invalid_numeric_values_are_safe(db, index, value):
|
||||||
|
row = list(ROW)
|
||||||
|
row[index] = value
|
||||||
|
db[2].fetchall.return_value = [row]
|
||||||
|
with pytest.raises(ErpReadError, match="invalid row") as error:
|
||||||
|
read()
|
||||||
|
assert "private-password" not in "".join(traceback.format_exception(error.value))
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"row",
|
||||||
|
[
|
||||||
|
ROW[:-1],
|
||||||
|
(*ROW, "extra"),
|
||||||
|
(*ROW[:2], None, *ROW[3:]),
|
||||||
|
(*ROW[:2], DB_TIME.replace(tzinfo=UTC), *ROW[3:]),
|
||||||
|
(*ROW[:3], None, *ROW[4:]),
|
||||||
|
(ROW[0], 123, *ROW[2:]),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_malformed_rows_are_safe(db, row):
|
||||||
|
db[2].fetchall.return_value = [row]
|
||||||
|
with pytest.raises(ErpReadError, match="invalid row"):
|
||||||
|
read()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("stage", ["connect", "execute", "fetch", "cursor_close", "close"])
|
||||||
|
def test_driver_errors_are_safe(db, stage):
|
||||||
|
connect, connection, cursor = db
|
||||||
|
target = {
|
||||||
|
"connect": connect,
|
||||||
|
"execute": cursor.execute,
|
||||||
|
"fetch": cursor.fetchall,
|
||||||
|
"cursor_close": connection.cursor.return_value.__exit__,
|
||||||
|
"close": connect.return_value.__exit__,
|
||||||
|
}[stage]
|
||||||
|
target.side_effect = RuntimeError("private-user private-password")
|
||||||
|
with pytest.raises(ErpReadError, match="read failed") as error:
|
||||||
|
read()
|
||||||
|
rendered = "".join(traceback.format_exception(error.value))
|
||||||
|
assert "private-user" not in rendered and "private-password" not in rendered
|
||||||
|
if stage != "connect":
|
||||||
|
connect.return_value.__exit__.assert_called_once()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"local,offset",
|
||||||
|
[
|
||||||
|
(datetime(2026, 3, 29, 1, 30), 1),
|
||||||
|
(datetime(2026, 3, 29, 3, 30), 2),
|
||||||
|
(datetime(2026, 10, 25, 1, 30), 2),
|
||||||
|
(datetime(2026, 10, 25, 3, 30), 1),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_dst_offsets_follow_local_plant_time(db, local, offset):
|
||||||
|
db[2].fetchall.return_value = [(*ROW[:2], local, *ROW[3:])]
|
||||||
|
start = local.replace(tzinfo=BERLIN)
|
||||||
|
confirmation = read(start=start.astimezone(UTC), end=start + timedelta(minutes=10))[0]
|
||||||
|
assert confirmation.timestamp.replace(tzinfo=None) == local
|
||||||
|
assert confirmation.timestamp.utcoffset() == timedelta(hours=offset)
|
||||||
|
assert db[2].execute.call_args.args[1][1] == local
|
||||||
|
|
||||||
|
|
||||||
|
def test_window_across_spring_dst_transition(db):
|
||||||
|
start = datetime(2026, 3, 29, 0, 30, tzinfo=UTC)
|
||||||
|
end = datetime(2026, 3, 29, 1, 30, tzinfo=UTC)
|
||||||
|
read(start=start, end=end)
|
||||||
|
assert db[2].execute.call_args.args[1][1:] == (
|
||||||
|
datetime(2026, 3, 29, 1, 30),
|
||||||
|
datetime(2026, 3, 29, 3, 30),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_ambiguous_db_timestamp_uses_documented_first_occurrence(db):
|
||||||
|
local = datetime(2026, 10, 25, 2, 30)
|
||||||
|
db[2].fetchall.return_value = [(*ROW[:2], local, *ROW[3:])]
|
||||||
|
confirmation = read(
|
||||||
|
start=datetime(2026, 10, 25, 0, tzinfo=UTC), end=datetime(2026, 10, 25, 3, tzinfo=UTC)
|
||||||
|
)[0]
|
||||||
|
assert confirmation.timestamp.fold == 0
|
||||||
|
assert confirmation.timestamp.astimezone(UTC) == datetime(2026, 10, 25, 0, 30, tzinfo=UTC)
|
||||||
|
|
||||||
|
|
||||||
|
def test_unrepresentable_repeated_hour_interval_is_rejected(db):
|
||||||
|
with pytest.raises(ValueError, match="plant-local SQL time"):
|
||||||
|
read(
|
||||||
|
start=datetime(2026, 10, 25, 2, 45, tzinfo=BERLIN, fold=0),
|
||||||
|
end=datetime(2026, 10, 25, 2, 15, tzinfo=BERLIN, fold=1),
|
||||||
|
)
|
||||||
|
db[0].assert_not_called()
|
||||||
@@ -0,0 +1,215 @@
|
|||||||
|
import traceback
|
||||||
|
from datetime import UTC, datetime, timedelta
|
||||||
|
from unittest.mock import MagicMock
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from production_analytics.service.postgres_material import PostgresSettings
|
||||||
|
from production_analytics.service.postgres_shift_material import (
|
||||||
|
PostgresShiftChannelMaterialRepository,
|
||||||
|
PostgresShiftMaterialRepository,
|
||||||
|
ShiftMaterialReadError,
|
||||||
|
)
|
||||||
|
|
||||||
|
START = datetime(2026, 10, 7, 4, tzinfo=UTC)
|
||||||
|
END = START + timedelta(hours=8)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(params=[False, True], ids=["machine", "channel"])
|
||||||
|
def db(request, monkeypatch):
|
||||||
|
connect = MagicMock()
|
||||||
|
monkeypatch.setattr("psycopg.connect", connect)
|
||||||
|
connection = connect.return_value.__enter__.return_value
|
||||||
|
channel = request.param
|
||||||
|
row = (
|
||||||
|
(
|
||||||
|
START,
|
||||||
|
"calc",
|
||||||
|
"machine",
|
||||||
|
"Ex1",
|
||||||
|
"C2",
|
||||||
|
"order",
|
||||||
|
"run",
|
||||||
|
123.0,
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
"UNAVAILABLE",
|
||||||
|
True,
|
||||||
|
)
|
||||||
|
if channel
|
||||||
|
else (START, "calc", "machine", "order", "run", 123.0)
|
||||||
|
)
|
||||||
|
connection.execute.return_value.fetchall.return_value = [row]
|
||||||
|
cls = PostgresShiftChannelMaterialRepository if channel else PostgresShiftMaterialRepository
|
||||||
|
return (
|
||||||
|
cls(PostgresSettings("localhost", 5432, "db", "user", "pw")),
|
||||||
|
connect,
|
||||||
|
connection,
|
||||||
|
channel,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def read(repository, **changes):
|
||||||
|
return repository.get_snapshots(
|
||||||
|
**{
|
||||||
|
"machine_id": "machine",
|
||||||
|
"calculation_ids": ("calc",),
|
||||||
|
"start": START,
|
||||||
|
"end": END,
|
||||||
|
**changes,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_one_query_parameterization_baseline_and_strict_end(db):
|
||||||
|
repository, connect, connection, channel = db
|
||||||
|
snapshots = read(repository)
|
||||||
|
sql, params = connection.execute.call_args.args
|
||||||
|
assert params == ("machine", ["calc"], START, END)
|
||||||
|
assert "timestamp <= r.start_time" in sql
|
||||||
|
assert "timestamp > r.start_time AND timestamp < r.end_time" in sql
|
||||||
|
assert "UNION ALL" in sql
|
||||||
|
assert "EXISTS" not in sql and "DENSE_RANK" not in sql and "scoped" not in sql
|
||||||
|
assert "MIN(" not in sql and "MAX(" not in sql
|
||||||
|
assert "calculation_id = ANY(r.calculation_ids)" in sql
|
||||||
|
assert ("FROM channel_material_consumption_snapshots" in sql) is channel
|
||||||
|
assert ("FROM material_consumption_snapshots" in sql) is not channel
|
||||||
|
if channel:
|
||||||
|
assert "DISTINCT ON (s.calculation_id, extruder, doser_channel)" in sql
|
||||||
|
assert "ORDER BY s.calculation_id, extruder, doser_channel, timestamp DESC" in sql
|
||||||
|
else:
|
||||||
|
assert "unnest(r.calculation_ids)" in sql
|
||||||
|
assert "calculation_id = ids.calculation_id AND machine_id = r.machine_id" in sql
|
||||||
|
assert "ORDER BY timestamp DESC, run_id, production_order" in sql
|
||||||
|
assert "LIMIT 1" in sql
|
||||||
|
# Valid baseline filters never affect the in-window branch, which must keep
|
||||||
|
# null, non-finite, and negative counters for run/reset validation.
|
||||||
|
baseline, window = sql.split("UNION ALL")
|
||||||
|
counter = "cumulative_consumption_kg" if channel else "consumption_kg"
|
||||||
|
assert f"{counter} >= 0" in baseline
|
||||||
|
assert f"{counter} < 'Infinity'::double precision" in baseline
|
||||||
|
assert f"{counter} >=" not in window and f"{counter} <" not in window
|
||||||
|
order = "calculation_id, " + ("extruder, doser_channel, " if channel else "")
|
||||||
|
assert sql.rstrip().endswith(f"ORDER BY {order}timestamp, run_id, production_order")
|
||||||
|
connection.execute.assert_called_once()
|
||||||
|
connection.execute.return_value.fetchall.assert_called_once()
|
||||||
|
connect.assert_called_once_with(
|
||||||
|
host="localhost",
|
||||||
|
port=5432,
|
||||||
|
dbname="db",
|
||||||
|
user="user",
|
||||||
|
password="pw",
|
||||||
|
connect_timeout=10,
|
||||||
|
options="-c statement_timeout=10000",
|
||||||
|
)
|
||||||
|
connect.return_value.__exit__.assert_called_once()
|
||||||
|
assert snapshots[0].run_id == "run"
|
||||||
|
assert snapshots[0].timestamp is START
|
||||||
|
if channel:
|
||||||
|
assert snapshots[0].material_name is None
|
||||||
|
assert snapshots[0].doser_channel == "C2"
|
||||||
|
assert snapshots[0].material_mapping_status == "UNAVAILABLE"
|
||||||
|
connection.commit.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
def test_parameterized_multiple_calculations(db):
|
||||||
|
ids = ("calc'; DELETE FROM x; --", "second")
|
||||||
|
read(db[0], calculation_ids=ids)
|
||||||
|
sql, params = db[2].execute.call_args.args
|
||||||
|
assert params[1] == list(ids)
|
||||||
|
assert ids[0] not in sql
|
||||||
|
|
||||||
|
|
||||||
|
def test_validation_before_connect(db):
|
||||||
|
for changes in (
|
||||||
|
{"start": START.replace(tzinfo=None)},
|
||||||
|
{"end": START},
|
||||||
|
{"machine_id": "bad\x00"},
|
||||||
|
{"calculation_ids": ()},
|
||||||
|
):
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
read(db[0], **changes)
|
||||||
|
db[1].assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
def test_empty_result(db):
|
||||||
|
db[2].execute.return_value.fetchall.return_value = []
|
||||||
|
assert read(db[0]) == []
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("stage", ["connect", "execute", "fetch", "close"])
|
||||||
|
def test_safe_driver_errors(db, stage):
|
||||||
|
repository, connect, connection, _ = db
|
||||||
|
target = {
|
||||||
|
"connect": connect,
|
||||||
|
"execute": connection.execute,
|
||||||
|
"fetch": connection.execute.return_value.fetchall,
|
||||||
|
"close": connect.return_value.__exit__,
|
||||||
|
}[stage]
|
||||||
|
target.side_effect = RuntimeError("private-password")
|
||||||
|
with pytest.raises(ShiftMaterialReadError, match="read failed") as error:
|
||||||
|
read(repository)
|
||||||
|
assert "private-password" not in "".join(traceback.format_exception(error.value))
|
||||||
|
|
||||||
|
|
||||||
|
def test_invalid_row_shape_wrapped(db):
|
||||||
|
db[2].execute.return_value.fetchall.return_value = [("bad",)]
|
||||||
|
with pytest.raises(ShiftMaterialReadError, match="invalid row"):
|
||||||
|
read(db[0])
|
||||||
|
|
||||||
|
|
||||||
|
def test_multiple_baselines_and_raw_window_rows_are_preserved(db):
|
||||||
|
repository, _, connection, channel = db
|
||||||
|
original = connection.execute.return_value.fetchall.return_value[0]
|
||||||
|
counter_index = 7 if channel else 5
|
||||||
|
|
||||||
|
def row(timestamp, value, calculation="calc", stream="C2"):
|
||||||
|
values = list(original)
|
||||||
|
values[0], values[1], values[counter_index] = timestamp, calculation, value
|
||||||
|
if channel:
|
||||||
|
values[4] = stream
|
||||||
|
return tuple(values)
|
||||||
|
|
||||||
|
# A baseline per calculation (and per channel), exact-start baseline, and
|
||||||
|
# raw null/reset rows all survive repository decoding without carry-forward.
|
||||||
|
rows = [
|
||||||
|
row(START, 100),
|
||||||
|
row(START + timedelta(seconds=1), None),
|
||||||
|
row(START + timedelta(seconds=2), -1),
|
||||||
|
row(END - timedelta(microseconds=1), 110),
|
||||||
|
]
|
||||||
|
if channel:
|
||||||
|
rows += [row(START, 200, stream="C3"), row(START + timedelta(seconds=1), 205, stream="C3")]
|
||||||
|
rows += [row(START - timedelta(seconds=1), 300, calculation="second")]
|
||||||
|
connection.execute.return_value.fetchall.return_value = rows
|
||||||
|
snapshots = read(repository, calculation_ids=("calc", "second"))
|
||||||
|
assert [snapshot.timestamp for snapshot in snapshots] == [row[0] for row in rows]
|
||||||
|
counter = "cumulative_consumption_kg" if channel else "consumption_kg"
|
||||||
|
assert [getattr(snapshot, counter) for snapshot in snapshots] == [
|
||||||
|
row[counter_index] for row in rows
|
||||||
|
]
|
||||||
|
assert {snapshot.calculation_id for snapshot in snapshots} == {"calc", "second"}
|
||||||
|
if channel:
|
||||||
|
assert {snapshot.doser_channel for snapshot in snapshots} == {"C2", "C3"}
|
||||||
|
assert all(snapshot.material_name is None for snapshot in snapshots)
|
||||||
|
connection.execute.assert_called_once()
|
||||||
|
|
||||||
|
|
||||||
|
def test_missing_baseline_leaves_in_window_sample_for_fallback(db):
|
||||||
|
repository, _, connection, _ = db
|
||||||
|
values = list(connection.execute.return_value.fetchall.return_value[0])
|
||||||
|
values[0] = START + timedelta(minutes=1)
|
||||||
|
connection.execute.return_value.fetchall.return_value = [tuple(values)]
|
||||||
|
snapshots = read(repository)
|
||||||
|
assert len(snapshots) == 1
|
||||||
|
assert snapshots[0].timestamp == START + timedelta(minutes=1)
|
||||||
|
from production_analytics.calculations.shift_material import (
|
||||||
|
aggregate_shift_channel_material,
|
||||||
|
aggregate_shift_material,
|
||||||
|
)
|
||||||
|
|
||||||
|
aggregate = aggregate_shift_channel_material if db[3] else aggregate_shift_material
|
||||||
|
summary = aggregate(snapshots, machine_id="machine", calculation_ids=("calc",),
|
||||||
|
start=START, end=END)
|
||||||
|
assert summary.total_consumption_kg == 0
|
||||||
|
assert summary.items[0].baseline_missing
|
||||||
@@ -0,0 +1,317 @@
|
|||||||
|
import traceback
|
||||||
|
from dataclasses import FrozenInstanceError, replace
|
||||||
|
from datetime import UTC, datetime, timedelta
|
||||||
|
from unittest.mock import MagicMock, Mock
|
||||||
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from production_analytics.calculations.shift_downtime import (
|
||||||
|
ShiftDowntimeEvent,
|
||||||
|
aggregate_shift_downtime,
|
||||||
|
)
|
||||||
|
from production_analytics.service.postgres_downtime import (
|
||||||
|
DowntimeReadError,
|
||||||
|
PostgresDowntimeRepository,
|
||||||
|
)
|
||||||
|
from production_analytics.service.postgres_material import PostgresSettings
|
||||||
|
from production_analytics.service.shift_downtime import ShiftDowntimeService
|
||||||
|
|
||||||
|
BERLIN = ZoneInfo("Europe/Berlin")
|
||||||
|
START = datetime(2026, 10, 7, 6, tzinfo=BERLIN)
|
||||||
|
END = START + timedelta(hours=8)
|
||||||
|
|
||||||
|
|
||||||
|
def event(identifier="event", *, start=START, end=END, reason="Reason", **changes):
|
||||||
|
return replace(
|
||||||
|
ShiftDowntimeEvent(
|
||||||
|
identifier,
|
||||||
|
"machine",
|
||||||
|
start,
|
||||||
|
end,
|
||||||
|
"reason-id",
|
||||||
|
reason,
|
||||||
|
"Description",
|
||||||
|
"Group",
|
||||||
|
"PLANNED",
|
||||||
|
"Comment",
|
||||||
|
),
|
||||||
|
**changes,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def summarize(events, **changes):
|
||||||
|
return aggregate_shift_downtime(
|
||||||
|
events,
|
||||||
|
**{
|
||||||
|
"machine_id": "machine",
|
||||||
|
"start": START,
|
||||||
|
"end": END,
|
||||||
|
**changes,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_clip_both_boundaries_preserve_source_and_immutable_results():
|
||||||
|
source = event(start=START - timedelta(hours=1), end=END + timedelta(hours=1))
|
||||||
|
summary = summarize([source])
|
||||||
|
assert summary.shift_duration_seconds == summary.total_downtime_seconds == 480 * 60
|
||||||
|
assert summary.non_downtime_seconds == 0
|
||||||
|
clipped = summary.events[0]
|
||||||
|
assert clipped.source is source
|
||||||
|
assert clipped.start is START and clipped.end is END
|
||||||
|
assert clipped.duration_seconds == 480 * 60
|
||||||
|
assert summary.reasons[0].duration_seconds == 480 * 60
|
||||||
|
assert summary.reasons[0].event_count == 1
|
||||||
|
assert summary.reasons[0].reason_description == "Description"
|
||||||
|
assert clipped.source.comment == "Comment"
|
||||||
|
for value, field in (
|
||||||
|
(source, "comment"),
|
||||||
|
(summary, "machine_id"),
|
||||||
|
(clipped, "start"),
|
||||||
|
(summary.reasons[0], "reason_name"),
|
||||||
|
):
|
||||||
|
with pytest.raises(FrozenInstanceError):
|
||||||
|
setattr(value, field, None)
|
||||||
|
|
||||||
|
|
||||||
|
def test_open_event_clipped_to_shift_end():
|
||||||
|
summary = summarize([event(start=START + timedelta(hours=7), end=None)])
|
||||||
|
assert summary.total_downtime_seconds == 3600
|
||||||
|
assert summary.non_downtime_seconds == 7 * 3600
|
||||||
|
assert summary.events[0].end is END
|
||||||
|
assert summary.events[0].source.source_end is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_overlap_nested_duplicates_and_adjacent_intervals_are_not_double_counted():
|
||||||
|
events = [
|
||||||
|
event("a", end=START + timedelta(hours=2)),
|
||||||
|
event("b", start=START + timedelta(hours=1), end=START + timedelta(hours=3)),
|
||||||
|
event("c", start=START + timedelta(minutes=30), end=START + timedelta(hours=1)),
|
||||||
|
event("d", start=START + timedelta(hours=3), end=START + timedelta(hours=4)),
|
||||||
|
]
|
||||||
|
summary = summarize([*events, events[0]])
|
||||||
|
assert summary.total_downtime_seconds == 4 * 3600
|
||||||
|
assert summary.non_downtime_seconds == 4 * 3600
|
||||||
|
assert summary.reasons[0].duration_seconds == 4 * 3600
|
||||||
|
|
||||||
|
|
||||||
|
def test_overlapping_different_reasons_do_not_inflate_total():
|
||||||
|
summary = summarize(
|
||||||
|
[
|
||||||
|
event("a", end=START + timedelta(hours=2), reason="A"),
|
||||||
|
event(
|
||||||
|
"b", start=START + timedelta(hours=1), end=START + timedelta(hours=3), reason="B"
|
||||||
|
),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
assert summary.total_downtime_seconds == 3 * 3600
|
||||||
|
assert sum(reason.duration_seconds for reason in summary.reasons) == 4 * 3600
|
||||||
|
assert summary.non_downtime_seconds == 5 * 3600
|
||||||
|
|
||||||
|
|
||||||
|
def test_half_open_window_excludes_touching_zero_length_and_other_machine_events():
|
||||||
|
summary = summarize(
|
||||||
|
[
|
||||||
|
event("before", start=START - timedelta(hours=1), end=START),
|
||||||
|
event("after", start=END, end=END + timedelta(hours=1)),
|
||||||
|
event("zero", start=START, end=START),
|
||||||
|
event("other", machine_id="other"),
|
||||||
|
event("future-open", start=END, end=None),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
assert summary.events == summary.reasons == ()
|
||||||
|
assert summary.total_downtime_seconds == 0
|
||||||
|
assert summary.non_downtime_seconds == 480 * 60
|
||||||
|
|
||||||
|
|
||||||
|
def test_empty_shift():
|
||||||
|
summary = summarize([])
|
||||||
|
assert summary.total_downtime_seconds == 0
|
||||||
|
assert summary.non_downtime_seconds == summary.shift_duration_seconds == 480 * 60
|
||||||
|
|
||||||
|
|
||||||
|
def test_example_reason_totals_using_synthetic_intervals_matching_supplied_approximations():
|
||||||
|
# Exact synthetic durations chosen within the supplied rounded real-data examples.
|
||||||
|
intervals = [
|
||||||
|
("clean", "Reinigung", -10, 50.84),
|
||||||
|
("setup1", "Rüstzeit Auftragsbeginn", 60, 91.34),
|
||||||
|
("mechanical", "212 - Hülsenzuführung mechanisch", 180, 59.22),
|
||||||
|
("setup2", "Rüstzeit Auftragsbeginn", 469.2, 10.8),
|
||||||
|
]
|
||||||
|
events = [
|
||||||
|
event(
|
||||||
|
identifier,
|
||||||
|
reason=reason,
|
||||||
|
start=START + timedelta(minutes=minute),
|
||||||
|
end=START + timedelta(minutes=max(0, minute) + duration),
|
||||||
|
)
|
||||||
|
for identifier, reason, minute, duration in intervals
|
||||||
|
]
|
||||||
|
summary = summarize(events)
|
||||||
|
assert summary.total_downtime_seconds / 60 == pytest.approx(212.2)
|
||||||
|
assert summary.non_downtime_seconds / 60 == pytest.approx(267.8)
|
||||||
|
assert [
|
||||||
|
(value.reason_name, round(value.duration_seconds / 60, 1)) for value in summary.reasons
|
||||||
|
] == [
|
||||||
|
("Rüstzeit Auftragsbeginn", 102.1),
|
||||||
|
("212 - Hülsenzuführung mechanisch", 59.2),
|
||||||
|
("Reinigung", 50.8),
|
||||||
|
]
|
||||||
|
assert summary.reasons[0].event_count == 2
|
||||||
|
|
||||||
|
|
||||||
|
def test_nullable_reasons_and_deterministic_order():
|
||||||
|
events = [
|
||||||
|
event(
|
||||||
|
"z",
|
||||||
|
reason=None,
|
||||||
|
reason_id=None,
|
||||||
|
reason_description=None,
|
||||||
|
reason_group=None,
|
||||||
|
category=None,
|
||||||
|
comment=None,
|
||||||
|
end=START + timedelta(minutes=1),
|
||||||
|
),
|
||||||
|
event("a", reason="A", end=START + timedelta(minutes=1)),
|
||||||
|
]
|
||||||
|
summary = summarize(events)
|
||||||
|
assert summary == summarize(reversed(events))
|
||||||
|
assert [value.source.external_id for value in summary.events] == ["a", "z"]
|
||||||
|
assert any(reason.reason_id is None for reason in summary.reasons)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("date,hours", [(datetime(2026, 3, 29), 7), (datetime(2026, 10, 25), 9)])
|
||||||
|
def test_dst_uses_elapsed_time_not_wall_clock_duration(date, hours):
|
||||||
|
start = date.replace(tzinfo=BERLIN)
|
||||||
|
end = start + timedelta(hours=8)
|
||||||
|
summary = summarize([event(start=start, end=end)], start=start, end=end)
|
||||||
|
assert summary.total_downtime_seconds == summary.shift_duration_seconds == hours * 3600
|
||||||
|
assert summary.start is start and summary.end is end
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def db(monkeypatch):
|
||||||
|
connect = MagicMock()
|
||||||
|
monkeypatch.setattr("psycopg.connect", connect)
|
||||||
|
connection = connect.return_value.__enter__.return_value
|
||||||
|
connection.execute.return_value.fetchall.return_value = [
|
||||||
|
(
|
||||||
|
"id",
|
||||||
|
"machine",
|
||||||
|
START.astimezone(UTC),
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
"UNKNOWN",
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
]
|
||||||
|
repository = PostgresDowntimeRepository(PostgresSettings("localhost", 5432, "db", "user", "pw"))
|
||||||
|
return repository, connect, connection
|
||||||
|
|
||||||
|
|
||||||
|
def test_repository_sql_parameters_mapping_and_lifecycle(db):
|
||||||
|
repository, connect, connection = db
|
||||||
|
values = repository.get_events(machine_id="machine", start=START, end=END)
|
||||||
|
sql, params = connection.execute.call_args.args
|
||||||
|
assert params == ("machine", END, START)
|
||||||
|
assert "WHERE machine_id = %s AND source_start < %s" in sql
|
||||||
|
assert "source_end IS NULL OR source_end > %s" in sql
|
||||||
|
assert "ORDER BY source_start, external_id" in sql
|
||||||
|
assert "attributed_" not in sql and "production_order" not in sql
|
||||||
|
assert len(values) == 1 and values[0].source_end is None
|
||||||
|
assert values[0].source_start.tzinfo is UTC
|
||||||
|
connect.assert_called_once_with(
|
||||||
|
host="localhost",
|
||||||
|
port=5432,
|
||||||
|
dbname="db",
|
||||||
|
user="user",
|
||||||
|
password="pw",
|
||||||
|
connect_timeout=10,
|
||||||
|
options="-c statement_timeout=10000",
|
||||||
|
)
|
||||||
|
connect.return_value.__exit__.assert_called_once()
|
||||||
|
connection.commit.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
def test_machine_id_is_parameterized(db):
|
||||||
|
machine_id = "id'; DELETE FROM anything; --"
|
||||||
|
db[0].get_events(machine_id=machine_id, start=START, end=END)
|
||||||
|
sql, params = db[2].execute.call_args.args
|
||||||
|
assert machine_id not in sql
|
||||||
|
assert params[0] == machine_id
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"changes",
|
||||||
|
[
|
||||||
|
{"machine_id": ""},
|
||||||
|
{"machine_id": " "},
|
||||||
|
{"machine_id": "bad\x00"},
|
||||||
|
{"start": START.replace(tzinfo=None)},
|
||||||
|
{"end": END.replace(tzinfo=None)},
|
||||||
|
{"start": None},
|
||||||
|
{"end": START},
|
||||||
|
{"end": START - timedelta(seconds=1)},
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_invalid_window_before_database_read(db, changes):
|
||||||
|
inputs = {"machine_id": "machine", "start": START, "end": END, **changes}
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
db[0].get_events(**inputs)
|
||||||
|
db[1].assert_not_called()
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
aggregate_shift_downtime([], **inputs)
|
||||||
|
reader = Mock()
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
ShiftDowntimeService(reader).summarize(**inputs)
|
||||||
|
reader.get_events.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("stage", ["connect", "execute", "fetch", "close"])
|
||||||
|
def test_repository_errors_are_safe(db, stage):
|
||||||
|
repository, connect, connection = db
|
||||||
|
target = {
|
||||||
|
"connect": connect,
|
||||||
|
"execute": connection.execute,
|
||||||
|
"fetch": connection.execute.return_value.fetchall,
|
||||||
|
"close": connect.return_value.__exit__,
|
||||||
|
}[stage]
|
||||||
|
target.side_effect = RuntimeError("private-password")
|
||||||
|
with pytest.raises(DowntimeReadError, match="read failed") as error:
|
||||||
|
repository.get_events(machine_id="machine", start=START, end=END)
|
||||||
|
assert "private-password" not in "".join(traceback.format_exception(error.value))
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"changes",
|
||||||
|
[
|
||||||
|
{"source_start": START.replace(tzinfo=None)},
|
||||||
|
{"source_end": END.replace(tzinfo=None)},
|
||||||
|
{"source_end": START - timedelta(seconds=1)},
|
||||||
|
{"reason_name": 123},
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_invalid_source_model(changes):
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
event(**changes)
|
||||||
|
|
||||||
|
|
||||||
|
def test_repository_invalid_row_is_wrapped(db):
|
||||||
|
db[2].execute.return_value.fetchall.return_value = [("invalid-row",)]
|
||||||
|
with pytest.raises(DowntimeReadError, match="invalid row"):
|
||||||
|
db[0].get_events(machine_id="machine", start=START, end=END)
|
||||||
|
|
||||||
|
|
||||||
|
def test_service_reads_once_and_propagates_errors():
|
||||||
|
reader = Mock()
|
||||||
|
reader.get_events.return_value = [event()]
|
||||||
|
summary = ShiftDowntimeService(reader).summarize(machine_id="machine", start=START, end=END)
|
||||||
|
assert summary == summarize([event()])
|
||||||
|
reader.get_events.assert_called_once_with(machine_id="machine", start=START, end=END)
|
||||||
|
reader.get_events.side_effect = DowntimeReadError("read failed")
|
||||||
|
with pytest.raises(DowntimeReadError):
|
||||||
|
ShiftDowntimeService(reader).summarize(machine_id="machine", start=START, end=END)
|
||||||
@@ -0,0 +1,407 @@
|
|||||||
|
from dataclasses import FrozenInstanceError, replace
|
||||||
|
from datetime import UTC, datetime, timedelta
|
||||||
|
from unittest.mock import Mock
|
||||||
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from production_analytics.calculations.shift_material import (
|
||||||
|
ShiftChannelMaterialSnapshot,
|
||||||
|
ShiftMaterialSnapshot,
|
||||||
|
aggregate_shift_channel_material,
|
||||||
|
aggregate_shift_material,
|
||||||
|
)
|
||||||
|
from production_analytics.service.shift_material import (
|
||||||
|
ShiftChannelMaterialService,
|
||||||
|
ShiftMaterialService,
|
||||||
|
)
|
||||||
|
|
||||||
|
START = datetime(2026, 10, 7, 6, tzinfo=ZoneInfo("Europe/Berlin"))
|
||||||
|
END = START + timedelta(hours=8)
|
||||||
|
|
||||||
|
|
||||||
|
def machine_sample(minutes=0, value=100.0, *, run="r1", calculation="calc", order="order"):
|
||||||
|
return ShiftMaterialSnapshot(
|
||||||
|
START + timedelta(minutes=minutes), calculation, "machine", order, run, value
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def channel_sample(
|
||||||
|
minutes=0,
|
||||||
|
value=100.0,
|
||||||
|
*,
|
||||||
|
name="Material A",
|
||||||
|
number=None,
|
||||||
|
status="ASSIGNED",
|
||||||
|
run="r1",
|
||||||
|
extruder="Ex1",
|
||||||
|
channel="C1",
|
||||||
|
order="order",
|
||||||
|
quality=True,
|
||||||
|
):
|
||||||
|
return ShiftChannelMaterialSnapshot(
|
||||||
|
START + timedelta(minutes=minutes),
|
||||||
|
"calc",
|
||||||
|
"machine",
|
||||||
|
extruder,
|
||||||
|
channel,
|
||||||
|
order,
|
||||||
|
run,
|
||||||
|
value,
|
||||||
|
number,
|
||||||
|
name,
|
||||||
|
status,
|
||||||
|
quality,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def aggregate(rows, *, channel=False, **changes):
|
||||||
|
function = aggregate_shift_channel_material if channel else aggregate_shift_material
|
||||||
|
return function(
|
||||||
|
rows,
|
||||||
|
**{
|
||||||
|
"machine_id": "machine",
|
||||||
|
"calculation_ids": ("calc",),
|
||||||
|
"start": START,
|
||||||
|
"end": END,
|
||||||
|
**changes,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_single_run_boundary_baseline_and_end_are_latest_not_min_max():
|
||||||
|
summary = aggregate(
|
||||||
|
[
|
||||||
|
machine_sample(-20, 1),
|
||||||
|
machine_sample(-1, 100),
|
||||||
|
machine_sample(10, 110),
|
||||||
|
machine_sample(479, 120),
|
||||||
|
machine_sample(480, 500),
|
||||||
|
machine_sample(500, 600),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
assert summary.total_consumption_kg == 20
|
||||||
|
assert summary.items[0].baseline_timestamp == START - timedelta(minutes=1)
|
||||||
|
assert summary.items[0].end_timestamp == END - timedelta(minutes=1)
|
||||||
|
assert not summary.items[0].baseline_missing
|
||||||
|
assert summary.items[0].material_name is None
|
||||||
|
assert summary.items[0].production_order == "order"
|
||||||
|
assert summary.items[0].run_id == "r1"
|
||||||
|
assert isinstance(summary.items, tuple)
|
||||||
|
with pytest.raises(FrozenInstanceError):
|
||||||
|
summary.total_consumption_kg = 0
|
||||||
|
with pytest.raises(FrozenInstanceError):
|
||||||
|
summary.items[0].consumption_kg = 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_exact_start_baseline_and_end_exclusion():
|
||||||
|
summary = aggregate(
|
||||||
|
[
|
||||||
|
machine_sample(-1, 90),
|
||||||
|
machine_sample(0, 100),
|
||||||
|
machine_sample(479, 125),
|
||||||
|
machine_sample(480, 500),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
assert summary.total_consumption_kg == 25
|
||||||
|
assert summary.items[0].baseline_timestamp is not None
|
||||||
|
assert summary.items[0].baseline_timestamp == START
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("channel", [False, True])
|
||||||
|
def test_run_change_never_differences_counters_across_runs(channel):
|
||||||
|
sample = channel_sample if channel else machine_sample
|
||||||
|
summary = aggregate(
|
||||||
|
[
|
||||||
|
sample(-1, 100),
|
||||||
|
sample(120, 120),
|
||||||
|
sample(121, 10, run="r2", order="order-2"),
|
||||||
|
sample(479, 45, run="r2", order="order-2"),
|
||||||
|
],
|
||||||
|
channel=channel,
|
||||||
|
)
|
||||||
|
assert [item.consumption_kg for item in summary.items] == [20, 35]
|
||||||
|
assert summary.total_consumption_kg == 55
|
||||||
|
assert summary.items[1].baseline_missing
|
||||||
|
assert summary.items[1].production_order == "order-2"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("channel", [False, True])
|
||||||
|
def test_missing_baseline_uses_first_sample_without_fabricating_consumption(channel):
|
||||||
|
sample = channel_sample if channel else machine_sample
|
||||||
|
summary = aggregate([sample(10, 1000), sample(20, 1005)], channel=channel)
|
||||||
|
assert summary.total_consumption_kg == 5
|
||||||
|
assert all(item.baseline_missing for item in summary.items)
|
||||||
|
assert aggregate([sample(10, 1000)], channel=channel).total_consumption_kg == 0
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("channel", [False, True])
|
||||||
|
def test_no_samples_and_zero_items_filter(channel):
|
||||||
|
assert aggregate([], channel=channel).items == ()
|
||||||
|
sample = channel_sample if channel else machine_sample
|
||||||
|
rows = [sample(0, 100), sample(10, 100)]
|
||||||
|
summary = aggregate(rows, channel=channel)
|
||||||
|
assert len(summary.items) == 1 and summary.total_consumption_kg == 0
|
||||||
|
assert aggregate(rows, channel=channel, include_zero=False).items == ()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("channel", [False, True])
|
||||||
|
@pytest.mark.parametrize("values", [(100, 90), (100, 90, 150)])
|
||||||
|
def test_counter_reset_rejected_even_when_final_value_recovers(channel, values):
|
||||||
|
sample = channel_sample if channel else machine_sample
|
||||||
|
with pytest.raises(ValueError, match="decreased/reset"):
|
||||||
|
aggregate(
|
||||||
|
[sample(index * 10, value) for index, value in enumerate(values)], channel=channel
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_last_valid_baseline_and_end_skip_null_and_nonfinite_counters():
|
||||||
|
summary = aggregate(
|
||||||
|
[
|
||||||
|
machine_sample(-2, 100),
|
||||||
|
machine_sample(-1, None),
|
||||||
|
machine_sample(0, float("nan")),
|
||||||
|
machine_sample(10, 105),
|
||||||
|
machine_sample(479, float("inf")),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
assert summary.total_consumption_kg == 5
|
||||||
|
assert summary.items[0].baseline_timestamp == START - timedelta(minutes=2)
|
||||||
|
assert summary.items[0].end_timestamp == START + timedelta(minutes=10)
|
||||||
|
|
||||||
|
|
||||||
|
def test_multiple_calculations_and_supplied_k7_b1_examples():
|
||||||
|
examples = {
|
||||||
|
"k7-fiber-consumption": (12083.537, 15552.303, 3468.766),
|
||||||
|
"bento1-fresh-bentonite-consumption": (34604.833, 47320.628, 12715.795),
|
||||||
|
"bento1-spreader3-consumption": (9540.429, 11303.167, 1762.738),
|
||||||
|
}
|
||||||
|
rows = [
|
||||||
|
machine_sample(minutes, value, calculation=calculation)
|
||||||
|
for calculation, (baseline, end, _) in examples.items()
|
||||||
|
for minutes, value in ((-1, baseline), (479, end))
|
||||||
|
]
|
||||||
|
summary = aggregate(rows, calculation_ids=tuple(examples))
|
||||||
|
assert {item.calculation_id: item.consumption_kg for item in summary.items} == pytest.approx(
|
||||||
|
{calculation: values[2] for calculation, values in examples.items()}
|
||||||
|
)
|
||||||
|
assert summary.total_consumption_kg == pytest.approx(
|
||||||
|
sum(values[2] for values in examples.values())
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_channel_b_identity_attribution_and_no_null_carry_forward():
|
||||||
|
rows = [
|
||||||
|
channel_sample(-1, 100, name="Old"),
|
||||||
|
channel_sample(10, 110, name="Material A"),
|
||||||
|
channel_sample(20, 130, name="Material A"),
|
||||||
|
channel_sample(30, 135, name=None),
|
||||||
|
channel_sample(40, 140, name=" "),
|
||||||
|
channel_sample(50, 155, name="Material A"),
|
||||||
|
channel_sample(60, 165, name="Material B"),
|
||||||
|
]
|
||||||
|
summary = aggregate(rows, channel=True)
|
||||||
|
assert [(item.material_name, item.consumption_kg) for item in summary.items] == [
|
||||||
|
("Material A", 30),
|
||||||
|
(None, 10),
|
||||||
|
("Material A", 15),
|
||||||
|
("Material B", 10),
|
||||||
|
]
|
||||||
|
assert summary.items[1].material_mapping_status == "UNAVAILABLE"
|
||||||
|
assert all(item.material_number is None for item in summary.items)
|
||||||
|
assert summary.total_consumption_kg == 65
|
||||||
|
assert all(item.material_name != "Old" for item in summary.items)
|
||||||
|
|
||||||
|
|
||||||
|
def test_material_number_metadata_and_quality_are_preserved():
|
||||||
|
summary = aggregate(
|
||||||
|
[
|
||||||
|
channel_sample(0, 100, number="123", name=None),
|
||||||
|
channel_sample(10, 105, number="123", name=None, quality=False),
|
||||||
|
channel_sample(20, 110, number="123", name=None, quality=True),
|
||||||
|
],
|
||||||
|
channel=True,
|
||||||
|
)
|
||||||
|
item = summary.items[0]
|
||||||
|
assert item.material_number == "123" and item.material_name is None
|
||||||
|
assert item.material_mapping_status == "ASSIGNED"
|
||||||
|
assert not item.percentage_sum_valid
|
||||||
|
assert item.consumption_kg == 10
|
||||||
|
|
||||||
|
|
||||||
|
def test_e1_historical_null_channel_fixtures():
|
||||||
|
expected = {
|
||||||
|
"Ex1": [0, 4890.271, 4890.271, 1772.723, 0, 0, 672.412],
|
||||||
|
"Ex2": [7596.677, 822.973, 2481.581, 1266.113, 0, 0, 493.784],
|
||||||
|
}
|
||||||
|
rows = [
|
||||||
|
channel_sample(
|
||||||
|
minutes, value, extruder=extruder, channel=f"C{index}", name=None, status="UNAVAILABLE"
|
||||||
|
)
|
||||||
|
for extruder, deltas in expected.items()
|
||||||
|
for index, delta in enumerate(deltas, 1)
|
||||||
|
for minutes, value in ((-1, 5000), (479, 5000 + delta))
|
||||||
|
]
|
||||||
|
summary = aggregate(rows, channel=True)
|
||||||
|
assert len(summary.items) == 14
|
||||||
|
assert {(item.extruder, item.doser_channel): item.consumption_kg for item in summary.items} == (
|
||||||
|
pytest.approx(
|
||||||
|
{
|
||||||
|
(extruder, f"C{index}"): delta
|
||||||
|
for extruder, deltas in expected.items()
|
||||||
|
for index, delta in enumerate(deltas, 1)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
)
|
||||||
|
assert all(item.material_name is None for item in summary.items)
|
||||||
|
assert all(item.material_mapping_status == "UNAVAILABLE" for item in summary.items)
|
||||||
|
assert summary == aggregate(reversed(rows), channel=True)
|
||||||
|
assert len(aggregate(rows, channel=True, include_zero=False).items) == 9
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("channel", [False, True])
|
||||||
|
def test_dst_fold_boundaries_use_instants(channel):
|
||||||
|
berlin = ZoneInfo("Europe/Berlin")
|
||||||
|
start = datetime(2026, 10, 25, 2, 30, tzinfo=berlin, fold=0)
|
||||||
|
end = start.replace(fold=1)
|
||||||
|
sample = channel_sample if channel else machine_sample
|
||||||
|
rows = [
|
||||||
|
replace(sample(value=value), timestamp=timestamp)
|
||||||
|
for timestamp, value in (
|
||||||
|
(start, 100),
|
||||||
|
(datetime(2026, 10, 25, 1, 20, tzinfo=UTC), 110),
|
||||||
|
(end, 500),
|
||||||
|
)
|
||||||
|
]
|
||||||
|
summary = aggregate(rows, channel=channel, start=start, end=end)
|
||||||
|
assert summary.total_consumption_kg == 10
|
||||||
|
assert summary.start is start and summary.end is end
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("channel", [False, True])
|
||||||
|
def test_invalid_windows_precede_reader_call(channel):
|
||||||
|
reader = Mock()
|
||||||
|
service = ShiftChannelMaterialService(reader) if channel else ShiftMaterialService(reader)
|
||||||
|
for changes in (
|
||||||
|
{"start": START.replace(tzinfo=None)},
|
||||||
|
{"end": END.replace(tzinfo=None)},
|
||||||
|
{"end": START},
|
||||||
|
{"end": START - timedelta(hours=1)},
|
||||||
|
{"machine_id": ""},
|
||||||
|
{"calculation_ids": ()},
|
||||||
|
{"calculation_ids": ("calc", "calc")},
|
||||||
|
):
|
||||||
|
inputs = {
|
||||||
|
"machine_id": "machine",
|
||||||
|
"calculation_ids": ("calc",),
|
||||||
|
"start": START,
|
||||||
|
"end": END,
|
||||||
|
**changes,
|
||||||
|
}
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
service.summarize(**inputs)
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
aggregate([], channel=channel, **changes)
|
||||||
|
reader.get_snapshots.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("channel", [False, True])
|
||||||
|
def test_service_composes_once_and_propagates_errors(channel):
|
||||||
|
reader = Mock()
|
||||||
|
reader.get_snapshots.return_value = [channel_sample() if channel else machine_sample()]
|
||||||
|
service = ShiftChannelMaterialService(reader) if channel else ShiftMaterialService(reader)
|
||||||
|
inputs = {"machine_id": "machine", "calculation_ids": ("calc",), "start": START, "end": END}
|
||||||
|
assert service.summarize(**inputs) == aggregate(
|
||||||
|
reader.get_snapshots.return_value, channel=channel
|
||||||
|
)
|
||||||
|
reader.get_snapshots.assert_called_once_with(**inputs)
|
||||||
|
reader.get_snapshots.side_effect = RuntimeError("reader failed")
|
||||||
|
with pytest.raises(RuntimeError, match="reader failed"):
|
||||||
|
service.summarize(**inputs)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("channel", [False, True])
|
||||||
|
def test_ambiguous_stream_timestamps_and_reappearing_runs_rejected(channel):
|
||||||
|
sample = channel_sample if channel else machine_sample
|
||||||
|
with pytest.raises(ValueError, match="same stream timestamp"):
|
||||||
|
aggregate([sample(0, 100), sample(0, 100)], channel=channel)
|
||||||
|
with pytest.raises(ValueError, match="reappeared"):
|
||||||
|
aggregate([sample(0, 100), sample(10, 10, run="r2"), sample(20, 200)], channel=channel)
|
||||||
|
with pytest.raises(ValueError, match="Production order"):
|
||||||
|
aggregate([sample(0, 100), sample(10, 110, order="different")], channel=channel)
|
||||||
|
|
||||||
|
|
||||||
|
def test_machine_and_calculation_scoping():
|
||||||
|
summary = aggregate(
|
||||||
|
[
|
||||||
|
machine_sample(),
|
||||||
|
machine_sample(10, 110),
|
||||||
|
replace(machine_sample(20, 1000), machine_id="other"),
|
||||||
|
machine_sample(20, 1000, calculation="other"),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
assert summary.total_consumption_kg == 10
|
||||||
|
|
||||||
|
|
||||||
|
def test_channel_invalid_numeric_samples_are_not_used_as_baseline_or_end():
|
||||||
|
summary = aggregate(
|
||||||
|
[
|
||||||
|
channel_sample(-2, 100),
|
||||||
|
channel_sample(-1, None),
|
||||||
|
channel_sample(10, 120, name=None),
|
||||||
|
channel_sample(479, float("nan")),
|
||||||
|
],
|
||||||
|
channel=True,
|
||||||
|
)
|
||||||
|
assert summary.total_consumption_kg == 20
|
||||||
|
assert summary.items[0].material_name is None
|
||||||
|
assert summary.items[0].material_mapping_status == "UNAVAILABLE"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("channel", [False, True])
|
||||||
|
def test_new_run_exactly_at_shift_start_is_its_own_baseline(channel):
|
||||||
|
sample = channel_sample if channel else machine_sample
|
||||||
|
summary = aggregate(
|
||||||
|
[sample(-1, 10000, run="old"), sample(0, 50, run="new"), sample(10, 60, run="new")],
|
||||||
|
channel=channel,
|
||||||
|
)
|
||||||
|
assert len(summary.items) == 1
|
||||||
|
assert summary.items[0].run_id == "new"
|
||||||
|
assert not summary.items[0].baseline_missing
|
||||||
|
assert summary.total_consumption_kg == 10
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("channel", [False, True])
|
||||||
|
def test_invalid_counters_do_not_hide_run_boundaries(channel):
|
||||||
|
sample = channel_sample if channel else machine_sample
|
||||||
|
summary = aggregate(
|
||||||
|
[sample(-2, 1000), sample(-1, None, run="r2"),
|
||||||
|
sample(10, 50, run="r2"), sample(20, 60, run="r2")],
|
||||||
|
channel=channel,
|
||||||
|
)
|
||||||
|
assert summary.total_consumption_kg == 10
|
||||||
|
assert len(summary.items) == 1
|
||||||
|
assert summary.items[0].run_id == "r2"
|
||||||
|
assert summary.items[0].baseline_missing
|
||||||
|
with pytest.raises(ValueError, match="reappeared"):
|
||||||
|
aggregate([sample(0, 100), sample(10, None, run="r2"), sample(20, 120)],
|
||||||
|
channel=channel)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("channel", [False, True])
|
||||||
|
def test_negative_counter_is_rejected(channel):
|
||||||
|
sample = channel_sample if channel else machine_sample
|
||||||
|
with pytest.raises(ValueError, match="non-negative"):
|
||||||
|
aggregate([sample(0, 100), sample(10, -1)], channel=channel)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("channel", [False, True])
|
||||||
|
def test_spring_dst_window_uses_elapsed_instants(channel):
|
||||||
|
berlin = ZoneInfo("Europe/Berlin")
|
||||||
|
start = datetime(2026, 3, 29, 1, 30, tzinfo=berlin)
|
||||||
|
end = datetime(2026, 3, 29, 3, 30, tzinfo=berlin)
|
||||||
|
sample = channel_sample if channel else machine_sample
|
||||||
|
rows = [replace(sample(value=value), timestamp=timestamp) for timestamp, value in
|
||||||
|
[(start, 100), (datetime(2026, 3, 29, 1, 20, tzinfo=UTC), 110), (end, 999)]]
|
||||||
|
assert (end.astimezone(UTC) - start.astimezone(UTC)).total_seconds() == 3600
|
||||||
|
assert aggregate(rows, channel=channel, start=start, end=end).total_consumption_kg == 10
|
||||||
@@ -0,0 +1,250 @@
|
|||||||
|
from dataclasses import FrozenInstanceError, replace
|
||||||
|
from datetime import UTC, datetime, timedelta
|
||||||
|
from unittest.mock import Mock
|
||||||
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from production_analytics.calculations.shift_production import aggregate_shift_production
|
||||||
|
from production_analytics.erp import ErpReadError, ProductionConfirmation
|
||||||
|
from production_analytics.service.shift_production import ShiftProductionService
|
||||||
|
|
||||||
|
BERLIN = ZoneInfo("Europe/Berlin")
|
||||||
|
START = datetime(2026, 9, 4, 6, tzinfo=BERLIN)
|
||||||
|
END = START + timedelta(hours=8)
|
||||||
|
ROW = ProductionConfirmation(
|
||||||
|
workplace="arbitrary-workplace",
|
||||||
|
production_order="order-1",
|
||||||
|
timestamp=START,
|
||||||
|
article_number="article-1",
|
||||||
|
article_description="4.85 x 40 m",
|
||||||
|
roll_number="roll-1",
|
||||||
|
production_quantity_m2=194.0,
|
||||||
|
feedback_quantity_m2=194.0,
|
||||||
|
raw_material_number=None,
|
||||||
|
raw_material_description=None,
|
||||||
|
batch_number=None,
|
||||||
|
raw_material_quantity=0.0,
|
||||||
|
tenant="tenant",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def summarize(rows, **kwargs):
|
||||||
|
return aggregate_shift_production(
|
||||||
|
rows,
|
||||||
|
**{
|
||||||
|
"workplace": ROW.workplace,
|
||||||
|
"start": START,
|
||||||
|
"end": END,
|
||||||
|
**kwargs,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_one_article_order_uses_feedback_area_and_tracks_times():
|
||||||
|
rows = [
|
||||||
|
ROW,
|
||||||
|
replace(
|
||||||
|
ROW,
|
||||||
|
timestamp=START + timedelta(hours=1),
|
||||||
|
roll_number="roll-2",
|
||||||
|
feedback_quantity_m2=1500.0,
|
||||||
|
production_quantity_m2=999.0,
|
||||||
|
),
|
||||||
|
]
|
||||||
|
summary = summarize(iter(reversed(rows)))
|
||||||
|
assert summary.total_produced_m2 == 1694.0
|
||||||
|
assert summary.total_roll_count == 2
|
||||||
|
assert len(summary.items) == 1
|
||||||
|
item = summary.items[0]
|
||||||
|
assert (item.production_order, item.article_number, item.article_description) == (
|
||||||
|
"order-1",
|
||||||
|
"article-1",
|
||||||
|
"4.85 x 40 m",
|
||||||
|
)
|
||||||
|
assert item.produced_m2 == 1694.0
|
||||||
|
assert item.roll_count == 2
|
||||||
|
assert item.first_confirmation_at is START
|
||||||
|
assert item.last_confirmation_at == START + timedelta(hours=1)
|
||||||
|
assert summary.start is START and summary.end is END
|
||||||
|
assert isinstance(summary.items, tuple)
|
||||||
|
with pytest.raises(FrozenInstanceError):
|
||||||
|
item.produced_m2 = 0
|
||||||
|
with pytest.raises(FrozenInstanceError):
|
||||||
|
summary.total_produced_m2 = 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_articles_orders_and_descriptions_form_separate_groups():
|
||||||
|
rows = [
|
||||||
|
ROW,
|
||||||
|
replace(ROW, article_number="article-2", feedback_quantity_m2=2500.0),
|
||||||
|
replace(ROW, production_order="order-2", feedback_quantity_m2=1500.0),
|
||||||
|
replace(ROW, article_description="Different description", feedback_quantity_m2=100.0),
|
||||||
|
]
|
||||||
|
summary = summarize(rows)
|
||||||
|
assert len(summary.items) == 4
|
||||||
|
assert summary.total_produced_m2 == 4294.0
|
||||||
|
# The same roll number is distinct within each group, not across the shift.
|
||||||
|
assert summary.total_roll_count == 4
|
||||||
|
assert summary.total_produced_m2 == sum(item.produced_m2 for item in summary.items)
|
||||||
|
assert summary.total_roll_count == sum(item.roll_count for item in summary.items)
|
||||||
|
|
||||||
|
|
||||||
|
def test_raw_material_null_zero_and_negative_feedback_do_not_contribute():
|
||||||
|
rows = [
|
||||||
|
ROW,
|
||||||
|
*[
|
||||||
|
replace(
|
||||||
|
ROW,
|
||||||
|
feedback_quantity_m2=quantity,
|
||||||
|
production_quantity_m2=0,
|
||||||
|
raw_material_quantity=999,
|
||||||
|
roll_number="raw-roll",
|
||||||
|
)
|
||||||
|
for quantity in (None, 0.0, -10.0)
|
||||||
|
],
|
||||||
|
]
|
||||||
|
summary = summarize(rows)
|
||||||
|
assert summary.total_produced_m2 == 194.0
|
||||||
|
assert summary.total_roll_count == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_repeated_roll_numbers_deduplicate_only_roll_count():
|
||||||
|
rows = [ROW, ROW, replace(ROW, roll_number=" roll-1 "), replace(ROW, roll_number="roll-2")]
|
||||||
|
summary = summarize(rows)
|
||||||
|
assert summary.total_produced_m2 == 4 * 194.0
|
||||||
|
assert summary.total_roll_count == summary.items[0].roll_count == 2
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("roll", [None, "", " "])
|
||||||
|
def test_missing_roll_number_still_contributes_area(roll):
|
||||||
|
summary = summarize([replace(ROW, roll_number=roll)])
|
||||||
|
assert summary.total_produced_m2 == 194.0
|
||||||
|
assert summary.total_roll_count == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_exact_workplace_and_half_open_boundaries():
|
||||||
|
summary = summarize(
|
||||||
|
[
|
||||||
|
replace(ROW, timestamp=START - timedelta(microseconds=1)),
|
||||||
|
ROW,
|
||||||
|
replace(ROW, timestamp=END - timedelta(microseconds=1), roll_number="last"),
|
||||||
|
replace(ROW, timestamp=END),
|
||||||
|
replace(ROW, workplace="different-workplace"),
|
||||||
|
],
|
||||||
|
workplace=" arbitrary-workplace ",
|
||||||
|
)
|
||||||
|
assert summary.workplace == ROW.workplace
|
||||||
|
assert summary.total_produced_m2 == 388.0
|
||||||
|
assert summary.total_roll_count == 2
|
||||||
|
assert summary.items[0].last_confirmation_at == END - timedelta(microseconds=1)
|
||||||
|
|
||||||
|
|
||||||
|
def test_empty_shift_and_material_only_shift():
|
||||||
|
for rows in ([], [replace(ROW, feedback_quantity_m2=0.0)]):
|
||||||
|
summary = summarize(rows)
|
||||||
|
assert summary.items == ()
|
||||||
|
assert summary.total_produced_m2 == 0.0
|
||||||
|
assert summary.total_roll_count == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_deterministic_order_with_nullable_article_identifiers():
|
||||||
|
rows = [
|
||||||
|
replace(ROW, production_order="z", timestamp=START + timedelta(minutes=1)),
|
||||||
|
replace(ROW, article_number="z"),
|
||||||
|
replace(ROW, article_number=None),
|
||||||
|
replace(ROW, article_number="", article_description=None),
|
||||||
|
replace(ROW, article_number="", article_description=""),
|
||||||
|
]
|
||||||
|
summary = summarize(rows)
|
||||||
|
assert summary == summarize(reversed(rows))
|
||||||
|
assert [(item.article_number, item.article_description) for item in summary.items[:4]] == [
|
||||||
|
(None, "4.85 x 40 m"),
|
||||||
|
("", None),
|
||||||
|
("", ""),
|
||||||
|
("z", "4.85 x 40 m"),
|
||||||
|
]
|
||||||
|
assert summary.items[-1].production_order == "z"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"kwargs",
|
||||||
|
[
|
||||||
|
{"start": START.replace(tzinfo=None)},
|
||||||
|
{"end": END.replace(tzinfo=None)},
|
||||||
|
{"start": None},
|
||||||
|
{"end": START},
|
||||||
|
{"end": START - timedelta(seconds=1)},
|
||||||
|
{"workplace": ""},
|
||||||
|
{"workplace": " "},
|
||||||
|
{"workplace": "bad\x00"},
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_validation_precedes_gateway_read(kwargs):
|
||||||
|
gateway = Mock()
|
||||||
|
service = ShiftProductionService(gateway)
|
||||||
|
inputs = {"workplace": ROW.workplace, "start": START, "end": END, **kwargs}
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
aggregate_shift_production([], **inputs)
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
service.summarize(**inputs)
|
||||||
|
gateway.get_confirmations.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
def test_naive_confirmation_timestamp_is_rejected():
|
||||||
|
with pytest.raises(ValueError, match="confirmation timestamp"):
|
||||||
|
summarize([replace(ROW, timestamp=START.replace(tzinfo=None))])
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("quantity", [float("nan"), float("inf"), True])
|
||||||
|
def test_invalid_feedback_quantity_rejected(quantity):
|
||||||
|
with pytest.raises(ValueError, match="finite"):
|
||||||
|
summarize([replace(ROW, feedback_quantity_m2=quantity)])
|
||||||
|
|
||||||
|
|
||||||
|
def test_service_reads_once_and_preserves_boundary_timezones():
|
||||||
|
gateway = Mock()
|
||||||
|
gateway.get_confirmations.return_value = [ROW]
|
||||||
|
summary = ShiftProductionService(gateway).summarize(
|
||||||
|
workplace=" arbitrary-workplace ",
|
||||||
|
start=START,
|
||||||
|
end=END,
|
||||||
|
)
|
||||||
|
gateway.get_confirmations.assert_called_once_with(workplace=ROW.workplace, start=START, end=END)
|
||||||
|
assert summary == summarize([ROW])
|
||||||
|
assert summary.start.tzinfo is summary.end.tzinfo is BERLIN
|
||||||
|
assert summary.items[0].first_confirmation_at.tzinfo is BERLIN
|
||||||
|
|
||||||
|
|
||||||
|
def test_gateway_errors_propagate():
|
||||||
|
gateway = Mock()
|
||||||
|
gateway.get_confirmations.side_effect = ErpReadError("ERP production confirmation read failed")
|
||||||
|
with pytest.raises(ErpReadError, match="read failed"):
|
||||||
|
ShiftProductionService(gateway).summarize(workplace=ROW.workplace, start=START, end=END)
|
||||||
|
|
||||||
|
|
||||||
|
def test_dst_fold_order_and_window_compare_instants_without_changing_timestamps():
|
||||||
|
start = datetime(2026, 10, 25, 2, 15, tzinfo=BERLIN, fold=0)
|
||||||
|
end = datetime(2026, 10, 25, 2, 45, tzinfo=BERLIN, fold=1)
|
||||||
|
early = datetime(2026, 10, 25, 2, 30, tzinfo=BERLIN, fold=0)
|
||||||
|
late = early.replace(fold=1)
|
||||||
|
summary = summarize(
|
||||||
|
[
|
||||||
|
replace(ROW, timestamp=late),
|
||||||
|
replace(ROW, timestamp=early),
|
||||||
|
replace(ROW, timestamp=end),
|
||||||
|
],
|
||||||
|
start=start,
|
||||||
|
end=end,
|
||||||
|
)
|
||||||
|
assert summary.total_produced_m2 == 388.0
|
||||||
|
assert summary.items[0].first_confirmation_at is early
|
||||||
|
assert summary.items[0].last_confirmation_at is late
|
||||||
|
assert summary.start is start and summary.end is end
|
||||||
|
|
||||||
|
|
||||||
|
def test_aware_other_timezone_compares_same_instants_without_rewriting():
|
||||||
|
instant = START.astimezone(UTC)
|
||||||
|
summary = summarize([replace(ROW, timestamp=instant)])
|
||||||
|
assert summary.items[0].first_confirmation_at is instant
|
||||||
|
assert summary.start is START
|
||||||
@@ -0,0 +1,238 @@
|
|||||||
|
from copy import deepcopy
|
||||||
|
from dataclasses import FrozenInstanceError
|
||||||
|
from datetime import UTC, date, timedelta
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
import yaml
|
||||||
|
|
||||||
|
from production_analytics.calculations.shift_downtime import (
|
||||||
|
ClippedShiftDowntimeEvent,
|
||||||
|
ShiftDowntimeEvent,
|
||||||
|
ShiftDowntimeReason,
|
||||||
|
ShiftDowntimeSummary,
|
||||||
|
)
|
||||||
|
from production_analytics.calculations.shift_material import ShiftMaterialItem, ShiftMaterialSummary
|
||||||
|
from production_analytics.calculations.shift_production import (
|
||||||
|
ShiftProductionItem,
|
||||||
|
ShiftProductionSummary,
|
||||||
|
)
|
||||||
|
from production_analytics.calculations.shift_report import shift_report_window
|
||||||
|
from production_analytics.calculations.shift_speed import aggregate_shift_speed
|
||||||
|
from production_analytics.service.shift_report import ShiftReportService
|
||||||
|
from production_analytics.service.shift_report_config import load_shift_report_machines
|
||||||
|
|
||||||
|
CONFIG_PATH = Path(__file__).resolve().parents[1] / "config/shift-report-machines.yaml"
|
||||||
|
START, END = shift_report_window(date(2026, 10, 7), "early")
|
||||||
|
|
||||||
|
|
||||||
|
class Stub:
|
||||||
|
def __init__(self, name, result, calls):
|
||||||
|
self.name, self.result, self.calls = name, result, calls
|
||||||
|
self.error = None
|
||||||
|
|
||||||
|
def summarize(self, **kwargs):
|
||||||
|
self.calls.append((self.name, kwargs))
|
||||||
|
if self.error is not None:
|
||||||
|
raise self.error
|
||||||
|
return self.result
|
||||||
|
|
||||||
|
|
||||||
|
def composition(name="B1"):
|
||||||
|
machines = load_shift_report_machines(CONFIG_PATH)
|
||||||
|
config = machines[name]
|
||||||
|
calls = []
|
||||||
|
production = ShiftProductionSummary(
|
||||||
|
START, END, config.erp_workplace, 123, 1,
|
||||||
|
(ShiftProductionItem("order", "article", "description", 123, 1, START, START),),
|
||||||
|
)
|
||||||
|
reasons = tuple(
|
||||||
|
ShiftDowntimeReason(str(index), reason_name, "description", "group", "category",
|
||||||
|
duration, 1)
|
||||||
|
for index, (reason_name, duration) in enumerate(
|
||||||
|
[(None, 100), ("Stop", 90), (" ", 80), ("Other", 70)]
|
||||||
|
)
|
||||||
|
)
|
||||||
|
source = ShiftDowntimeEvent("event", config.machine_id, START,
|
||||||
|
START + timedelta(seconds=100), None, None, None, None, None, None)
|
||||||
|
event = ClippedShiftDowntimeEvent(source, START, source.source_end, 100)
|
||||||
|
downtime = ShiftDowntimeSummary(config.machine_id, START, END, 28800, 100, 28700,
|
||||||
|
(event,), reasons)
|
||||||
|
channel = config.material.mode == "channel"
|
||||||
|
item = ShiftMaterialItem(
|
||||||
|
source="channel_material_consumption_snapshots" if channel
|
||||||
|
else "material_consumption_snapshots",
|
||||||
|
calculation_id=config.material.calculation_ids[0], machine_id=config.machine_id,
|
||||||
|
production_order="order", run_id="run", consumption_kg=42,
|
||||||
|
baseline_timestamp=START, end_timestamp=END - timedelta(seconds=1),
|
||||||
|
baseline_missing=False, extruder="Ex1" if channel else None,
|
||||||
|
doser_channel="C2" if channel else None, material_name=None,
|
||||||
|
material_mapping_status="UNAVAILABLE" if channel else None,
|
||||||
|
)
|
||||||
|
materials = ShiftMaterialSummary(config.machine_id, START, END, 42, (item,))
|
||||||
|
speed = aggregate_shift_speed([], config=config.speed, start=START, end=END)
|
||||||
|
stubs = {key: Stub(key, value, calls) for key, value in [
|
||||||
|
("production", production), ("downtime", downtime), ("materials", materials),
|
||||||
|
("channel_materials", materials), ("speed", speed),
|
||||||
|
]}
|
||||||
|
service = ShiftReportService(machines=machines, **stubs)
|
||||||
|
return service, stubs, calls, config
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("name,workplace,mode,ids", [
|
||||||
|
("B1", "BENTO 1", "materials",
|
||||||
|
("bento1-fresh-bentonite-consumption", "bento1-spreader3-consumption")),
|
||||||
|
("E1", "1568705", "channel_materials", ("e1-channel-material-consumption",)),
|
||||||
|
("K7", "K7", "materials", ("k7-fiber-consumption",)),
|
||||||
|
])
|
||||||
|
def test_machine_composition(name, workplace, mode, ids):
|
||||||
|
service, stubs, calls, config = composition(name)
|
||||||
|
report = service.build(machine_name=name, start=START, end=END)
|
||||||
|
assert calls == [
|
||||||
|
("production", {"workplace": workplace, "start": START, "end": END}),
|
||||||
|
("downtime", {"machine_id": config.machine_id, "start": START, "end": END}),
|
||||||
|
(mode, {"machine_id": config.machine_id, "calculation_ids": ids,
|
||||||
|
"start": START, "end": END}),
|
||||||
|
("speed", {"config": config.speed, "start": START, "end": END}),
|
||||||
|
]
|
||||||
|
assert report.machine_name == name and report.machine_id == config.machine_id
|
||||||
|
assert report.production is stubs["production"].result
|
||||||
|
assert report.downtime is stubs["downtime"].result
|
||||||
|
assert report.materials is stubs[mode].result
|
||||||
|
assert report.speed is stubs["speed"].result
|
||||||
|
assert report.materials.items[0].consumption_kg == 42
|
||||||
|
assert report.materials.items[0].material_name is None
|
||||||
|
if name == "E1":
|
||||||
|
assert report.materials.items[0].extruder == "Ex1"
|
||||||
|
assert report.materials.items[0].doser_channel == "C2"
|
||||||
|
assert report.materials.items[0].material_mapping_status == "UNAVAILABLE"
|
||||||
|
assert report.downtime.non_downtime_seconds == 28700
|
||||||
|
assert report.downtime_event_count == 1
|
||||||
|
assert report.production.items[0].article_description == "description"
|
||||||
|
with pytest.raises(FrozenInstanceError):
|
||||||
|
report.machine_name = "other"
|
||||||
|
|
||||||
|
|
||||||
|
def test_top_three_and_fallback_preserve_reason_metadata_and_order():
|
||||||
|
service, stubs, _, _ = composition()
|
||||||
|
report = service.build(machine_name="B1", start=START, end=END)
|
||||||
|
assert len(report.downtime_reasons) == 4
|
||||||
|
assert len(report.top_downtime_reasons) == 3
|
||||||
|
assert [reason.display_name for reason in report.top_downtime_reasons] == [
|
||||||
|
"Ohne Stillstandsgrund", "Stop", "Ohne Stillstandsgrund",
|
||||||
|
]
|
||||||
|
for index, view in enumerate(report.top_downtime_reasons):
|
||||||
|
assert view.reason is stubs["downtime"].result.reasons[index]
|
||||||
|
assert view.reason.duration_seconds == [100, 90, 80][index]
|
||||||
|
assert view.reason.reason_description == "description"
|
||||||
|
assert report.downtime.reasons[0].reason_name is None
|
||||||
|
with pytest.raises(FrozenInstanceError):
|
||||||
|
report.top_downtime_reasons[0].display_name = "changed"
|
||||||
|
|
||||||
|
|
||||||
|
def test_legitimate_empty_sources_are_kept():
|
||||||
|
service, stubs, _, config = composition()
|
||||||
|
stubs["production"].result = ShiftProductionSummary(START, END, config.erp_workplace, 0, 0, ())
|
||||||
|
stubs["downtime"].result = ShiftDowntimeSummary(config.machine_id, START, END, 28800,
|
||||||
|
0, 28800, (), ())
|
||||||
|
stubs["materials"].result = ShiftMaterialSummary(config.machine_id, START, END, 0, ())
|
||||||
|
report = service.build(machine_name="B1", start=START, end=END)
|
||||||
|
assert report.production.items == () and report.production.total_produced_m2 == 0
|
||||||
|
assert report.materials.items == () and report.materials.total_consumption_kg == 0
|
||||||
|
assert report.speed.average_line_speed_m_min is None
|
||||||
|
assert report.top_downtime_reasons == ()
|
||||||
|
assert report.downtime_event_count == 0
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("name,stage", [
|
||||||
|
("B1", "production"), ("B1", "downtime"), ("B1", "materials"),
|
||||||
|
("E1", "channel_materials"), ("K7", "speed"),
|
||||||
|
])
|
||||||
|
def test_mandatory_failures_propagate_without_reading_later_sources(name, stage):
|
||||||
|
service, stubs, calls, _ = composition(name)
|
||||||
|
error = RuntimeError("source failed")
|
||||||
|
stubs[stage].error = error
|
||||||
|
with pytest.raises(RuntimeError) as caught:
|
||||||
|
service.build(machine_name=name, start=START, end=END)
|
||||||
|
assert caught.value is error
|
||||||
|
assert calls[-1][0] == stage
|
||||||
|
sequence = ["production", "downtime",
|
||||||
|
"channel_materials" if name == "E1" else "materials", "speed"]
|
||||||
|
assert [call[0] for call in calls] == sequence[:sequence.index(stage) + 1]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("start,end", [
|
||||||
|
(START.replace(tzinfo=None), END), (START, END.replace(tzinfo=None)),
|
||||||
|
(START, START), (END, START),
|
||||||
|
])
|
||||||
|
def test_invalid_window_precedes_source_calls(start, end):
|
||||||
|
service, _, calls, _ = composition()
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
service.build(machine_name="B1", start=start, end=end)
|
||||||
|
assert calls == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_unknown_machine_precedes_source_calls():
|
||||||
|
service, _, calls, _ = composition()
|
||||||
|
with pytest.raises(ValueError, match="Unknown"):
|
||||||
|
service.build(machine_name="unknown", start=START, end=END)
|
||||||
|
assert calls == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_utc_input_is_normalized_to_berlin_without_changing_instants():
|
||||||
|
service, _, calls, _ = composition()
|
||||||
|
report = service.build(machine_name="B1", start=START.astimezone(UTC), end=END.astimezone(UTC))
|
||||||
|
assert report.start.tzinfo.key == "Europe/Berlin"
|
||||||
|
assert report.start == START and report.end == END
|
||||||
|
assert all(call[1]["start"].tzinfo.key == "Europe/Berlin" for call in calls)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("shift,hours", [
|
||||||
|
("early", (6, 14)), ("late", (14, 22)), ("night", (22, 6)),
|
||||||
|
])
|
||||||
|
def test_shift_windows(shift, hours):
|
||||||
|
start, end = shift_report_window(date(2026, 10, 7), shift)
|
||||||
|
assert (start.hour, end.hour) == hours
|
||||||
|
expected_end_day = date(2026, 10, 8) if shift == "night" else start.date()
|
||||||
|
assert end.date() == expected_end_day
|
||||||
|
assert (end.astimezone(UTC) - start.astimezone(UTC)).total_seconds() == 28800
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("day,hours", [(date(2026, 3, 28), 7), (date(2026, 10, 24), 9)])
|
||||||
|
def test_night_shift_dst_elapsed_duration(day, hours):
|
||||||
|
start, end = shift_report_window(day, "night")
|
||||||
|
assert (end.astimezone(UTC) - start.astimezone(UTC)).total_seconds() == hours * 3600
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("mutation", [
|
||||||
|
lambda d: d["machines"]["B1"].pop("erp_workplace"),
|
||||||
|
lambda d: d["machines"]["B1"].update(unknown=True),
|
||||||
|
lambda d: d["machines"]["B1"]["material"].update(mode="erp"),
|
||||||
|
lambda d: d["machines"]["B1"]["material"].update(calculation_ids=[]),
|
||||||
|
lambda d: d["machines"]["B1"]["material"].update(calculation_ids="calc"),
|
||||||
|
lambda d: d["machines"]["B1"]["material"].update(calculation_ids=["calc", "calc"]),
|
||||||
|
lambda d: d["machines"]["B1"]["material"].update(calculation_ids=[None]),
|
||||||
|
lambda d: d["machines"]["B1"]["material"].update(extra=True),
|
||||||
|
lambda d: d["machines"]["B1"]["speed"].pop("signal_ref"),
|
||||||
|
lambda d: d["machines"]["B1"]["speed"].update(extra=True),
|
||||||
|
lambda d: d["machines"]["B1"]["speed"].update(signal=" "),
|
||||||
|
lambda d: d["machines"]["B1"]["speed"].update(unit="rpm"),
|
||||||
|
lambda d: d["machines"]["B1"]["speed"].update(production_gate_m_min=float("nan")),
|
||||||
|
lambda d: d["machines"]["E1"].update(machine_id=d["machines"]["B1"]["machine_id"]),
|
||||||
|
lambda d: d["machines"]["B1"].update(erp_workplace=1568705),
|
||||||
|
lambda d: d.update(extra=True),
|
||||||
|
])
|
||||||
|
def test_strict_configuration(tmp_path, mutation):
|
||||||
|
document = deepcopy(yaml.safe_load(CONFIG_PATH.read_text()))
|
||||||
|
mutation(document)
|
||||||
|
path = tmp_path / "machines.yaml"
|
||||||
|
path.write_text(yaml.safe_dump(document))
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
load_shift_report_machines(path)
|
||||||
|
|
||||||
|
|
||||||
|
def test_duplicate_yaml_keys_rejected(tmp_path):
|
||||||
|
path = tmp_path / "machines.yaml"
|
||||||
|
path.write_text("machines: {}\nmachines: {}\n")
|
||||||
|
with pytest.raises(ValueError, match="unique"):
|
||||||
|
load_shift_report_machines(path)
|
||||||
@@ -0,0 +1,215 @@
|
|||||||
|
from dataclasses import FrozenInstanceError, replace
|
||||||
|
from datetime import UTC, datetime, timedelta
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import Mock
|
||||||
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from production_analytics.calculations.shift_speed import (
|
||||||
|
ShiftSpeedConfig,
|
||||||
|
ShiftSpeedSample,
|
||||||
|
aggregate_shift_speed,
|
||||||
|
)
|
||||||
|
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
|
||||||
|
|
||||||
|
START = datetime(2026, 10, 7, 6, tzinfo=ZoneInfo("Europe/Berlin"))
|
||||||
|
END = START + timedelta(hours=8)
|
||||||
|
CONFIG = ShiftSpeedConfig("machine", "speed", 0.5)
|
||||||
|
CONFIG_PATH = Path(__file__).resolve().parents[1] / "config/shift-report-machines.yaml"
|
||||||
|
|
||||||
|
|
||||||
|
def summarize(values, **kwargs):
|
||||||
|
return aggregate_shift_speed(
|
||||||
|
[ShiftSpeedSample(START + timedelta(seconds=index), value)
|
||||||
|
for index, value in enumerate(values)],
|
||||||
|
config=CONFIG, start=START, end=END, **kwargs,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_active_filtering_counts_and_statistics():
|
||||||
|
summary = summarize([0, -1, 0.2, 0.5, 1, 2, 6, None, float("nan"),
|
||||||
|
float("inf"), -float("inf"), "3", True, 10**1000])
|
||||||
|
assert summary.sample_count == 7
|
||||||
|
assert summary.active_sample_count == 3
|
||||||
|
assert summary.inactive_sample_count == 4
|
||||||
|
assert summary.invalid_sample_count == 7
|
||||||
|
assert summary.average_line_speed_m_min == 3
|
||||||
|
assert summary.minimum_active_speed_m_min == 1
|
||||||
|
assert summary.maximum_active_speed_m_min == 6
|
||||||
|
assert summary.machine_id == CONFIG.machine_id
|
||||||
|
assert summary.speed_signal_ref == CONFIG.speed_signal_ref
|
||||||
|
assert summary.production_gate_m_min == 0.5
|
||||||
|
assert summary.unit == "m/min"
|
||||||
|
with pytest.raises(FrozenInstanceError):
|
||||||
|
summary.sample_count = 1
|
||||||
|
with pytest.raises(FrozenInstanceError):
|
||||||
|
CONFIG.production_gate_m_min = 0
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("values", [[], [None, float("nan")], [-1, 0, 0.5]])
|
||||||
|
def test_no_active_samples(values):
|
||||||
|
summary = summarize(values)
|
||||||
|
assert summary.active_sample_count == 0
|
||||||
|
assert summary.average_line_speed_m_min is None
|
||||||
|
assert summary.minimum_active_speed_m_min is None
|
||||||
|
assert summary.maximum_active_speed_m_min is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_sample_mean_is_not_time_weighted():
|
||||||
|
samples = [ShiftSpeedSample(START, 1), ShiftSpeedSample(END - timedelta(seconds=1), 9)]
|
||||||
|
summary = aggregate_shift_speed(samples, config=CONFIG, start=START, end=END)
|
||||||
|
assert summary.average_line_speed_m_min == 5
|
||||||
|
|
||||||
|
|
||||||
|
def test_exact_boundaries_and_missing_timestamps():
|
||||||
|
samples = [
|
||||||
|
ShiftSpeedSample(START - timedelta(microseconds=1), 100),
|
||||||
|
ShiftSpeedSample(START, 2),
|
||||||
|
ShiftSpeedSample(END - timedelta(microseconds=1), 4),
|
||||||
|
ShiftSpeedSample(END, 200),
|
||||||
|
ShiftSpeedSample(END + timedelta(seconds=1), None),
|
||||||
|
ShiftSpeedSample(None, 10),
|
||||||
|
ShiftSpeedSample(START.replace(tzinfo=None), 10),
|
||||||
|
]
|
||||||
|
summary = aggregate_shift_speed(samples, config=CONFIG, start=START, end=END)
|
||||||
|
assert summary.average_line_speed_m_min == 3
|
||||||
|
assert summary.sample_count == 2
|
||||||
|
assert summary.invalid_sample_count == 2
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("start,end", [
|
||||||
|
(START.replace(tzinfo=None), END), (START, END.replace(tzinfo=None)),
|
||||||
|
(START, START), (END, START),
|
||||||
|
])
|
||||||
|
def test_invalid_windows_fail_before_gateway(start, end):
|
||||||
|
gateway = Mock()
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
ShiftSpeedService(gateway).summarize(config=CONFIG, start=start, end=end)
|
||||||
|
gateway.get_speed_samples.assert_not_called()
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
aggregate_shift_speed([], config=CONFIG, start=start, end=end)
|
||||||
|
client = Mock()
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
EnlyzeApiGateway(client).get_speed_samples(
|
||||||
|
machine_id="machine", speed_signal_ref="speed", start=start, end=end,
|
||||||
|
)
|
||||||
|
client.post_json.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
def test_dst_fold_compares_elapsed_instants():
|
||||||
|
berlin = ZoneInfo("Europe/Berlin")
|
||||||
|
start = datetime(2026, 10, 25, 2, 30, tzinfo=berlin, fold=0)
|
||||||
|
end = start.replace(fold=1)
|
||||||
|
samples = [ShiftSpeedSample(start, 2),
|
||||||
|
ShiftSpeedSample(datetime(2026, 10, 25, 1, 20, tzinfo=UTC), 4),
|
||||||
|
ShiftSpeedSample(end, 100)]
|
||||||
|
summary = aggregate_shift_speed(samples, config=CONFIG, start=start, end=end)
|
||||||
|
assert summary.average_line_speed_m_min == 3
|
||||||
|
assert summary.active_sample_count == 2
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("gate", [-1, None, True, "0.5", float("nan"), float("inf")])
|
||||||
|
def test_invalid_gate_rejected(gate):
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
replace(CONFIG, production_gate_m_min=gate)
|
||||||
|
|
||||||
|
|
||||||
|
def test_zero_gate_excludes_zero_and_negative():
|
||||||
|
summary = aggregate_shift_speed(
|
||||||
|
[ShiftSpeedSample(START, value) for value in [-1, 0, 1]],
|
||||||
|
config=replace(CONFIG, production_gate_m_min=0), start=START, end=END,
|
||||||
|
)
|
||||||
|
assert summary.active_sample_count == 1
|
||||||
|
assert summary.average_line_speed_m_min == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_large_finite_speeds_do_not_overflow_mean():
|
||||||
|
assert summarize([1e308, 1e308]).average_line_speed_m_min == 1e308
|
||||||
|
|
||||||
|
|
||||||
|
def test_service_composes_gateway_and_propagates_read_failure():
|
||||||
|
gateway = Mock()
|
||||||
|
gateway.get_speed_samples.return_value = [ShiftSpeedSample(START, 2)]
|
||||||
|
service = ShiftSpeedService(gateway)
|
||||||
|
assert service.summarize(config=CONFIG, start=START, end=END).average_line_speed_m_min == 2
|
||||||
|
gateway.get_speed_samples.assert_called_once_with(
|
||||||
|
machine_id="machine", speed_signal_ref="speed", start=START, end=END,
|
||||||
|
)
|
||||||
|
gateway.get_speed_samples.side_effect = RuntimeError("read failed")
|
||||||
|
with pytest.raises(RuntimeError, match="read failed"):
|
||||||
|
service.summarize(config=CONFIG, start=START, end=END)
|
||||||
|
|
||||||
|
|
||||||
|
def page(records, cursor=None, columns=None):
|
||||||
|
return Mock(body={"data": {"columns": columns or ["time", "speed"], "records": records},
|
||||||
|
"metadata": {"next_cursor": cursor}})
|
||||||
|
|
||||||
|
|
||||||
|
def test_gateway_pagination_column_order_and_unavailable_samples():
|
||||||
|
client = Mock()
|
||||||
|
client.post_json.side_effect = [
|
||||||
|
page([[2, START.isoformat()], [None, START.isoformat()]], "next", ["speed", "time"]),
|
||||||
|
page([[START.isoformat(), 4], [START.isoformat(), float("nan")],
|
||||||
|
["invalid-time", 3], None, [START.isoformat()]]),
|
||||||
|
]
|
||||||
|
summary = ShiftSpeedService(EnlyzeApiGateway(client)).summarize(
|
||||||
|
config=CONFIG, start=START, end=END,
|
||||||
|
)
|
||||||
|
assert summary.average_line_speed_m_min == 3
|
||||||
|
assert summary.sample_count == 2
|
||||||
|
assert summary.invalid_sample_count == 5
|
||||||
|
body = {"machine": "machine", "start": START.astimezone(UTC).isoformat(),
|
||||||
|
"end": END.astimezone(UTC).isoformat(), "variables": [{"uuid": "speed"}]}
|
||||||
|
assert client.post_json.call_args_list[0].args == ("/v2/timeseries", body)
|
||||||
|
assert client.post_json.call_args_list[1].args == ("/v2/timeseries", {**body, "cursor": "next"})
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("body", [
|
||||||
|
{"data": {"columns": ["time"], "records": []}},
|
||||||
|
{"data": {"columns": ["time", "speed", "speed"], "records": []}},
|
||||||
|
{"data": {"columns": ["time", "speed"], "records": None}},
|
||||||
|
{"data": {"columns": ["time", "speed"], "records": []}, "metadata": {}},
|
||||||
|
])
|
||||||
|
def test_gateway_structural_errors_fail_read(body):
|
||||||
|
client = Mock()
|
||||||
|
client.post_json.return_value = Mock(body=body)
|
||||||
|
with pytest.raises(ValueError, match="Invalid speed timeseries response"):
|
||||||
|
EnlyzeApiGateway(client).get_speed_samples(
|
||||||
|
machine_id="machine", speed_signal_ref="speed", start=START, end=END,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_gateway_repeated_cursor_rejected():
|
||||||
|
client = Mock()
|
||||||
|
client.post_json.side_effect = [page([], "same"), page([], "same")]
|
||||||
|
with pytest.raises(ValueError, match="already been followed"):
|
||||||
|
EnlyzeApiGateway(client).get_speed_samples(
|
||||||
|
machine_id="machine", speed_signal_ref="speed", start=START, end=END,
|
||||||
|
)
|
||||||
|
assert client.post_json.call_count == 2
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("name,machine,signal,gate", [
|
||||||
|
("B1", "5f42a4f6-9ca0-4f6f-9786-40d50a35b230", "fef41976-1103-4090-b780-eaeecc02fdfa", 0.3),
|
||||||
|
("E1", "8302e3d1-b1e5-42f1-8540-615eb6c73e08", "488e28a9-79a6-44c4-9cc2-c021bb2108ec", 0.5),
|
||||||
|
("K7", "c220f95c-a65e-4cb7-99b7-0626d6c7508c", "823867bb-f5d2-40eb-b875-657155addfd0", 0.5),
|
||||||
|
])
|
||||||
|
def test_validated_machine_configuration(name, machine, signal, gate):
|
||||||
|
config = load_shift_report_machines(CONFIG_PATH)[name].speed
|
||||||
|
assert config.machine_id == machine
|
||||||
|
assert config.speed_signal_ref == signal
|
||||||
|
assert config.production_gate_m_min == gate
|
||||||
|
assert config.unit == "m/min"
|
||||||
|
assert config.signal
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("document", ["machines: {}", "other: {}", "machines: []",
|
||||||
|
"machines:\n B1: {}", "machines:\n B1: null"])
|
||||||
|
def test_invalid_configuration(tmp_path, document):
|
||||||
|
path = tmp_path / "machines.yaml"
|
||||||
|
path.write_text(document)
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
load_shift_report_machines(path)
|
||||||
Reference in new issue
Block a user