Compare commits

..
14 Commits
104 changed files with 11445 additions and 107 deletions

No files matched your search

+2
View File
@@ -32,3 +32,5 @@ activate.sh
# Live polling checkpoints # Live polling checkpoints
data/state/ data/state/
data/backup-spreader3/
+32 -13
View File
@@ -99,11 +99,13 @@ an exact per-order yield needs WIP/transport-delay accounting.
## Bento 1 bentonite-powder integration ## Bento 1 bentonite-powder integration
Bento 1 bentonite-powder consumption is the next planned application of the Bento 1 uses the generic integration mechanism for fresh-bentonite spreaders
same generic integration mechanism. Its ENLYZE source variable and its 1+2 and a separate Spreader 3 source using `linear_signal_discharge`. Spreader 3
validity/gating logic have not yet been selected or validated; both must be may carry bentonite or sand; material identity is not inferred, and only its
determined from Bento 1 process data before implementation. Bento 1 does not bentonite calibration is implemented. It is not automatically aggregated into
need a separate subsystem or calculation formula. `bento1-fresh-bentonite-consumption`. Its dedicated service is deployed and
verified. See [Bento 1 material documentation](docs/bento1-fresh-bentonite.md)
for signals, calibration, validation and runtime details.
## Quantity-total interpretation ## Quantity-total interpretation
@@ -162,12 +164,29 @@ historical-only calculation path.
## Power-meter pipeline ## Power-meter pipeline
The generic `power_meter` package collects configured ENLYZE meters into The generic `power_meter` package collects configured ENLYZE meters into
TimescaleDB/PostgreSQL. The B2 example uses only verified UUIDs for machine, TimescaleDB/PostgreSQL. As of 2026-10-01, the collector is running for B2 with total active power,
energy total, active power total and grid frequency. Power-outage counting is L2 active power, total energy, grid frequency, and Power Outages
supported by schema/repository but remains unset until the real UUID is present (operator-confirmed production state; sandbox systemd access cannot independently
in local raw exploration data. Counter decreases start a new epoch and record confirm live status). Both additional signals are verified and configured.
the new counter value as the increment; the first observation establishes a
baseline with zero increment. Optional phase power is stored as JSONB and does | B2 signal | Verified ENLYZE UUID | Register |
not require L2. `report monthly` reads the database directly, writes | --- | --- | --- |
| L2 active power | `d9ae584e-551b-44b8-a822-3cf9554e77e4` | `3055` |
| Power Outages | `ea1f1f51-1758-4818-8ec3-fbb4b76d1a77` | `1828` |
The deployed service is `production-analytics-power-meter.service`, running B2
with `--follow` at a 60-second interval. Systemd loads the repository `.env`;
the CLI explicitly loads `secrets/enlyze.env` then `secrets/postgres.env`, whose
values override the environment in that order. The CLI does not automatically
load `.env`. Effective settings must include ENLYZE base URL/API key and all
five PostgreSQL connection settings. See the [production runbook](README.md#production-service-and-runtime-settings)
for secret-file requirements and start/restart/status/log commands.
Counter decreases start a new epoch and record the new counter value as the
increment; the first observation establishes a baseline with zero increment.
Optional phase power is stored as JSONB; B2 includes L2. `report monthly` reads
the database directly, writes
`<mount>/<meter>/<year>/<meter>_Powermeter_<YYYY-MM>.pdf`, and persists report `<mount>/<meter>/<year>/<meter>_Powermeter_<YYYY-MM>.pdf`, and persists report
metadata independently of Grafana. metadata independently of Grafana. **The SMB report mount at
`/mnt/reports/energy` is still pending**, so production report delivery remains
pending; collection is independent of the mount.
+69 -10
View File
@@ -101,7 +101,8 @@ utility: `Stundenleistung Anlage` is gated by `Geschwindigkeit Gesamtanlage > 0.
2,672 common samples yield **5.205555556 h** and **5,180.127150811 kg** for run 2,672 common samples yield **5.205555556 h** and **5,180.127150811 kg** for run
00842, matching the previous manual calculation's rounded results. Synthetic 00842, matching the previous manual calculation's rounded results. Synthetic
tests verify equivalence to manual interval integration without local captures tests verify equivalence to manual interval integration without local captures
or live ENLYZE access. Grafana and Bento 1 remain pending. or live ENLYZE access. See [Bento 1 documentation](docs/bento1-fresh-bentonite.md)
for its implemented material sources and verified deployment.
`MaterialPollingService.poll_once(now=...)` starts at the open run's start or `MaterialPollingService.poll_once(now=...)` starts at the open run's start or
resumes inclusively at its last processed timestamp. Duplicate boundary samples resumes inclusively at its last processed timestamp. Duplicate boundary samples
@@ -218,17 +219,68 @@ The primary key deduplicates calculation/machine/order/timestamp (first write wi
A short transaction opens and closes one synchronous connection per snapshot, A short transaction opens and closes one synchronous connection per snapshot,
with 10-second connection and statement timeouts. Snapshot timestamps are poll with 10-second connection and statement timeouts. Snapshot timestamps are poll
start times, not source-sample timestamps. Schema application is manual. start times, not source-sample timestamps. Schema application is manual.
Bento 1 bentonite source and gate selection remain intentionally undefined pending Bento 1 uses the generic integration core for spreaders 1+2 and a separate
process validation; the generic integration core is unchanged and reusable. Spreader 3 source. See [Bento 1 configuration and deployment](docs/bento1-fresh-bentonite.md)
for verified machine-specific details.
## Generic ENLYZE power meters ## Generic ENLYZE power meters
`config/power-meters.example.yaml` is the configuration-only B2 starting point. As of 2026-10-01, the collector is running for B2 with total active power,
It contains the verified machine, energy, active-power and frequency UUIDs; K1 L2 active power, total energy, grid frequency, and Power Outages
and K6 are added as more `meters` entries without new code. Optional phase (operator-confirmed production state; sandbox systemd access cannot independently
channels are a mapping and may omit L2. `power_outages` is intentionally absent confirm live status). Both additional signals are verified and configured.
until its real UUID is verified from the raw second `/v2/variables` page/register
1828; sanitized placeholders are never accepted. | B2 signal | Verified ENLYZE UUID | Register |
| --- | --- | --- |
| L2 active power | `d9ae584e-551b-44b8-a822-3cf9554e77e4` | `3055` |
| Power Outages | `ea1f1f51-1758-4818-8ec3-fbb4b76d1a77` | `1828` |
`config/power-meters.example.yaml` contains the verified B2 machine and signals.
K1 and K6 can be added as more `meters` entries without new code. Phase channels
remain optional for other meters; B2 has L2 configured.
### Production service and runtime settings
The deployed unit is `/etc/systemd/system/production-analytics-power-meter.service`.
It runs as `mtazl` from `/opt/git-projects/production-analytics`, using the repository
venv and B2 configuration with `--meter B2 --follow` at a 60-second interval.
It sets `PYTHONUNBUFFERED=1`, `Restart=always`, and `RestartSec=10`.
The unit loads the repository `.env` through an optional systemd
`EnvironmentFile`; the CLI itself does **not** automatically load `.env`.
Required effective settings are `ENLYZE_BASE_URL` (use
`https://app.enlyze.com/api/`), `ENLYZE_API_KEY`, `POSTGRES_HOST`, `POSTGRES_PORT`,
`POSTGRES_DB`, `POSTGRES_USER`, and `POSTGRES_PASSWORD`.
`ENLYZE_HTTP_TIMEOUT_SECONDS` is optional (default 20).
Compose requires `POSTGRES_PASSWORD` in `.env`; optional `POSTGRES_PORT` controls
the published database port. The collector password must match the database.
Keep credentials in ignored local files. The unit explicitly passes absolute
paths to `secrets/enlyze.env` and `secrets/postgres.env` in the repository.
The CLI merges process environment, ENLYZE secret file, then PostgreSQL secret
file; later file values override earlier ones. Files accept simple `KEY=VALUE`
assignments with optional quotes and are parsed without shell execution.
Do not commit `.env` or secret files or pass credentials as command arguments.
After dependencies, runtime settings, database, and schema are ready, use these
commands on the production host:
```bash
sudo systemctl start production-analytics-power-meter.service
sudo systemctl restart production-analytics-power-meter.service
systemctl status production-analytics-power-meter.service --no-pager
journalctl -u production-analytics-power-meter.service -n 100 --no-pager
journalctl -u production-analytics-power-meter.service -f
```
Restart after changing runtime settings. For foreground collection from the
repository root, provide settings through exported variables or secret files:
```bash
.venv/bin/production-analytics run power-meter \
--config config/power-meters.example.yaml --meter B2 --follow \
--secrets-file secrets/enlyze.env --db-secrets-file secrets/postgres.env
```
Apply `db/schema.sql`, then run a bounded collection/backfill with ENLYZE and Apply `db/schema.sql`, then run a bounded collection/backfill with ENLYZE and
PostgreSQL values from the environment or secret files: PostgreSQL values from the environment or secret files:
@@ -238,7 +290,10 @@ production-analytics run power-meter --config config/power-meters.example.yaml \
--meter B2 --start 2026-09-01T00:00:00Z --end 2026-10-01T00:00:00Z --meter B2 --start 2026-09-01T00:00:00Z --end 2026-10-01T00:00:00Z
``` ```
Generate the independent monthly PDF (under the configured mounted SMB path): **SMB report mount still pending:** `/mnt/reports/energy` is configured but the
SMB share has not yet been mounted/verified. Production report delivery remains
pending; collection is independent of the mount. Once the mount and PDF renderer
are ready, generate the independent monthly PDF:
```bash ```bash
production-analytics report monthly --config config/power-meters.example.yaml \ production-analytics report monthly --config config/power-meters.example.yaml \
@@ -505,3 +560,7 @@ changes. Daily 24h reports and final order summary tables remain future work.
No dashboard, aggregation or lag correction is added here. No dashboard, aggregation or lag correction is added here.
Bento 1: [fresh bentonite consumption configuration and scope](docs/bento1-fresh-bentonite.md). Bento 1: [fresh bentonite consumption configuration and scope](docs/bento1-fresh-bentonite.md).
Explicit shift PDFs for B1, E1, and K7: see [shift report documentation](docs/shift-report.md#generate-an-explicit-shift-pdf).
Nightly historical attribution repair and deployment examples: [Historical reconciliation](docs/historical-reconciliation.md).
+2 -1
View File
@@ -1,4 +1,4 @@
# Fresh bentonite only: the recycled/recovered third spreader is excluded. # Fresh bentonite only: spreader 3 is a separate material source and is excluded.
calculations: calculations:
- id: bento1-fresh-bentonite-consumption - id: bento1-fresh-bentonite-consumption
type: material_consumption type: material_consumption
@@ -16,6 +16,7 @@ calculations:
max_sample_gap_seconds: 20.0 max_sample_gap_seconds: 20.0
erp_workplace: Bento 1 erp_workplace: Bento 1
production_order_format: "Bento 1-{production_order}" production_order_format: "Bento 1-{production_order}"
fallback_nominal_width_m: 5.0
output_metric: material_consumption output_metric: material_consumption
output_unit: kg output_unit: kg
group_by: production_order group_by: production_order
@@ -0,0 +1,20 @@
# Bentonite calibration only. Material identity is not inferred; no total aggregation.
calculations:
- id: bento1-spreader3-consumption
type: material_consumption
version: "1"
machine_ref: 5f42a4f6-9ca0-4f6f-9786-40d50a35b230
process_application_calculation_id: bento1-spreader3-application
source_mode: linear_signal_discharge
application_signal_refs:
- c5611859-275c-44c4-aec0-dfaccc87d478
calibration_ref: bento1-spreader-3-bentonite
gate_signal_ref: fef41976-1103-4090-b780-eaeecc02fdfa
gate_threshold: 0.3
max_sample_gap_seconds: 20.0
erp_workplace: Bento 1
production_order_format: "Bento 1-{production_order}"
fallback_nominal_width_m: 5.0
output_metric: material_consumption
output_unit: kg
group_by: production_order
@@ -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"
+7
View File
@@ -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
+7
View File
@@ -0,0 +1,7 @@
machine_id: 646ebfa0-e97d-4970-b9f4-da94492aecc3
erp_workplace: '1568700'
production_order_format: "E 4-{production_order}"
poll_interval_seconds: 300
lookback_hours: 48
full_reconciliation_hours: 24
completion_tolerance_m2: 0.001
+7
View File
@@ -0,0 +1,7 @@
machine_id: 35612735-03cc-4496-a72e-3c3e2216c720
erp_workplace: GITTERANL
production_order_format: "Gitter 1-{production_order}"
poll_interval_seconds: 300
lookback_hours: 48
full_reconciliation_hours: 24
completion_tolerance_m2: 0.001
+7
View File
@@ -0,0 +1,7 @@
machine_id: 5e89db10-ef0e-4224-866c-eee12bc3d27c
erp_workplace: "GITTER II"
production_order_format: "Gitter 2-{production_order}"
poll_interval_seconds: 300
lookback_hours: 48
full_reconciliation_hours: 24
completion_tolerance_m2: 0.001
+7
View File
@@ -0,0 +1,7 @@
machine_id: ec3baac3-ccc1-4d1e-9b57-3f5ab2daa567
erp_workplace: GITTERIII
production_order_format: "Gitter 3-{production_order}"
poll_interval_seconds: 300
lookback_hours: 48
full_reconciliation_hours: 24
completion_tolerance_m2: 0.001
+7
View File
@@ -0,0 +1,7 @@
machine_id: ffa5de99-66a2-44bd-b039-9b4275bc5f9e
erp_workplace: "GITTER IV"
production_order_format: "Gitter 4-{production_order}"
poll_interval_seconds: 300
lookback_hours: 48
full_reconciliation_hours: 24
completion_tolerance_m2: 0.001
+4
View File
@@ -0,0 +1,4 @@
# Names reference shift-report-machines.yaml; source naming belongs here only.
B1: 'Bento 1-{production_order}'
E1: 'E 1-{production_order}'
K7: 'K 7-{production_order}'
+7
View File
@@ -0,0 +1,7 @@
machine_id: 8c094b9d-32d2-4ddf-b56a-2cd11a09eebf
erp_workplace: K5
production_order_format: "K 5-{production_order}"
poll_interval_seconds: 300
lookback_hours: 48
full_reconciliation_hours: 24
completion_tolerance_m2: 0.001
+7
View File
@@ -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
+11
View File
@@ -12,3 +12,14 @@ calibrations:
signal_values: signal_values:
left: 1.65 left: 1.65
right: 1.75 right: 1.75
bento1-spreader-3-bentonite:
type: linear_signal_discharge
value: 0.376
unit: kg_per_signal_unit_m
calibrated_at: 2026-10-07
method: gravimetric_tray
description: Bento 1 spreader 3, bentonite
reference:
measured_application_g_m2: 540
signal_value: 3.3032
line_speed_m_min: 2.3
+5 -1
View File
@@ -6,10 +6,14 @@ meters:
active_power_total: 41e5729e-b724-49d4-ad24-666d959e121d active_power_total: 41e5729e-b724-49d4-ad24-666d959e121d
grid_frequency: 127ddf56-9358-43ce-84fe-f7631486cfc9 grid_frequency: 127ddf56-9358-43ce-84fe-f7631486cfc9
# Add only after verifying the real UUID in the raw /v2/variables page. # Add only after verifying the real UUID in the raw /v2/variables page.
# power_outages: <verified-uuid> power_outages: ea1f1f51-1758-4818-8ec3-fbb4b76d1a77
# Optional; L2 is not required when it is unavailable. # Optional; L2 is not required when it is unavailable.
# phase_active_power: # phase_active_power:
# L1: <verified-uuid> # L1: <verified-uuid>
# L3: <verified-uuid> # L3: <verified-uuid>
phase_active_power:
L1: 4d94a3f2-005d-4132-9b44-b8ae1d9fa174
L2: d9ae584e-551b-44b8-a822-3cf9554e77e4
L3: 16fadb64-66b2-46e1-b94e-52499d607dbc
poll_interval_seconds: 60 poll_interval_seconds: 60
report_mount_path: /mnt/reports/energy report_mount_path: /mnt/reports/energy
+7
View File
@@ -0,0 +1,7 @@
machine_id: 16c0a111-3049-41d5-9e19-42ee0e047757
erp_workplace: SECEXTRU
production_order_format: "Sec 1/2-{production_order}"
poll_interval_seconds: 300
lookback_hours: 48
full_reconciliation_hours: 24
completion_tolerance_m2: 0.001
+7
View File
@@ -0,0 +1,7 @@
machine_id: 0c207a7c-7813-4cff-90ba-6a0148919d38
erp_workplace: SEC3
production_order_format: "Sec 3-{production_order}"
poll_interval_seconds: 300
lookback_hours: 48
full_reconciliation_hours: 24
completion_tolerance_m2: 0.001
+232
View File
@@ -0,0 +1,232 @@
sites:
espelkamp:
display_name: Espelkamp
timezone: Europe/Berlin
adorf:
display_name: Adorf
timezone: Europe/Berlin
malaysia:
display_name: Malaysia
timezone: Asia/Kuala_Lumpur
machines:
B1:
display_name: B1
site: espelkamp
machine_id: 5f42a4f6-9ca0-4f6f-9786-40d50a35b230
erp_workplace: BENTO 1
capabilities:
production: true
downtime: true
material: true
speed: true
material:
mode: cumulative
calculation_ids:
- 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:
display_name: E1
site: espelkamp
machine_id: 8302e3d1-b1e5-42f1-8540-615eb6c73e08
erp_workplace: '1568705'
capabilities:
production: true
downtime: true
material: true
speed: true
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:
display_name: K7
site: espelkamp
machine_id: c220f95c-a65e-4cb7-99b7-0626d6c7508c
erp_workplace: K7
capabilities:
production: true
downtime: true
material: true
speed: true
material:
mode: cumulative
calculation_ids:
- k7-fiber-consumption
allocation: erp_fiber_share
speed:
signal_ref: 823867bb-f5d2-40eb-b875-657155addfd0
signal: Geschwindigkeit Gesamtanlage
unit: m/min
production_gate_m_min: 0.5
K3/4:
display_name: K3/4
site: espelkamp
machine_id: null
erp_workplace: K3/4
capabilities:
production: true
downtime: false
material: false
speed: false
E4:
display_name: E4
site: espelkamp
machine_id: 646ebfa0-e97d-4970-b9f4-da94492aecc3
erp_workplace: '1568700'
capabilities:
production: true
downtime: true
material: false
speed: false
Gitter 1:
display_name: Gitter 1
site: adorf
machine_id: 35612735-03cc-4496-a72e-3c3e2216c720
erp_workplace: GITTERANL
capabilities:
production: true
downtime: true
material: false
speed: true
speed:
signal_ref: 33abccf8-8dee-4b40-b0ce-63c3c0fd2cd9
signal: Produktionsgeschwindigkeit Automatikbetrieb
unit: m/min
numeric_dwell_gate:
signal_ref: 620511e3-a46b-47c4-8514-f2d4bde29e2b # Querspeicher Geschwindigkeit Abzug Quer (m/min)
threshold: 50.0
comparison: below
minimum_duration_seconds: 150
Gitter 2:
display_name: Gitter 2
site: adorf
machine_id: 5e89db10-ef0e-4224-866c-eee12bc3d27c
erp_workplace: GITTER II
capabilities:
production: true
downtime: true
material: false
speed: true
speed:
signal_ref: d3acefd8-1013-4b59-a235-fa265fd85fae
signal: Produktionsgeschwindigkeit Automatikbetrieb
unit: m/min
numeric_dwell_gate:
signal_ref: 1ae8fb5d-1d25-414a-9181-d35b6cdde507 # Quer Transportwagen Position re. Absolutwertgeber (Position; DB21:224.0)
threshold: 27000
comparison: below
minimum_duration_seconds: 150
Gitter 3:
display_name: Gitter 3
site: adorf
machine_id: ec3baac3-ccc1-4d1e-9b57-3f5ab2daa567
erp_workplace: GITTERIII
capabilities:
production: true
downtime: true
material: false
speed: true
speed:
signal_ref: 88641764-6fd1-4733-a054-80fa43a62470
signal: Produktionsgeschwindigkeit Automatikbetrieb
unit: m/min
numeric_dwell_gate:
signal_ref: f78bd11f-b2a8-4454-86a0-c8de576799c2 # Transportwagen Position re. Absolutwertgeber (Position; DB21:224.0)
threshold: 31000
comparison: below
minimum_duration_seconds: 150
Gitter 4:
display_name: Gitter 4
site: adorf
machine_id: ffa5de99-66a2-44bd-b039-9b4275bc5f9e
erp_workplace: GITTER IV
capabilities:
production: true
downtime: true
material: false
speed: true
speed:
signal_ref: 1d7660d4-10f4-4466-b1fd-076f9fd504fe
signal: Produktionsgeschwindigkeit Automatikbetrieb
unit: m/min
numeric_dwell_gate:
signal_ref: 5685fb13-861d-4e95-8a98-e39d4fc3e059 # Querspeicher Geschwindigkeit Abzug Quer (m/min; DB21:482.0)
threshold: 2
comparison: below
minimum_duration_seconds: 150
K5:
display_name: K5
site: adorf
machine_id: 8c094b9d-32d2-4ddf-b56a-2cd11a09eebf
erp_workplace: K5
capabilities:
production: true
downtime: true
material: false
speed: true
speed:
signal_ref: c3ae3002-b75c-4d7c-bb33-f10265fcf428
signal: Nadelmaschine 3 Auszug
unit: m/min
running_signal_ref: 507b1225-2992-4dd1-8412-34969466722f # Stillstand Nadelmaschine 3 (technical origin: Stillstand Anlage)
running_when: false
Secumat 1/2:
display_name: Secumat 1/2
site: adorf
machine_id: 16c0a111-3049-41d5-9e19-42ee0e047757
erp_workplace: SECEXTRU
capabilities:
production: true
downtime: true
material: false
speed: false
Secumat 3:
display_name: Secumat 3
site: adorf
machine_id: 0c207a7c-7813-4cff-90ba-6a0148919d38
erp_workplace: SEC3
capabilities:
production: true
downtime: true
material: false
speed: false
Bento 2:
display_name: Bento 2
site: malaysia
machine_id: 6201f3de-b940-45d7-930c-1481c5ae9e1d
erp_workplace: BENTO 2
capabilities:
production: true
downtime: false
material: false
speed: false
K1:
display_name: K1
site: malaysia
machine_id: 40f1f58b-21fc-490a-8343-d1888938f11b
erp_workplace: K1
capabilities:
production: true
downtime: false
material: false
speed: false
K6:
display_name: K6
site: malaysia
machine_id: 5e778f87-2d0f-47ac-a3ce-0c0dd9957918
erp_workplace: K6
capabilities:
production: true
downtime: false
material: false
speed: false
+21
View File
@@ -0,0 +1,21 @@
-- Apply once before enabling the reconciliation service (also safe to reapply).
CREATE TABLE IF NOT EXISTS historical_assignment_audit (
id bigserial PRIMARY KEY,
machine_id text NOT NULL,
source_table text NOT NULL,
record_identity jsonb NOT NULL,
previous_order text NOT NULL,
new_order text NOT NULL,
run_id text NOT NULL,
reason text NOT NULL,
action text NOT NULL DEFAULT 'updated',
retained_run_id text,
reconciled_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP,
CHECK (previous_order <> new_order)
);
ALTER TABLE historical_assignment_audit
ADD COLUMN IF NOT EXISTS action text NOT NULL DEFAULT 'updated';
ALTER TABLE historical_assignment_audit
ADD COLUMN IF NOT EXISTS retained_run_id text;
CREATE INDEX IF NOT EXISTS historical_assignment_audit_machine_time_idx
ON historical_assignment_audit (machine_id, reconciled_at);
+17
View File
@@ -126,3 +126,20 @@ CREATE TABLE IF NOT EXISTS production_order_attribution_state (
started_at timestamptz NOT NULL, started_at timestamptz NOT NULL,
ended_at timestamptz NULL ended_at timestamptz NULL
); );
-- Apply once before enabling the reconciliation service (also safe to reapply).
CREATE TABLE IF NOT EXISTS historical_assignment_audit (
id bigserial PRIMARY KEY,
machine_id text NOT NULL,
source_table text NOT NULL,
record_identity jsonb NOT NULL,
previous_order text NOT NULL,
new_order text NOT NULL,
run_id text NOT NULL,
reason text NOT NULL,
action text NOT NULL DEFAULT 'updated',
retained_run_id text,
reconciled_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP,
CHECK (previous_order <> new_order)
);
CREATE INDEX IF NOT EXISTS historical_assignment_audit_machine_time_idx
ON historical_assignment_audit (machine_id, reconciled_at);
+21
View File
@@ -0,0 +1,21 @@
# E4 and Adorf downtime runners
The eight service files use the existing `run downtime-reconcile` command, one
process per machine. Each loads its matching `config/*-downtime.yaml` file and
uses the existing ENLYZE, ERP, and PostgreSQL environment files. They follow the
installed B1/E1/K7 service settings.
From `/opt/git-projects/production-analytics`, install and enable them with:
```bash
sudo install -m 0644 deploy/systemd/production-analytics-downtime-{e4,gitter1,gitter2,gitter3,gitter4,k5,secumat12,secumat3}.service /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable --now production-analytics-downtime-{e4,gitter1,gitter2,gitter3,gitter4,k5,secumat12,secumat3}.service
```
The unit names are `production-analytics-downtime-e4.service`,
`production-analytics-downtime-gitter1.service` through
`production-analytics-downtime-gitter4.service`,
`production-analytics-downtime-k5.service`,
`production-analytics-downtime-secumat12.service`, and
`production-analytics-downtime-secumat3.service`.
@@ -0,0 +1,18 @@
[Unit]
Description=Production Analytics - E4 Downtime Reconciliation
Wants=network-online.target
After=network-online.target
[Service]
Type=simple
User=production-analytics
Group=production-analytics
WorkingDirectory=/opt/git-projects/production-analytics
EnvironmentFile=/opt/git-projects/production-analytics/.env
Environment=PYTHONUNBUFFERED=1
ExecStart=/opt/git-projects/production-analytics/.venv/bin/python -m production_analytics.cli run downtime-reconcile --config /opt/git-projects/production-analytics/config/e4-downtime.yaml --secrets-file /opt/git-projects/production-analytics/secrets/enlyze.env --erp-secrets-file /opt/git-projects/production-analytics/secrets/erp.env
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target
@@ -0,0 +1,18 @@
[Unit]
Description=Production Analytics - Gitter 1 Downtime Reconciliation
Wants=network-online.target
After=network-online.target
[Service]
Type=simple
User=production-analytics
Group=production-analytics
WorkingDirectory=/opt/git-projects/production-analytics
EnvironmentFile=/opt/git-projects/production-analytics/.env
Environment=PYTHONUNBUFFERED=1
ExecStart=/opt/git-projects/production-analytics/.venv/bin/python -m production_analytics.cli run downtime-reconcile --config /opt/git-projects/production-analytics/config/gitter1-downtime.yaml --secrets-file /opt/git-projects/production-analytics/secrets/enlyze.env --erp-secrets-file /opt/git-projects/production-analytics/secrets/erp.env
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target
@@ -0,0 +1,18 @@
[Unit]
Description=Production Analytics - Gitter 2 Downtime Reconciliation
Wants=network-online.target
After=network-online.target
[Service]
Type=simple
User=production-analytics
Group=production-analytics
WorkingDirectory=/opt/git-projects/production-analytics
EnvironmentFile=/opt/git-projects/production-analytics/.env
Environment=PYTHONUNBUFFERED=1
ExecStart=/opt/git-projects/production-analytics/.venv/bin/python -m production_analytics.cli run downtime-reconcile --config /opt/git-projects/production-analytics/config/gitter2-downtime.yaml --secrets-file /opt/git-projects/production-analytics/secrets/enlyze.env --erp-secrets-file /opt/git-projects/production-analytics/secrets/erp.env
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target
@@ -0,0 +1,18 @@
[Unit]
Description=Production Analytics - Gitter 3 Downtime Reconciliation
Wants=network-online.target
After=network-online.target
[Service]
Type=simple
User=production-analytics
Group=production-analytics
WorkingDirectory=/opt/git-projects/production-analytics
EnvironmentFile=/opt/git-projects/production-analytics/.env
Environment=PYTHONUNBUFFERED=1
ExecStart=/opt/git-projects/production-analytics/.venv/bin/python -m production_analytics.cli run downtime-reconcile --config /opt/git-projects/production-analytics/config/gitter3-downtime.yaml --secrets-file /opt/git-projects/production-analytics/secrets/enlyze.env --erp-secrets-file /opt/git-projects/production-analytics/secrets/erp.env
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target
@@ -0,0 +1,18 @@
[Unit]
Description=Production Analytics - Gitter 4 Downtime Reconciliation
Wants=network-online.target
After=network-online.target
[Service]
Type=simple
User=production-analytics
Group=production-analytics
WorkingDirectory=/opt/git-projects/production-analytics
EnvironmentFile=/opt/git-projects/production-analytics/.env
Environment=PYTHONUNBUFFERED=1
ExecStart=/opt/git-projects/production-analytics/.venv/bin/python -m production_analytics.cli run downtime-reconcile --config /opt/git-projects/production-analytics/config/gitter4-downtime.yaml --secrets-file /opt/git-projects/production-analytics/secrets/enlyze.env --erp-secrets-file /opt/git-projects/production-analytics/secrets/erp.env
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target
@@ -0,0 +1,18 @@
[Unit]
Description=Production Analytics - K5 Downtime Reconciliation
Wants=network-online.target
After=network-online.target
[Service]
Type=simple
User=production-analytics
Group=production-analytics
WorkingDirectory=/opt/git-projects/production-analytics
EnvironmentFile=/opt/git-projects/production-analytics/.env
Environment=PYTHONUNBUFFERED=1
ExecStart=/opt/git-projects/production-analytics/.venv/bin/python -m production_analytics.cli run downtime-reconcile --config /opt/git-projects/production-analytics/config/k5-downtime.yaml --secrets-file /opt/git-projects/production-analytics/secrets/enlyze.env --erp-secrets-file /opt/git-projects/production-analytics/secrets/erp.env
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target
@@ -0,0 +1,18 @@
[Unit]
Description=Production Analytics - Secumat 1/2 Downtime Reconciliation
Wants=network-online.target
After=network-online.target
[Service]
Type=simple
User=production-analytics
Group=production-analytics
WorkingDirectory=/opt/git-projects/production-analytics
EnvironmentFile=/opt/git-projects/production-analytics/.env
Environment=PYTHONUNBUFFERED=1
ExecStart=/opt/git-projects/production-analytics/.venv/bin/python -m production_analytics.cli run downtime-reconcile --config /opt/git-projects/production-analytics/config/secumat12-downtime.yaml --secrets-file /opt/git-projects/production-analytics/secrets/enlyze.env --erp-secrets-file /opt/git-projects/production-analytics/secrets/erp.env
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target
@@ -0,0 +1,18 @@
[Unit]
Description=Production Analytics - Secumat 3 Downtime Reconciliation
Wants=network-online.target
After=network-online.target
[Service]
Type=simple
User=production-analytics
Group=production-analytics
WorkingDirectory=/opt/git-projects/production-analytics
EnvironmentFile=/opt/git-projects/production-analytics/.env
Environment=PYTHONUNBUFFERED=1
ExecStart=/opt/git-projects/production-analytics/.venv/bin/python -m production_analytics.cli run downtime-reconcile --config /opt/git-projects/production-analytics/config/secumat3-downtime.yaml --secrets-file /opt/git-projects/production-analytics/secrets/enlyze.env --erp-secrets-file /opt/git-projects/production-analytics/secrets/erp.env
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target
@@ -0,0 +1,11 @@
[Unit]
Description=Production Analytics historical assignment reconciliation
Wants=network-online.target
After=network-online.target
[Service]
Type=oneshot
WorkingDirectory=/opt/git-projects/production-analytics
EnvironmentFile=-/opt/git-projects/production-analytics/.env
ExecStart=/opt/git-projects/production-analytics/.venv/bin/production-analytics historical-reconcile --lookback-days 3
TimeoutStartSec=2h
@@ -0,0 +1,10 @@
[Unit]
Description=Daily historical reconciliation after ERP and DB1 nightly processing
[Timer]
OnCalendar=*-*-* 04:30:00 Europe/Berlin
Persistent=true
Unit=production-analytics-historical-reconcile.service
[Install]
WantedBy=timers.target
+102 -4
View File
@@ -3,8 +3,7 @@
## Three distinct quantities ## Three distinct quantities
All **fresh bentonite** values exclude the third recycled/recovered-material All **fresh bentonite** values exclude the separate spreader 3. Only the two actual rpm signals listed below are used; no SET signals
scatterer. Only the two actual rpm signals listed below are used; no SET signals
are introduced. The specific discharge is central calibration are introduced. The specific discharge is central calibration
data: **2.75 kg/(revolution × metre product width)**. data: **2.75 kg/(revolution × metre product width)**.
@@ -56,7 +55,7 @@ Scope Grafana queries by calculation ID and
`material_snapshot_timestamp` for auditability. `material_snapshot_timestamp` for auditability.
`config/bento1-material-consumption.yaml` opts into process snapshots through `config/bento1-material-consumption.yaml` opts into process snapshots through
`process_application_calculation_id`. This generic option requires rotational `process_application_calculation_id`. This generic option requires calibrated
sources and a positive speed gate. Both outputs reuse the same configured ACT sources and a positive speed gate. Both outputs reuse the same configured ACT
signals, discharge factor and samples. Process points use source timestamps, signals, discharge factor and samples. Process points use source timestamps,
including bootstrap samples from disjoint runs; no interpolation or hold-forward including bootstrap samples from disjoint runs; no interpolation or hold-forward
@@ -103,7 +102,7 @@ cleanup was performed as part of this implementation.
`config/bento1-material-consumption.yaml` defines `config/bento1-material-consumption.yaml` defines
`bento1-fresh-bentonite-consumption`, an estimate of **fresh bentonite consumption** `bento1-fresh-bentonite-consumption`, an estimate of **fresh bentonite consumption**
from actual spreader roll speeds. Both needle rolls apply sequentially across the from actual spreader roll speeds. Both needle rolls apply sequentially across the
full web width. The recycled/recovered third spreader is excluded. full web width. Spreader 3 is excluded.
The generic `rotational_discharge` source converts one or more rpm signals to the The generic `rotational_discharge` source converts one or more rpm signals to the
existing integrator's kg/h: `sum(rpm) × nominal_width_m × specific_discharge_kg_per_rev_m × 60`. existing integrator's kg/h: `sum(rpm) × nominal_width_m × specific_discharge_kg_per_rev_m × 60`.
@@ -155,6 +154,105 @@ and persistence semantics.
Tests use realistic rpm values and synthetic samples, including disjoint-run Tests use realistic rpm values and synthetic samples, including disjoint-run
bootstrap and persisted resume. They are not a new replay of recorded ENLYZE data. bootstrap and persisted resume. They are not a new replay of recorded ENLYZE data.
## Separate spreader 3 material source
Spreader 1+2 remains fresh bentonite from actual roll rpm, calibrated at
**2.75 kg/(rev*m)**. Spreader 3 is a separate material source: it can contain
bentonite or sand depending on the product. No material identity is inferred,
and no spreader-3 value is added to fresh-bentonite consumption or efficiency.
No total-bentonite aggregate is implemented. Sand calibration is intentionally
not implemented yet.
`config/bento1-spreader3-material-consumption.yaml` uses generic
`linear_signal_discharge` with central calibration
`bento1-spreader-3-bentonite`: **0.4691089108910891 kg/(signal_unit*m)**,
gravimetric tray, 2026-09-08. Reference: **3.03 signal @ 2.3 m/min → 618 g/m²**.
The factor is derived as `factor = 618 * 2.3 / (3.03 * 1000)`.
Source `c5611859-275c-44c4-aec0-dfaccc87d478`, display name
“Austragsbehälter Austragsschnecke Geschwindigkeit Istwert”, origin
`AUFSTREUUNG_2/DischargeHopper_Output_Screw/ACT_Speed`.
The source's ENLYZE unit metadata is not authoritative physical units.
- Application: `application_g_m2 = signal_sum * factor * 1000 / line_speed_m_min`, independent of width.
- Consumption rate: `mass_flow_kg_min = signal_sum * factor * nominal_width_m`,
multiplied by 60 for the existing kg/h integrator. This equals
`application_g_m2 * nominal_width_m * line_speed_m_min / 1000`.
- Same ERP nominal-width provider, `Bento 1-{production_order}` formatting,
ERP workplace `Bento 1`, and gate signal
`fef41976-1103-4090-b780-eaeecc02fdfa`
(`Transport Auszug Geschwindigkeit Istwert`, unit m/min) strictly > 0.3 m/min,
previous-value integration, 20-second maximum gap, and disjoint-run boundaries.
- Application points are emitted only while the gate is active; zero source
signal emits zero application during production.
Mass flow is independent of line speed. Speed is required for conversion to
application in g/m² and serves as the production gate; consumption does not
divide by speed. Consumption is attributed separately per production order.
| Calculation ID | Persistence |
| --- | --- |
| `bento1-spreader3-application` | `material_application_snapshots.application_g_m2` |
| `bento1-spreader3-consumption` | `material_consumption_snapshots.consumption_kg` |
### Validation
The gravimetric reference, source 3.03 at 2.3 m/min, gives approximately
**618 g/m²**. This is the calibration reference.
Production plausibility check on **2026-09-30**, 10:00–13:00 Europe/Berlin,
order `Bento 1-12026000984`: average Spreader 3 source approximately **8.999**
and average line speed approximately **4.999 m/min** give Spreader 3 application
approximately **844.47 g/m²**. Spreaders 1+2 application was approximately
**3915.96 g/m²**. The manually combined value for this verified bentonite
production was approximately **4760.43 g/m²**, matching the expected overall
range of roughly **4400–4800 g/m²**. These rounded values are a plausibility
cross-check, not a precision measurement. This combined value is only a
validation cross-check: software intentionally does not automatically combine
Spreader 3 with spreaders 1+2 because it may contain another material.
An observed short startup peak of approximately **2132.5 g/m²** was verified
as physically consistent with Spreader 3 signal approximately **2.2339** and
line speed approximately **0.4914 m/min**. Low web speed during startup causes
the high g/m² value. It should not be filtered from material consumption:
consumption integrates mass flow and does not divide by line speed.
### Runtime and deployment notes
Spreader 3 now runs as a dedicated systemd service,
`production-analytics-bento1-spreader3.service`, using the normal project `.env`,
ENLYZE secrets and ERP secrets for production-order attribution. The deployed
service was verified running successfully and polling approximately every
10 seconds.
The shared material state root isolates calculation-specific JSON checkpoints
under `<state-directory>/<sha256(calculation-id)>/`. For consumption calculation
`bento1-spreader3-consumption`, the directory is:
```text
/opt/git-projects/production-analytics/data/state/material/c8d0426504f2ce2ff214818e4ffa9b4daf4182131c0af3c5a1cca23a3dee566a/
```
There is no separate application checkpoint directory. Existing spreaders 1+2
and K7 checkpoint paths remain unchanged; do not reset their state. No schema
changes are needed if the existing generic snapshot tables are present.
Verified accumulated state after correction for `Bento 1-12026000984`:
consumption approximately **11203.890692078 kg**, integrated running time
**31260 s**. This is only a runtime validation snapshot, not a calibration
reference or a precision claim for physical consumption.
The initial manual validation run created Spreader 3 state as user `mtazl`,
causing a state-directory ownership issue. The production service runs as
`production-analytics:production-analytics`; the calculation-specific state
directory must be writable by that service account.
This calibration is valid only for bentonite. Enable this runner only for
validated bentonite operation; until reliable material identification is available,
its output is a bentonite-calibrated estimate, not material-aware consumption.
Future sand support needs independently measured calibration and reliable
material/order attribution, with explicit handling of material changes and
checkpoint/history separation. Current ERP width is assumed constant per order.
## Historical migration from SET to rpm: review before execution ## Historical migration from SET to rpm: review before execution
The following records the earlier source-model migration, **not a prerequisite The following records the earlier source-model migration, **not a prerequisite
+25
View File
@@ -102,6 +102,31 @@ an approximate reported finished-product mass of 4,845.8 kg. This supports the
physical plausibility of the feed integration; it is not a precise material physical plausibility of the feed integration; it is not a precise material
yield calculation. yield calculation.
### B2 power-meter signals
Verified B2 machine UUID: `0d7955e9-5cde-4e14-9af7-5b041dc796f0`.
These are customer-specific observations.
| B2 signal | Verified ENLYZE UUID | Register |
| --- | --- | --- |
| L2 active power | `d9ae584e-551b-44b8-a822-3cf9554e77e4` | `3055` |
| Power Outages | `ea1f1f51-1758-4818-8ec3-fbb4b76d1a77` | `1828` |
Other verified configured signals are total energy
`0f5c0853-1aa7-4fa3-b267-ea2669024e46`, total active power
`41e5729e-b724-49d4-ad24-666d959e121d`, and grid frequency
`127ddf56-9358-43ce-84fe-f7631486cfc9`.
As of 2026-10-01, the collector is running for B2 with total active power,
L2 active power, total energy, grid frequency, and Power Outages
(operator-confirmed production state; sandbox systemd access cannot independently
confirm live status). Both additional signals are verified and configured.
The deployed service is `production-analytics-power-meter.service`. See the
[production runbook](../README.md#production-service-and-runtime-settings) for
`.env`/secret-file requirements and start/restart/status/log commands.
**The SMB report mount at `/mnt/reports/energy` is still pending.**
## STILL UNKNOWN ## STILL UNKNOWN
- Full customer response coverage, permissions, authentication - Full customer response coverage, permissions, authentication
+77
View File
@@ -0,0 +1,77 @@
# Historical attribution reconciliation
Run from the repository with the existing ENLYZE, ERP, and PostgreSQL secret
files (or use the CLI secret-file flags):
```sh
production-analytics historical-reconcile --lookback-days 3 --dry-run
production-analytics historical-reconcile --lookback-days 3
```
The default window is the previous three **complete Europe/Berlin calendar days**,
from local midnight inclusive to today's midnight exclusive. DST days can have
23 or 25 hours. Today's live polling is excluded. Machine IDs and ERP workplaces
come from `config/shift-report-machines.yaml`; ENLYZE order name templates are
in `config/historical-order-formats.yaml` using the existing order formatter.
Apply (or reapply) `db/historical_assignment_audit.sql` before a write run; new database
installations can use `db/schema.sql`. No schema changes happen automatically.
The job reads material consumption, channel consumption, and process application
snapshots for every configured machine. It requires exactly one closed ENLYZE run
covering the sample, plus finished-goods ERP confirmations in that run whose order
set equals the run's order. It queries the full extent of overlapping closed runs,
including evidence outside the selected window. No confirmation timestamp is
interpreted as a production boundary. Missing evidence, open runs, competing runs,
and ERP/ENLYZE disagreements are unresolved and logged with record identities.
Ordinary corrections change only production_order. Measured values, timestamps,
and run IDs remain untouched. A persisted cumulative run must be entirely inside the selected data
and every affected sample must have unambiguous corroborated evidence. Different
parts of the same physical run may map to different closed ENLYZE runs/orders.
Ambiguous or partial persisted runs remain unresolved; a wider lookback can
resolve partial runs. No ERP confirmation point is used to invent a boundary.
Cumulative material intervals belong to the ending sample's production order.
Order changes never establish a new baseline: each adjacent counter delta is
counted exactly once, preserving total physical consumption. Channel material
identity gaps are bridged only when all enclosing samples share the same order.
The summary retains raw row counts and additionally reports physical runs
inspected, runs with proposed corrections, proposed/corrected order segments,
and unresolved runs/segments. Run identities are scoped by source table, machine,
and calculation; channel segment counts use separate extruder/channel streams.
Segments are contiguous samples with the same target order and correction state.
ERP KPI efficiency snapshots and downtime attribution are outside this job's
scope: they have separate derivation/reconciliation semantics. Live report
reconstruction is unchanged; no final reports are persisted or regenerated.
Updates use compare-and-set predicates and one serializable transaction per
machine, with an advisory lock for concurrent jobs. For application snapshots only,
an existing corrected-key row is retained and the stale row deleted when their
application_g_m2 values are exactly equal and the target run ID matches the
corroborated ENLYZE run. A different value or run ID fails and rolls back the
machine. Concurrent modifications also fail. The same transaction inserts audit
rows recording the action, machine, table, full record key, old/new order, source
run ID, retained target run ID for deduplication, evidence reason, and database
timestamp. Already-correct rows
produce neither updates nor audit entries. Dry-run runs the same evidence and
whole-run checks but writes nothing, including audit rows.
Any required source/database failure is reported per machine and results in a
nonzero exit status; other machines can complete. Invalid configuration fails
before processing. Inspect unresolved counts as well as the exit status: lack of
unambiguous evidence is distinct from a source outage.
Deployment examples (not installed or enabled automatically):
- `deploy/systemd/production-analytics-historical-reconcile.service`
- `deploy/systemd/production-analytics-historical-reconcile.timer`
Review deployment paths, credentials and service user for the host; apply the audit
DDL and review a dry-run before installing/enabling the timer. The timer uses
`OnCalendar=*-*-* 04:30:00 Europe/Berlin` after ERP at approximately 00:00 and DB1 at
approximately 02:30. `Persistent=true` catches a missed run after reboot. The
lookback is relative to actual execution time, so long outages require an explicit
larger lookback. No automatic retention or backfill beyond that window is implied.
+36 -6
View File
@@ -2,7 +2,7 @@
Process calibration values live in the version-controlled Process calibration values live in the version-controlled
`config/material-calibrations.yaml`. Calculations refer to opaque IDs; IDs have `config/material-calibrations.yaml`. Calculations refer to opaque IDs; IDs have
no special meaning to the parser. The current entry is: no special meaning to the parser. The spreader 1+2 entry is:
```yaml ```yaml
calibrations: calibrations:
@@ -40,7 +40,7 @@ consumption; the calculation algorithms are unchanged. There is no unit conversi
Missing/unreadable files, missing IDs, invalid metadata and incompatible type or Missing/unreadable files, missing IDs, invalid metadata and incompatible type or
unit raise `CalculationConfigError` before a runner starts. Existing direct numeric unit raise `CalculationConfigError` before a runner starts. Existing direct numeric
configurations remain supported; specifying both a reference and a direct factor configurations remain supported; specifying both a reference and a direct factor
is rejected. References are currently supported by rotational discharge consumers. is rejected. References are supported by rotational discharge and `linear_signal_discharge` consumers.
K7 uses direct mass rate and does not load or require a calibration file. K7 uses direct mass rate and does not load or require a calibration file.
## Updating a calibration ## Updating a calibration
@@ -67,7 +67,37 @@ On 2026-09-08, an independent gravimetric tray measurement found 4068 g/m² at
rounded factor **2.75 kg/(rev*m)**. The original measurement remains recorded, rounded factor **2.75 kg/(rev*m)**. The original measurement remains recorded,
without fitting or adjusting the runtime value to reproduce it exactly. without fitting or adjusting the runtime value to reproduce it exactly.
Only fresh-bentonite spreaders 1 and 2 are included. Before adding spreader 3, Spreader 3 has an independent entry in the same registry:
confirm its material scope, actual signal units, independent calibration and
whether its output belongs in the fresh-material KPIs. No spreader 3 support is ```yaml
included here. bento1-spreader-3-bentonite:
type: linear_signal_discharge
value: 0.4691089108910891
unit: kg_per_signal_unit_m
calibrated_at: 2026-09-08
method: gravimetric_tray
description: Bento 1 spreader 3, bentonite
reference:
measured_application_g_m2: 618
signal_value: 3.03
line_speed_m_min: 2.3
```
The generic linear consumer requires type `linear_signal_discharge`, unit
`kg_per_signal_unit_m`, a positive value, and an explicit calibration reference.
It resolves `specific_discharge_kg_per_signal_unit_m`; this runtime field cannot
be configured directly as a substitute for the central reference.
Calibration measurement: **3.03 signal @ 2.3 m/min → 618 g/m²**.
The exact derived discharge factor is `618 * 2.3 / (3.03 * 1000) = 2369/5050`,
stored at float precision as **0.4691089108910891 kg/(signal_unit*m)**.
Application is `signal_sum * factor * 1000 / line_speed_m_min`, independent of width.
Mass flow is `signal_sum * factor * nominal_width_m` kg/min, independent of speed;
the existing kg/h integrator receives this discharge multiplied by 60.
This measured bentonite calibration does not establish physical units from
ENLYZE metadata and must not be used for sand. Sand calibration is intentionally
not implemented yet. Spreader 3 may carry sand on other
products. Its application, consumption and checkpoints remain separate from
fresh-bentonite spreaders 1+2, with no inferred material identity or automatic
sum. See [Bento material documentation](bento1-fresh-bentonite.md) for configuration,
formulas and operating assumptions.
+105
View File
@@ -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.
+290
View File
@@ -0,0 +1,290 @@
# Unified shift-report composition
`ShiftReportService` composes the existing production, downtime, material, and
speed services sequentially. It performs no database or HTTP reads itself.
For production rows it asks the shared production-order service for FA KPI
attribution, preserving the original shift totals and source metadata. The
frozen `ShiftReport` feeds both PDF and live web UI; presentation remains
output-independent.
## Configuration and API
`config/shift-report-machines.yaml` is self-contained for composition:
```yaml
sites:
espelkamp:
display_name: Espelkamp
timezone: Europe/Berlin
adorf:
display_name: Adorf
timezone: Europe/Berlin
malaysia:
display_name: Malaysia
timezone: Asia/Kuala_Lumpur
machines:
B1:
display_name: B1
site: espelkamp
machine_id: 5f42a4f6-9ca0-4f6f-9786-40d50a35b230
erp_workplace: BENTO 1
capabilities:
production: true
downtime: true
material: true
speed: true
material:
mode: cumulative
calculation_ids:
- 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
```
Every machine requires a display name, configured site, ERP workplace, and all four
boolean capability flags; at least one capability must be enabled. A machine ID is
required for downtime, material, or speed, but may be absent for production-only
machines. Material and speed configuration are required
exactly when their capability is enabled. Material modes remain `cumulative` and
`channel`; optional `allocation` is `none` (default) or `erp_fiber_share`. K7 selects
the latter through configuration. `load_shift_report_config()` exposes immutable
site and machine mappings; `load_shift_report_machines()` retains the machine-only
view used by historical reconciliation.
The loader returns `ShiftReportMachineConfig` values with frozen material and
speed configurations. Speed-only consumers now use `machines[name].speed`.
Missing/unknown fields, duplicate YAML keys or non-null machine IDs, invalid site
timezones, unsupported material
modes, empty/duplicate calculation IDs, and invalid speed metadata are rejected.
No unrelated YAML configuration is loaded at runtime.
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", machines["B1"].timezone)
report = service.build(machine_name="B1", start=start, end=end)
```
`shift_report_window` lives in `calculations.shift_report`; the loader and
service live in `service.shift_report_config` and `service.shift_report`.
The day is the shift's start date in the machine site's timezone. Early is 06:00–14:00, late is
14:00–22:00, and night is 22:00–06:00 on the following day. Night shifts can have
seven or nine elapsed hours at DST transitions. Explicit windows are validated
as aware, positive-duration instants and normalized to the site timezone 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`.
The ERP SQL query uses naive site-local `[start, end)` timestamps, and returned
confirmations are attached to the configured IANA timezone. Historical
reconciliation retains its Europe/Berlin default.
`report.downtime.non_downtime_seconds` is the elapsed shift duration minus the
union of downtime intervals. It is a time complement and does not measure actual
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 enabled shift-wide source is mandatory. Disabled sections are `None` in the report and
render as unavailable; no source is queried for them. Exceptions propagate
immediately and later services are not called. An empty successful summary remains
an empty summary; a failed
read is never replaced with zeros. No cross-source matching of runs or orders is
introduced, and sequential reads are not a transactionally consistent snapshot
across ERP, PostgreSQL, and ENLYZE.
## Generate an explicit shift PDF
Install the project with `pip install -e '.[dev]'`. Shift PDFs use the declared
`reportlab>=4.2,<5` dependency: a direct PDF writer without an external browser
or native HTML rendering stack. The older monthly energy report remains separate.
Run from the repository root, with access to the existing read-only sources:
```bash
production-analytics report shift --machine E1 \
--start '2026-10-07T06:00:00+02:00' \
--end '2026-10-07T14:00:00+02:00' \
--output data/reports/E1_2026-10-07_early.pdf
```
The PDF is written exactly to `--output`, relative to the working directory for
relative paths. Parent directories are created, and an existing file is replaced
only after rendering succeeds. No sidecar HTML is written. B1, E1, and K7 are
configured in `config/shift-report-machines.yaml`; override with `--config`.
Start and end are mandatory ISO 8601 timestamps with offsets (or `Z`); the end
must follow the start. There is no implicit current-shift selection.
Settings are read from the process environment, overlaid by these dotenv files:
- `secrets/enlyze.env` (`--secrets-file`): `ENLYZE_BASE_URL`, `ENLYZE_API_KEY`,
optional `ENLYZE_HTTP_TIMEOUT_SECONDS`.
- `secrets/erp.env` (`--erp-secrets-file`): `ERP_DB_HOST`, `ERP_DB_PORT`,
`ERP_DB_NAME`, `ERP_DB_USER`, `ERP_DB_PASSWORD`.
- `secrets/postgres.env` (`--db-secrets-file`): `POSTGRES_HOST`, `POSTGRES_PORT`,
`POSTGRES_DB`, `POSTGRES_USER`, `POSTGRES_PASSWORD`.
PostgreSQL must already contain the existing downtime and material snapshots;
this command performs no collection or polling. ERP supplies production and
ENLYZE supplies speed through the existing readers. Source failures fail the
command; empty successful summaries receive explicit German empty-state text.
Validation/configuration errors return exit code 2; other failures return 1.
The A4 slip includes production, supplied totals, downtime with the top three
reasons, material consumption including channel identities, and running speed.
Numbers use German separators with two decimal places. Durations retain hours,
minutes, and tenths of seconds. Times display the report site's timezone and
numeric offsets, including across daylight-saving transitions. Missing material
names are explicitly marked `Nicht verfügbar`; no identity is inferred. B1
source assignments are rendered unchanged, and energy is excluded.
`present_report(report)` returns an immutable, deterministic presentation model;
`render_pdf(report)` returns PDF bytes and `write_pdf(report, output)` writes them.
Only the supplied `ShiftReport` is consumed. Fixed ReportLab invariant metadata,
styles, fonts, and no generated-at clock make PDF bytes repeatable for the same
input and installed ReportLab version. Bytes are not promised identical across
library versions. Long reports paginate with repeated table headers and page
numbers. The domain report is also the input for the live web presenter.
## Live web interface
The website is the primary working interface; PDF is an export/archive artifact.
Run from the repository root:
```bash
.venv/bin/python -m production_analytics.web --port 8087
```
Open <http://127.0.0.1:8087/>. After installing the updated project, the equivalent
entry point is `production-analytics-web`. This lightweight standard-library WSGI
application uses no frontend framework. `--host` defaults to loopback; `--port`
defaults to `SHIFT_REPORT_PORT` or 8087. The bundled server is intended for local
use; a production deployment can serve `create_app(...)` with a WSGI server.
Machine configuration and secret-file options match the report CLI: `--config`,
`--secrets-file`, `--erp-secrets-file`, and `--db-secrets-file`.
The date is always the shift **start date**, including night shifts. The default
uses the selected machine site's local time and selects the most recent fully completed
shift: before 06:00 yesterday's late shift; from 06:00 yesterday's night shift;
from 14:00 today's early shift; from 22:00 today's late shift. At a boundary the
just-completed shift becomes the default. Night windows end on the following
calendar day; DST nights have seven or nine elapsed hours.
GET parameters are `date=YYYY-MM-DD`, `shift=early|late|night`, and `machine`
(configuration key). Omitted parameters use the default selection. Every request,
including reloads and `format=pdf`, constructs the existing source services and
calls `ShiftReportService.build` exactly once. No final report is persisted or
cached. Existing raw material snapshots remain source inputs. Responses use
`Cache-Control: no-store`.
HTML formats `present_report(report)` blocks shared with PDF, including the
existing material allocation explanation. `Als PDF exportieren` submits the
selected controls and passes that request's freshly built `ShiftReport` directly
to `render_pdf`. Export therefore reflects current data at export time; source
corrections between viewing and exporting may change the result. It never reuses
a stale stored report or runs a second fetch/calculation path. The HTML data-state
time is recorded after service generation, in the machine site's timezone, and makes no
completeness claim. Sources are still read sequentially, not transactionally.
Invalid selections return a German page-level error (HTTP 400). Source/settings
or rendering failures return a generic German error (HTTP 503), retaining the
selection controls without exposing exception text or credentials.
## Fertigungsauftrag search
The web UI links to `/orders?q=...` for a complete or partial FA number. Search
trims surrounding whitespace, rejects empty input, treats SQL wildcard characters
literally, and caps results at 25 distinct FAs. An exact match is listed first;
other results are ordered by FA. Repeated confirmation rows collapse into one FA
result, with separate workplace/article entries when needed. `/order?production_order=...`
shows the selected order and its affected shifts. Each shift links to the existing
live report URL with machine, shift start date and shift name.
The order view reads positive `Rückmeldemenge` rows from
`dbo.GRAFANA_PRODUCTION_CONFIRMATION`, matching the finished-production quantity
semantics of the shift report. The view's `Zeitstempel` is an ERP confirmation
timestamp; first and last timestamps do not describe uninterrupted machine runtime.
Each row is assigned to a configured machine by its exact `erp_workplace`, then
interpreted in that machine's site timezone. Local 22:00–05:59 belongs to the
night shift whose start date may be the previous day. Multiple rows for the same
FA, machine and shift sum their positive feedback m². Unknown or ambiguous
workplaces remain visible but cannot be assigned a configured shift.
The ERP gateway owns parameterized read-only SQL, the production-order service
owns mapping, shift grouping, and approximate KPI windows, and a dedicated
presenter renders HTML. The order/machine/shift model can later anchor roll/QS
and setup-sheet views; those data are not included yet. ERP timestamps are local
datetimes without offsets; autumn repeated-hour rows are interpreted as the
first occurrence, as in the existing confirmation gateway.
For each affected machine shift, positive ERP confirmations for **all** FAs are
sorted by instant (FA breaks ties). Consecutive confirmations of one FA form a
run. The boundary between adjacent runs is the midpoint between the preceding
run's last confirmation and the next run's first confirmation. The first run
starts at shift start and the last ends at shift end. Windows are half-open and
do not overlap. If an FA returns after another FA, it has multiple windows but
still one row for that shift. These windows are a practical estimate from ERP
confirmation times, **not** exact machine-running intervals; idle periods at
shift edges may be included. Exact same-time FA changes are sorted by FA; a
zero-length window yields unavailable KPIs rather than an invented interval.
Each window is passed to the existing speed service, retaining the machine's
numeric, Boolean, or dwell activity gate. The displayed FA speed combines active
sample means by active sample count, so it remains an arithmetic sample mean.
For material sources without an order-aware allocator, each window is passed to
the configured cumulative or channel material service, using its normal
baseline and counter-delta rules. Snapshot timing around midpoint boundaries
can leave small gaps or shifts in attribution, so those segment totals need only
approximately reconcile with the whole-shift total. Where an order-aware
allocator is configured, K7 being the current example, FA material instead sums
the allocated items from the **full-shift** material result by production order.
The compact FA value thus uses the same ENLYZE measurement and ERP fiber
allocation as the detailed material table. The shift report reuses its already
allocated summary; the order detail obtains and allocates a full-shift summary.
Speed always uses the approximate FA windows.
The shift report's production table uses these same FA windows and KPI results
for each listed order. Its speed describes the FA's estimated period; material
uses the configured segment or order-aware source rule. The shift-wide material
section remains available as a reconciliation total; the shift-wide speed
summary stays in the report model but is not rendered. In HTML, the FA number
links directly to `/order?production_order=...` for the order's full shift list.
The PDF prints the FA number as text.
Disabled speed or material capability produces `—` and makes no query to that
source. No active speed samples also produce `—`; an observed material total of
zero remains `0,00 kg`. Known ENLYZE/PostgreSQL/ERP source-read failures degrade
that optional KPI to unavailable. Unexpected configuration or calculation errors
still fail the order page rather than being hidden.
+68
View File
@@ -0,0 +1,68 @@
# Shift running-speed KPI
`average_line_speed_m_min` is the arithmetic mean of active, finite production-speed
samples in `[start, end)`. Each active sample has equal weight. The calculation does
not interpolate or weight speed by elapsed time.
## Activity gates
The `speed` block has exactly one activity method:
- **Simple numeric:** `production_gate_m_min` selects speed samples strictly above
the threshold. B1, E1 and K7 retain this behavior.
- **Boolean:** `running_signal_ref` and optional `running_when` (default `true`)
select samples whose status is exactly that Boolean. K5 uses `running_when: false`
because its status signal is true when stopped.
- **Numeric dwell:** `numeric_dwell_gate` has `signal_ref`, finite `threshold`,
`comparison` (`below` or `above`), and positive integer
`minimum_duration_seconds`. Gitter 1–4 use `below` and 150 seconds. Their
production-speed signal holds its last value while stopped, and their PLC
Boolean status did not reliably indicate downtime. The numeric gate follows
the configured ENLYZE threshold and minimum duration concept.
For `below`, only a gate value strictly less than the threshold satisfies the
condition. An equal value ends a below-threshold run. Rows are ordered by their
UTC timestamps; a condition reading remains the observed state until the next
reading. A continuous below-threshold run qualifies when the elapsed time from
its first below-threshold timestamp to the first non-below reading is at least
the minimum duration. If it qualifies, **all** speed samples in that run are
inactive, including those before the minimum duration elapsed. A short run
bracketed by non-below readings stays active. The same rules apply to `above`.
The interval ending at the non-satisfying reading excludes that reading.
The service requests speed and the gate signal together from `/v2/timeseries`.
For a dwell gate it extends the read window by one minimum duration on each side;
only production-speed samples in the original report window enter the KPI. This
lets a qualifying run crossing a report boundary be classified when the source
provides enough surrounding readings. An unclosed short run, or a short run
without a preceding non-satisfying reading, has unknown duration and is excluded
conservatively. An invalid or non-finite gate reading breaks continuity and its
speed row is excluded. A missing required gate column fails the read. No absent
rows are synthesized; the result depends on the timestamps returned by ENLYZE,
which deserves validation against live boundary cases.
Invalid speed values (including Boolean, null, non-numeric, NaN, and infinity)
are excluded in every mode. Invalid timestamps are also excluded. In Boolean
mode, missing or non-Boolean status is excluded. `sample_count` is the sum of
active and inactive valid speed samples; excluded samples increment
`invalid_sample_count`. If no active samples remain, average, minimum and maximum
are `None`.
Machine UUIDs and gate settings live in `config/shift-report-machines.yaml`.
The loader validates the gate fields and rejects overlapping Boolean and dwell
gates. `ShiftSpeedService.summarize()` composes the gateway read with the pure
`aggregate_shift_speed()` calculation. The calculation accepts
`ShiftSpeedSample(timestamp, value, running, gate_value)` records. Structural
timeseries and pagination errors fail the read instead of returning a partial KPI.
## Supplied legacy 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 supplied validation values, not a new live read.
+2 -1
View File
@@ -10,7 +10,7 @@ readme = "README.md"
requires-python = ">=3.11" requires-python = ">=3.11"
license = { text = "Proprietary" } license = { text = "Proprietary" }
authors = [{ name = "Production Analytics Team" }] authors = [{ name = "Production Analytics Team" }]
dependencies = ["PyYAML>=6.0", "psycopg[binary]>=3.2,<4", "pymssql>=2.4.0,<3"] dependencies = ["PyYAML>=6.0", "psycopg[binary]>=3.2,<4", "pymssql>=2.4.0,<3", "reportlab>=4.2,<5"]
[project.optional-dependencies] [project.optional-dependencies]
dev = [ dev = [
@@ -20,6 +20,7 @@ dev = [
[project.scripts] [project.scripts]
production-analytics = "production_analytics.cli.__main__:main" production-analytics = "production_analytics.cli.__main__:main"
production-analytics-web = "production_analytics.web:main"
[tool.hatch.build.targets.wheel] [tool.hatch.build.targets.wheel]
packages = ["src/production_analytics"] packages = ["src/production_analytics"]
@@ -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
@@ -59,8 +59,10 @@ class MaterialCalculationConfig:
rotational_speed_signal_refs: tuple[str, ...] = () rotational_speed_signal_refs: tuple[str, ...] = ()
specific_discharge_kg_per_rev_m: float | None = None specific_discharge_kg_per_rev_m: float | None = None
calibration_ref: str | None = None calibration_ref: str | None = None
specific_discharge_kg_per_signal_unit_m: float | None = None
erp_workplace: str = "" erp_workplace: str = ""
production_order_format: str = "" production_order_format: str = ""
fallback_nominal_width_m: float | None = None
process_application_calculation_id: str | None = None process_application_calculation_id: str | None = None
@@ -92,10 +94,11 @@ def load_material_calculation(
raise CalculationConfigError(f"{prefix}.type: only 'material_consumption' is supported") raise CalculationConfigError(f"{prefix}.type: only 'material_consumption' is supported")
area = entry.get("source_mode", "direct_mass_rate") == "area_application" area = entry.get("source_mode", "direct_mass_rate") == "area_application"
rotational = entry.get("source_mode") == "rotational_discharge" rotational = entry.get("source_mode") == "rotational_discharge"
linear = entry.get("source_mode") == "linear_signal_discharge"
if rotational: if rotational:
entry.setdefault("gate_signal_ref", None) entry.setdefault("gate_signal_ref", None)
entry.setdefault("gate_threshold", 0.0) entry.setdefault("gate_threshold", 0.0)
if area or rotational: if area or rotational or linear:
entry.setdefault("rate_signal_ref", "unused") entry.setdefault("rate_signal_ref", "unused")
missing = required - entry.keys() missing = required - entry.keys()
if missing: if missing:
@@ -121,9 +124,10 @@ def load_material_calculation(
mode = entry.get("source_mode", "direct_mass_rate") mode = entry.get("source_mode", "direct_mass_rate")
if not isinstance(mode, str) or mode not in { if not isinstance(mode, str) or mode not in {
"direct_mass_rate", "area_application", "rotational_discharge", "direct_mass_rate", "area_application", "rotational_discharge",
"linear_signal_discharge",
}: }:
raise CalculationConfigError("Unsupported material source_mode") raise CalculationConfigError("Unsupported material source_mode")
if area or rotational: if area or rotational or linear:
refs_name = "rotational_speed_signal_refs" if rotational else "application_signal_refs" refs_name = "rotational_speed_signal_refs" if rotational else "application_signal_refs"
other = "application_signal_refs" if rotational else "rotational_speed_signal_refs" other = "application_signal_refs" if rotational else "rotational_speed_signal_refs"
if other in entry: if other in entry:
@@ -146,14 +150,19 @@ def load_material_calculation(
except ValueError as exc: except ValueError as exc:
raise CalculationConfigError("Invalid production_order_format") from exc raise CalculationConfigError("Invalid production_order_format") from exc
entry[refs_name] = tuple(refs) entry[refs_name] = tuple(refs)
if "fallback_nominal_width_m" in entry:
entry["fallback_nominal_width_m"] = finite_number(
entry["fallback_nominal_width_m"],
f"{prefix}.fallback_nominal_width_m", positive=True,
)
elif any(name in entry for name in ( elif any(name in entry for name in (
"application_signal_refs", "rotational_speed_signal_refs", "application_signal_refs", "rotational_speed_signal_refs",
"erp_workplace", "production_order_format", "erp_workplace", "production_order_format", "fallback_nominal_width_m",
)): )):
raise CalculationConfigError("Width context fields require a width-based source mode") raise CalculationConfigError("Width context fields require a width-based source mode")
if "calibration_ref" in entry: if "calibration_ref" in entry:
if not rotational: if not (rotational or linear):
raise CalculationConfigError("calibration_ref requires rotational_discharge") raise CalculationConfigError("calibration_ref requires a calibrated source mode")
if "specific_discharge_kg_per_rev_m" in entry: if "specific_discharge_kg_per_rev_m" in entry:
raise CalculationConfigError( raise CalculationConfigError(
"Specify calibration_ref or direct specific discharge, not both" "Specify calibration_ref or direct specific discharge, not both"
@@ -166,9 +175,23 @@ def load_material_calculation(
calibrations = load_calibrations(Path(path).parent / "material-calibrations.yaml") calibrations = load_calibrations(Path(path).parent / "material-calibrations.yaml")
calibration = resolve_calibration( calibration = resolve_calibration(
calibrations, entry["calibration_ref"], calibrations, entry["calibration_ref"],
expected_type="rotational_discharge", expected_unit="kg_per_rev_m", expected_type=mode,
expected_unit="kg_per_signal_unit_m" if linear else "kg_per_rev_m",
) )
entry["specific_discharge_kg_per_rev_m"] = calibration.value factor_name = ("specific_discharge_kg_per_signal_unit_m" if linear
else "specific_discharge_kg_per_rev_m")
if factor_name in entry:
raise CalculationConfigError("Specify calibration_ref only, not a direct factor")
entry[factor_name] = calibration.value
if linear:
if "calibration_ref" not in entry:
raise CalculationConfigError("linear_signal_discharge requires calibration_ref")
entry["specific_discharge_kg_per_signal_unit_m"] = finite_number(
entry["specific_discharge_kg_per_signal_unit_m"],
"specific_discharge_kg_per_signal_unit_m", positive=True,
)
elif "specific_discharge_kg_per_signal_unit_m" in entry:
raise CalculationConfigError("Signal discharge factor requires linear_signal_discharge")
if rotational: if rotational:
entry["specific_discharge_kg_per_rev_m"] = finite_number( entry["specific_discharge_kg_per_rev_m"] = finite_number(
entry.get("specific_discharge_kg_per_rev_m"), entry.get("specific_discharge_kg_per_rev_m"),
@@ -183,9 +206,10 @@ def load_material_calculation(
raise CalculationConfigError( raise CalculationConfigError(
"process application ID must be a distinct non-empty string" "process application ID must be a distinct non-empty string"
) )
if not rotational or not entry["gate_signal_ref"] or entry["gate_threshold"] <= 0: if (not (rotational or linear) or not entry["gate_signal_ref"]
or entry["gate_threshold"] <= 0):
raise CalculationConfigError( raise CalculationConfigError(
"Process application requires rotational_discharge and a positive speed gate" "Process application requires a calibrated source and a positive speed gate"
) )
if entry["id"] in instances: if entry["id"] in instances:
raise CalculationConfigError("Calculation ids must be unique") raise CalculationConfigError("Calculation ids must be unique")
@@ -0,0 +1,56 @@
"""Allocate measured fiber mass using order-specific ERP booking weights."""
from collections import defaultdict
from collections.abc import Iterable
from dataclasses import dataclass, replace
from math import fsum, isfinite
from production_analytics.calculations.shift_material import ShiftMaterialItem
@dataclass(frozen=True, slots=True)
class FiberBooking:
production_order: str
material_number: str | None
material_name: str | None
quantity_kg: float | None
def allocate_fiber_materials(
item: ShiftMaterialItem, bookings: Iterable[FiberBooking], *, erp_order: str
) -> tuple[ShiftMaterialItem, ...]:
"""ERP quantities are weights only; the supplied measured mass is authoritative."""
weights = defaultdict(list)
for booking in bookings:
quantity = booking.quantity_kg
number = (booking.material_number or "").strip()
if (
booking.production_order != erp_order
or not number
or quantity is None
or not isfinite(quantity)
or quantity <= 0
):
continue
name = (booking.material_name or "").strip() or None
weights[(number, name)].append(quantity)
totals = [
(number, name, fsum(values))
for (number, name), values in sorted(
weights.items(), key=lambda entry: (entry[0][0], entry[0][1] or "")
)
]
total = fsum(quantity for _, _, quantity in totals)
if total <= 0:
return (item,)
return tuple(
replace(
item,
consumption_kg=item.consumption_kg * (quantity / total),
material_number=number,
material_name=name,
material_mapping_status="ERP_BOOKING_ESTIMATE",
erp_booking_share=quantity / total,
)
for number, name, quantity in totals
)
@@ -1,4 +1,4 @@
"""Width-independent process application from actual rotational speeds.""" """Width-independent process application from calibrated source signals."""
from collections.abc import Iterable from collections.abc import Iterable
from math import isfinite from math import isfinite
@@ -23,3 +23,15 @@ def rotational_application_g_m2(
if not isfinite(value): if not isfinite(value):
raise ValueError("derived application must be finite") raise ValueError("derived application must be finite")
return value return value
def linear_signal_discharge_g_m2(
signal_values: Iterable[float], specific_discharge_kg_per_signal_unit_m: float,
line_speed_m_min: float, gate_threshold: float,
) -> float | None:
"""Derive speed-normalized application from calibrated signal discharge."""
return rotational_application_g_m2(
signal_values, specific_discharge_kg_per_signal_unit_m,
line_speed_m_min, gate_threshold,
)
@@ -138,3 +138,13 @@ def rotational_discharge_rate_kg_per_hour(
if not isfinite(rate): if not isfinite(rate):
raise ValueError("derived material rate must be finite") raise ValueError("derived material rate must be finite")
return rate return rate
def linear_signal_discharge_rate_kg_per_hour(
signal_values: Iterable[float], nominal_width_m: float,
specific_discharge_kg_per_signal_unit_m: float,
) -> float:
"""Convert calibrated signal discharge to kg/h, independently of line speed."""
return rotational_discharge_rate_kg_per_hour(
signal_values, nominal_width_m, specific_discharge_kg_per_signal_unit_m,
)
@@ -0,0 +1,183 @@
"""Machine-independent shift downtime from effective attribution 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
attributed_start: datetime | None = None
attributed_end: datetime | None = 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")
for name in ("attributed_start", "attributed_end"):
value = getattr(self, name)
if value is not None:
_aware(value, name)
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 effective 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.
Attribution timestamps take precedence, falling back to raw source timestamps.
"""
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
effective_start = event.attributed_start or event.source_start
effective_end = (
event.attributed_end if event.attributed_end is not None else event.source_end
)
event_start = effective_start.astimezone(UTC)
event_end = upper if effective_end is None else effective_end.astimezone(UTC)
if event_start >= upper or event_end <= lower:
continue
clipped_start = start if event_start < lower else effective_start
clipped_end = end if effective_end is None or event_end > upper else effective_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,377 @@
"""Shift counter deltas with bounded, matching-identity channel gap bridging."""
from collections import defaultdict
from collections.abc import Iterable
from dataclasses import dataclass, replace
from datetime import UTC, datetime, timedelta
from math import fsum, isfinite
MATERIAL_IDENTITY_GAP_LIMIT = timedelta(minutes=10)
@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
erp_booking_share: float | 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.
Each delta belongs to the ending sample's order, consolidated by run/order.
"""
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):
_check_deltas(run, channel=False)
missing = _instant(run[0].timestamp) > _instant(start)
segment_items = []
for previous, current in list(zip(run, run[1:])) or [(run[0], run[0])]:
segment_items.append(
ShiftMaterialItem(
source="material_consumption_snapshots",
calculation_id=current.calculation_id,
machine_id=machine_id,
production_order=current.production_order,
run_id=current.run_id,
consumption_kg=current.consumption_kg - previous.consumption_kg,
baseline_timestamp=previous.timestamp,
end_timestamp=current.timestamp,
baseline_missing=missing,
)
)
items.extend(_consolidate_items(segment_items))
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.
After differencing, bridge unknown intervals only between identical known
identities at most ten minutes apart in the same stream/run/order. Consolidate
by final identity afterwards. 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
segments.append(
_ChannelSegment(
identity, previous, current, [delta], current.percentage_sum_valid
)
)
_bridge_channel_identity_gaps(segments)
segment_items = []
for segment in segments:
number, name, status = segment.identity
first, last = segment.first, segment.last
segment_items.append(
ShiftMaterialItem(
source="channel_material_consumption_snapshots",
calculation_id=first.calculation_id,
machine_id=machine_id,
production_order=last.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,
)
)
items.extend(_consolidate_items(segment_items))
return _summary(items, machine_id, start, end, include_zero)
def _bridge_channel_identity_gaps(intervals: list[_ChannelSegment]) -> None:
"""Reassign already-differenced unknown intervals inside a bounded A/unknown/A gap.
The full enclosing sample span is used, including the return-to-known interval,
so sparse sampling cannot turn a long outage into an apparently short gap.
Enclosing samples must share an order within this physical stream/run.
"""
index = 0
while index < len(intervals):
if intervals[index].identity[:2] != (None, None):
index += 1
continue
first = index
while index < len(intervals) and intervals[index].identity[:2] == (None, None):
index += 1
if index == len(intervals):
continue # No known identity after the gap.
before = _identity(intervals[first].first)
after = intervals[index].identity
duration = _instant(intervals[index].last.timestamp) - _instant(
intervals[first].first.timestamp
)
if (
before[:2] != (None, None)
and before == after
and all(
interval.first.production_order == intervals[first].first.production_order
and interval.last.production_order == intervals[first].first.production_order
for interval in intervals[first:index + 1]
)
and duration <= MATERIAL_IDENTITY_GAP_LIMIT
):
for interval in intervals[first:index]:
interval.identity = before
def _consolidate_items(items: list[ShiftMaterialItem]) -> list[ShiftMaterialItem]:
groups = defaultdict(list)
for item in items:
key = (
item.calculation_id,
item.machine_id,
item.production_order,
item.run_id,
item.extruder,
item.doser_channel,
item.material_number,
item.material_name,
item.material_mapping_status,
)
groups[key].append(item)
consolidated = []
# Explicit identity ordering also resolves any ties in the summary's time ordering.
for key in sorted(
groups, key=lambda key: tuple((part is not None, part or "") for part in key)
):
contributions = groups[key]
consolidated.append(
replace(
contributions[0],
consumption_kg=fsum(item.consumption_kg for item in contributions),
baseline_timestamp=min(
(item.baseline_timestamp for item in contributions), key=_instant
),
end_timestamp=max((item.end_timestamp for item in contributions), key=_instant),
percentage_sum_valid=(
None if contributions[0].percentage_sum_valid is None
else all(item.percentage_sum_valid for item in contributions)
),
)
)
return consolidated
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 = []
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:
runs.append([])
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,126 @@
"""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
average_speed_m_min: float | None = None
material_consumption_kg: float | None = None
@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,120 @@
"""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
@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 | None
start: datetime
end: datetime
production: ShiftProductionSummary | None
downtime: ShiftDowntimeSummary | None
materials: ShiftMaterialSummary | None
speed: ShiftSpeedSummary | None
timezone: ZoneInfo
display_name: str | None = None
site: str | None = None
@property
def downtime_event_count(self) -> int:
return len(self.downtime.events) if self.downtime is not None else 0
@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 if self.downtime is not None else ())
)
@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"], timezone: ZoneInfo,
) -> tuple[datetime, datetime]:
"""Site-local 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")
if not isinstance(timezone, ZoneInfo):
raise ValueError("timezone must be a ZoneInfo")
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=timezone),
datetime.combine(end_day, time(end_hour), tzinfo=timezone),
)
def shift_containing(
timestamp: datetime, timezone: ZoneInfo,
) -> tuple[date, Literal["early", "late", "night"], datetime, datetime]:
"""Return the site-local shift containing one confirmation instant."""
if (not isinstance(timestamp, datetime) or timestamp.tzinfo is None
or timestamp.utcoffset() is None):
raise ValueError("timestamp must be timezone-aware")
if not isinstance(timezone, ZoneInfo):
raise ValueError("timezone must be a ZoneInfo")
local = timestamp.astimezone(timezone)
if local.hour < 6:
day, shift = local.date() - timedelta(days=1), "night"
elif local.hour < 14:
day, shift = local.date(), "early"
elif local.hour < 22:
day, shift = local.date(), "late"
else:
day, shift = local.date(), "night"
start, end = shift_report_window(day, shift, timezone)
return day, shift, start, end
def most_recent_completed_shift(
now: datetime, timezone: ZoneInfo,
) -> tuple[date, Literal["early", "late", "night"]]:
"""Return start date and name of the last completed site-local shift."""
if now.tzinfo is None or now.utcoffset() is None:
raise ValueError("now must include a timezone")
if not isinstance(timezone, ZoneInfo):
raise ValueError("timezone must be a ZoneInfo")
local = now.astimezone(timezone)
day = local.date()
if local.hour < 6:
return day - timedelta(days=1), "late"
if local.hour < 14:
return day - timedelta(days=1), "night"
if local.hour < 22:
return day, "early"
return day, "late"
@@ -0,0 +1,220 @@
"""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 NumericDwellGate:
signal_ref: str
threshold: float
comparison: str
minimum_duration_seconds: int
def __post_init__(self) -> None:
if (not isinstance(self.signal_ref, str) or not self.signal_ref.strip()
or "\x00" in self.signal_ref):
raise ValueError("numeric_dwell_gate.signal_ref must be a non-empty string")
if finite_speed(self.threshold) is None:
raise ValueError("numeric_dwell_gate.threshold must be finite")
if self.comparison not in ("below", "above"):
raise ValueError("numeric_dwell_gate.comparison must be below or above")
if (type(self.minimum_duration_seconds) is not int
or self.minimum_duration_seconds <= 0):
raise ValueError("numeric_dwell_gate.minimum_duration_seconds must be positive")
@dataclass(frozen=True, slots=True)
class ShiftSpeedConfig:
machine_id: str
speed_signal_ref: str
production_gate_m_min: float | None = None
unit: str = "m/min"
signal: str = ""
running_signal_ref: str | None = None
running_when: bool = True
numeric_dwell_gate: NumericDwellGate | None = None
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")
if self.running_signal_ref is not None:
value = self.running_signal_ref
if not isinstance(value, str) or not value.strip() or "\x00" in value:
raise ValueError("running_signal_ref must be a non-empty string without NUL bytes")
if value == self.speed_signal_ref:
raise ValueError("running_signal_ref must differ from speed_signal_ref")
if type(self.running_when) is not bool:
raise ValueError("running_when must be a boolean")
if self.running_signal_ref is None and self.running_when is not True:
raise ValueError("running_when requires running_signal_ref")
if self.numeric_dwell_gate is not None:
if not isinstance(self.numeric_dwell_gate, NumericDwellGate):
raise ValueError("numeric_dwell_gate must be a NumericDwellGate")
if self.numeric_dwell_gate.signal_ref == self.speed_signal_ref:
raise ValueError("numeric dwell signal must differ from speed signal")
if self.running_signal_ref is not None:
raise ValueError("Boolean and numeric dwell gates are mutually exclusive")
gate = finite_speed(self.production_gate_m_min)
if (self.production_gate_m_min is not None and (gate is None or gate < 0)) or (
self.running_signal_ref is None and self.numeric_dwell_gate is None and gate is None
):
raise ValueError("production_gate_m_min must be finite and non-negative")
if self.numeric_dwell_gate is not None and self.production_gate_m_min is not None:
raise ValueError("numeric dwell gate cannot use production_gate_m_min")
if self.running_signal_ref is not None and self.production_gate_m_min is not None:
raise ValueError("Boolean gate cannot use production_gate_m_min")
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
running: object = None
gate_value: object = None
@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 | None
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; select activity by configured 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)
samples = list(samples)
dwell_states = _dwell_states(samples, config.numeric_dwell_gate) if (
config.numeric_dwell_gate is not None) else {}
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
if config.running_signal_ref is not None and type(sample.running) is not bool:
invalid += 1
continue
if config.numeric_dwell_gate is not None and dwell_states.get(id(sample)) is None:
invalid += 1
continue
count += 1
if config.numeric_dwell_gate is not None:
is_active = dwell_states[id(sample)]
elif config.running_signal_ref is not None:
is_active = sample.running is config.running_when
else:
is_active = value > config.production_gate_m_min
if is_active:
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 _dwell_states(
samples: list[ShiftSpeedSample], gate: NumericDwellGate,
) -> dict[int, bool | None]:
"""Classify each row from timestamped gate runs; None means unknown."""
ordered = []
for sample in samples:
try:
stamp = _instant(sample.timestamp)
except ValueError:
continue
number = finite_speed(sample.gate_value)
below = (number < gate.threshold if gate.comparison == "below"
else number > gate.threshold) if number is not None else None
ordered.append((stamp, sample, below))
ordered.sort(key=lambda item: item[0])
states: dict[int, bool | None] = {}
cursor = 0
while cursor < len(ordered):
stamp, sample, condition = ordered[cursor]
if condition is not True:
states[id(sample)] = True if condition is False else None
cursor += 1
continue
run_start = cursor
while cursor < len(ordered) and ordered[cursor][2] is True:
cursor += 1
last_below = ordered[cursor - 1][0]
closed = cursor < len(ordered) and ordered[cursor][2] is False
finish = ordered[cursor][0] if closed else last_below
duration = (finish - stamp).total_seconds()
if duration >= gate.minimum_duration_seconds:
state = False
elif closed and run_start > 0 and ordered[run_start - 1][2] is False:
state = True
else:
state = None
for _, member, _ in ordered[run_start:cursor]:
states[id(member)] = state
return states
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)
+74 -3
View File
@@ -104,6 +104,18 @@ def _parser() -> argparse.ArgumentParser:
default=Path("secrets/enlyze.env"), default=Path("secrets/enlyze.env"),
help="Local dotenv-style secret file (default: secrets/enlyze.env)", help="Local dotenv-style secret file (default: secrets/enlyze.env)",
) )
historical = namespaces.add_parser("historical-reconcile", help="Repair historical attribution")
historical.add_argument("--lookback-days", type=int, default=3)
historical.add_argument("--dry-run", action="store_true")
historical.add_argument("--verbose", action="store_true",
help="Show individual record diagnostics as well as summaries")
historical.add_argument("--config", type=Path,
default=Path("config/shift-report-machines.yaml"))
historical.add_argument("--order-formats", type=Path,
default=Path("config/historical-order-formats.yaml"))
historical.add_argument("--secrets-file", type=Path, default=Path("secrets/enlyze.env"))
historical.add_argument("--erp-secrets-file", type=Path, default=Path("secrets/erp.env"))
historical.add_argument("--db-secrets-file", type=Path, default=Path("secrets/postgres.env"))
run = namespaces.add_parser("run", help="Foreground production runners") run = namespaces.add_parser("run", help="Foreground production runners")
runners = run.add_subparsers(dest="command", required=True) runners = run.add_subparsers(dest="command", required=True)
material = runners.add_parser("material-poll", help="Continuously poll material consumption") material = runners.add_parser("material-poll", help="Continuously poll material consumption")
@@ -113,7 +125,9 @@ def _parser() -> argparse.ArgumentParser:
material.add_argument("--state-directory", type=Path, default=Path("data/state/material")) material.add_argument("--state-directory", type=Path, default=Path("data/state/material"))
material.add_argument("--secrets-file", type=Path, default=Path("secrets/enlyze.env")) material.add_argument("--secrets-file", type=Path, default=Path("secrets/enlyze.env"))
material.add_argument("--erp-secrets-file", type=Path, default=Path("secrets/erp.env")) material.add_argument("--erp-secrets-file", type=Path, default=Path("secrets/erp.env"))
power = runners.add_parser("power-meter", help="Collect configured ENLYZE power-meter telemetry") power = runners.add_parser(
"power-meter", help="Collect configured ENLYZE power-meter telemetry",
)
power.add_argument("--config", type=Path, required=True) power.add_argument("--config", type=Path, required=True)
power.add_argument("--meter") power.add_argument("--meter")
power.add_argument("--start", help="ISO timestamp; defaults to one polling window ago") power.add_argument("--start", help="ISO timestamp; defaults to one polling window ago")
@@ -129,6 +143,16 @@ def _parser() -> argparse.ArgumentParser:
monthly.add_argument("--month", required=True, help="YYYY-MM") monthly.add_argument("--month", required=True, help="YYYY-MM")
monthly.add_argument("--db-secrets-file", type=Path, default=Path("secrets/postgres.env")) monthly.add_argument("--db-secrets-file", type=Path, default=Path("secrets/postgres.env"))
shift = report_commands.add_parser("shift", help="Render one explicit shift report PDF")
shift.add_argument("--config", type=Path, default=Path("config/shift-report-machines.yaml"))
shift.add_argument("--machine", required=True)
shift.add_argument("--start", required=True, help="ISO 8601 datetime with timezone")
shift.add_argument("--end", required=True, help="ISO 8601 datetime with timezone")
shift.add_argument("--output", type=Path, required=True)
shift.add_argument("--secrets-file", type=Path, default=Path("secrets/enlyze.env"))
shift.add_argument("--erp-secrets-file", type=Path, default=Path("secrets/erp.env"))
shift.add_argument("--db-secrets-file", type=Path, default=Path("secrets/postgres.env"))
channel_material = runners.add_parser( channel_material = runners.add_parser(
"channel-material-poll", help="Continuously poll channel-level material consumption" "channel-material-poll", help="Continuously poll channel-level material consumption"
) )
@@ -258,8 +282,10 @@ def _parse_cli_timestamp(value: str) -> object:
def _run_power_meter(args: argparse.Namespace) -> int: def _run_power_meter(args: argparse.Namespace) -> int:
from datetime import UTC, datetime, timedelta
import time import time
from datetime import UTC, datetime, timedelta
from production_analytics.calculations.config import CalculationConfigError
from production_analytics.enlyze.exploration import ConfigurationError from production_analytics.enlyze.exploration import ConfigurationError
from production_analytics.power_meter.config import load_power_meter_config from production_analytics.power_meter.config import load_power_meter_config
from production_analytics.power_meter.gateway import PowerMeterGateway from production_analytics.power_meter.gateway import PowerMeterGateway
@@ -291,6 +317,7 @@ def _run_power_meter(args: argparse.Namespace) -> int:
def _run_monthly_report(args: argparse.Namespace) -> int: def _run_monthly_report(args: argparse.Namespace) -> int:
from production_analytics.calculations.config import CalculationConfigError
from production_analytics.enlyze.exploration import ConfigurationError from production_analytics.enlyze.exploration import ConfigurationError
from production_analytics.power_meter.config import load_power_meter_config from production_analytics.power_meter.config import load_power_meter_config
from production_analytics.power_meter.repository import PostgresPowerMeterRepository from production_analytics.power_meter.repository import PostgresPowerMeterRepository
@@ -299,7 +326,8 @@ def _run_monthly_report(args: argparse.Namespace) -> int:
config = load_power_meter_config(args.config, args.meter) config = load_power_meter_config(args.config, args.meter)
environment = _runtime_environment(args.db_secrets_file) environment = _runtime_environment(args.db_secrets_file)
from production_analytics.service.postgres_material import PostgresSettings from production_analytics.service.postgres_material import PostgresSettings
path = monthly_report(config, PostgresPowerMeterRepository(PostgresSettings.from_environment(environment)), args.month) repository = PostgresPowerMeterRepository(PostgresSettings.from_environment(environment))
path = monthly_report(config, repository, args.month)
print(path) print(path)
return 0 return 0
except (CalculationConfigError, ConfigurationError, ValueError, RuntimeError) as exc: except (CalculationConfigError, ConfigurationError, ValueError, RuntimeError) as exc:
@@ -307,6 +335,36 @@ def _run_monthly_report(args: argparse.Namespace) -> int:
return 2 return 2
def _run_shift_report(args: argparse.Namespace) -> int:
from production_analytics.calculations.shift_speed import validate_speed_window
from production_analytics.enlyze.exploration import ConfigurationError
from production_analytics.presentation.shift_report import write_pdf
from production_analytics.service.shift_report_config import load_shift_report_machines
from production_analytics.service.shift_report_runtime import build_shift_report_service
try:
start = _parse_cli_timestamp(args.start)
end = _parse_cli_timestamp(args.end)
validate_speed_window(start, end)
machines = load_shift_report_machines(args.config)
if args.machine not in machines:
raise ValueError(f"Unknown shift-report machine: {args.machine}")
environment = _runtime_environment(
args.secrets_file, args.erp_secrets_file, args.db_secrets_file,
)
service = build_shift_report_service(machines, environment)
report = service.build(machine_name=args.machine, start=start, end=end)
write_pdf(report, args.output)
except (ValueError, ConfigurationError, ExplorationError) as exc:
print(f"Report error: {exc}", file=sys.stderr)
return 2
except Exception as exc:
print(f"Report failed: {type(exc).__name__}", file=sys.stderr)
return 1
print(args.output)
return 0
def _run_downtime(args: argparse.Namespace) -> int: def _run_downtime(args: argparse.Namespace) -> int:
from production_analytics.service.downtime_runtime import build_downtime_runner from production_analytics.service.downtime_runtime import build_downtime_runner
@@ -324,6 +382,17 @@ def _run_downtime(args: argparse.Namespace) -> int:
def main(argv: Sequence[str] | None = None) -> int: def main(argv: Sequence[str] | None = None) -> int:
args = _parser().parse_args(argv) args = _parser().parse_args(argv)
if args.namespace == "historical-reconcile":
from production_analytics.service.historical_runtime import run
try:
return run(args, _runtime_environment(
args.secrets_file, args.erp_secrets_file, args.db_secrets_file,
))
except Exception as exc:
print(f"Historical reconciliation failed: {type(exc).__name__}: {exc}",
file=sys.stderr)
return 1
if args.namespace == "run": if args.namespace == "run":
if args.command == "channel-material-poll": if args.command == "channel-material-poll":
return _run_channel_material(args) return _run_channel_material(args)
@@ -335,6 +404,8 @@ def main(argv: Sequence[str] | None = None) -> int:
return _run_downtime(args) return _run_downtime(args)
return _run_material(args) return _run_material(args)
if args.namespace == "report": if args.namespace == "report":
if args.command == "shift":
return _run_shift_report(args)
return _run_monthly_report(args) return _run_monthly_report(args)
if args.namespace != "enlyze" or args.command not in {"raw", "timeseries"}: if args.namespace != "enlyze" or args.command not in {"raw", "timeseries"}:
return 2 return 2
+154 -12
View File
@@ -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,91 @@ 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,
running_signal_ref: str | None = None,
numeric_gate_signal_ref: str | None = None,
) -> list[ShiftSpeedSample]:
"""Retrieve bounded speed and optional status in one timeseries request.
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")
if running_signal_ref is not None and numeric_gate_signal_ref is not None:
raise ValueError("Speed activity gates are mutually exclusive")
for name, signal_ref in (("running_signal_ref", running_signal_ref),
("numeric_gate_signal_ref", numeric_gate_signal_ref)):
if signal_ref is not None and (
not isinstance(signal_ref, str) or not signal_ref.strip()
or "\x00" in signal_ref or signal_ref == speed_signal_ref
):
raise ValueError(f"{name} must be a distinct non-empty string")
variables = [{"uuid": speed_signal_ref}]
if running_signal_ref is not None:
variables.append({"uuid": running_signal_ref})
if numeric_gate_signal_ref is not None:
variables.append({"uuid": numeric_gate_signal_ref})
body = {
"machine": machine_id,
"start": start.astimezone(UTC).isoformat(),
"end": end.astimezone(UTC).isoformat(),
"variables": variables,
}
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"]
required = ["time", speed_signal_ref]
if running_signal_ref is not None:
required.append(running_signal_ref)
if numeric_gate_signal_ref is not None:
required.append(numeric_gate_signal_ref)
if not isinstance(columns, list) or any(
columns.count(column) != 1 for column in required
):
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)
running_index = columns.index(running_signal_ref) if running_signal_ref else None
numeric_index = (columns.index(numeric_gate_signal_ref)
if numeric_gate_signal_ref else None)
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],
record[running_index] if running_index is not None else None,
record[numeric_index] if numeric_index is not None else None,
))
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,
*, *,
@@ -165,6 +252,7 @@ class EnlyzeApiGateway:
rotational_speed_variable_ids: tuple[str, ...] = (), rotational_speed_variable_ids: tuple[str, ...] = (),
specific_discharge_kg_per_rev_m: float | None = None, specific_discharge_kg_per_rev_m: float | None = None,
process_application_gate_threshold: float | None = None, process_application_gate_threshold: float | None = None,
specific_discharge_kg_per_signal_unit_m: float | None = None,
) -> list[MaterialSample]: ) -> list[MaterialSample]:
for name, value in (("start", start), ("end", end)): for name, value in (("start", start), ("end", end)):
if value.tzinfo is None or value.utcoffset() is None: if value.tzinfo is None or value.utcoffset() is None:
@@ -175,6 +263,8 @@ class EnlyzeApiGateway:
raise ValueError("Material source modes are mutually exclusive") raise ValueError("Material source modes are mutually exclusive")
if gate_variable_id is None and not rotational_speed_variable_ids: if gate_variable_id is None and not rotational_speed_variable_ids:
raise ValueError("This source requires a gate signal") raise ValueError("This source requires a gate signal")
if specific_discharge_kg_per_signal_unit_m is not None and not application_variable_ids:
raise ValueError("Signal discharge requires source signals")
source_ids = ( source_ids = (
rotational_speed_variable_ids or application_variable_ids or (rate_variable_id,) rotational_speed_variable_ids or application_variable_ids or (rate_variable_id,)
) )
@@ -223,6 +313,16 @@ class EnlyzeApiGateway:
nominal_width_m, nominal_width_m,
specific_discharge_kg_per_rev_m, specific_discharge_kg_per_rev_m,
) )
elif specific_discharge_kg_per_signal_unit_m is not None:
from production_analytics.calculations.material_consumption import (
linear_signal_discharge_rate_kg_per_hour,
)
if nominal_width_m is None:
raise ValueError("signal discharge requires nominal width")
rate = linear_signal_discharge_rate_kg_per_hour(
sources, nominal_width_m, specific_discharge_kg_per_signal_unit_m,
)
elif application_variable_ids: elif application_variable_ids:
if nominal_width_m is None: if nominal_width_m is None:
raise ValueError("area application requires nominal width") raise ValueError("area application requires nominal width")
@@ -231,12 +331,24 @@ class EnlyzeApiGateway:
rate = sources[0] rate = sources[0]
application = None application = None
if process_application_gate_threshold is not None: if process_application_gate_threshold is not None:
if not rotational_speed_variable_ids or gate_variable_id is None: if specific_discharge_kg_per_signal_unit_m is not None:
raise ValueError("Process application requires rpm and speed gate") from production_analytics.calculations.material_application import (
linear_signal_discharge_g_m2,
)
application = linear_signal_discharge_g_m2(
sources, specific_discharge_kg_per_signal_unit_m,
gate, process_application_gate_threshold,
)
elif not rotational_speed_variable_ids or gate_variable_id is None:
raise ValueError(
"Process application requires discharge and speed gate"
)
from production_analytics.calculations.material_application import ( from production_analytics.calculations.material_application import (
rotational_application_g_m2, rotational_application_g_m2,
) )
if rotational_speed_variable_ids:
application = rotational_application_g_m2( application = rotational_application_g_m2(
sources, sources,
specific_discharge_kg_per_rev_m, specific_discharge_kg_per_rev_m,
@@ -283,8 +395,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
@@ -330,9 +442,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)
@@ -351,10 +471,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,
@@ -369,7 +490,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
@@ -382,6 +513,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)]
@@ -413,6 +545,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),
@@ -420,9 +555,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()
@@ -436,6 +574,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")
+13 -2
View File
@@ -1,10 +1,21 @@
"""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,
ErpFiberBookingGateway,
ErpProductionConfirmationGateway,
ErpReadError, ErpReadError,
ErpSettings, ErpSettings,
ErpWorkplaceStatusGateway, ErpWorkplaceStatusGateway,
ProductionConfirmation,
) )
__all__ = ["CurrentWorkplaceStatus", "ErpReadError", "ErpSettings", "ErpWorkplaceStatusGateway"] __all__ = [
"CurrentWorkplaceStatus",
"ErpFiberBookingGateway",
"ErpProductionConfirmationGateway",
"ErpReadError",
"ErpSettings",
"ErpWorkplaceStatusGateway",
"ProductionConfirmation",
]
+298 -14
View File
@@ -1,14 +1,16 @@
"""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
from production_analytics.calculations.fiber_allocation import FiberBooking
from production_analytics.enlyze.exploration import ConfigurationError, load_secret_file from production_analytics.enlyze.exploration import ConfigurationError, load_secret_file
@@ -22,7 +24,10 @@ class ErpSettings:
def __post_init__(self) -> None: def __post_init__(self) -> None:
for attribute, suffix in ( for attribute, suffix in (
("host", "HOST"), ("database", "NAME"), ("user", "USER"), ("password", "PASSWORD"), ("host", "HOST"),
("database", "NAME"),
("user", "USER"),
("password", "PASSWORD"),
): ):
value = getattr(self, attribute) value = getattr(self, attribute)
if not isinstance(value, str) or not value.strip() or "\x00" in value: if not isinstance(value, str) or not value.strip() or "\x00" in value:
@@ -40,7 +45,8 @@ class ErpSettings:
except ValueError: except ValueError:
raise ConfigurationError("ERP_DB_PORT must be an integer from 1 to 65535") from None raise ConfigurationError("ERP_DB_PORT must be an integer from 1 to 65535") from None
return cls( return cls(
host=environment.get("ERP_DB_HOST", ""), port=port, host=environment.get("ERP_DB_HOST", ""),
port=port,
database=environment.get("ERP_DB_NAME", ""), database=environment.get("ERP_DB_NAME", ""),
user=environment.get("ERP_DB_USER", ""), user=environment.get("ERP_DB_USER", ""),
password=environment.get("ERP_DB_PASSWORD", ""), password=environment.get("ERP_DB_PASSWORD", ""),
@@ -48,8 +54,10 @@ class ErpSettings:
@classmethod @classmethod
def from_secret_file( def from_secret_file(
cls, path: str | os.PathLike[str] = "secrets/erp.env", cls,
*, environment: Mapping[str, str] | None = None, path: str | os.PathLike[str] = "secrets/erp.env",
*,
environment: Mapping[str, str] | None = None,
) -> "ErpSettings": ) -> "ErpSettings":
"""Load dotenv values over the environment, following the existing convention.""" """Load dotenv values over the environment, following the existing convention."""
try: try:
@@ -62,7 +70,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
@@ -97,9 +105,13 @@ class ErpWorkplaceStatusGateway:
raise ValueError("workplace must be a non-empty string without NUL bytes") raise ValueError("workplace must be a non-empty string without NUL bytes")
try: try:
with pymssql.connect( with pymssql.connect(
server=self._settings.host, port=self._settings.port, server=self._settings.host,
database=self._settings.database, user=self._settings.user, port=self._settings.port,
password=self._settings.password, login_timeout=10, timeout=10, database=self._settings.database,
user=self._settings.user,
password=self._settings.password,
login_timeout=10,
timeout=10,
) as connection: ) as connection:
with connection.cursor() as cursor: with connection.cursor() as cursor:
cursor.execute(_CURRENT_STATUS_SQL, (workplace,)) cursor.execute(_CURRENT_STATUS_SQL, (workplace,))
@@ -117,12 +129,17 @@ class ErpWorkplaceStatusGateway:
if len(row) != 10 or not isinstance(row[4], datetime): if len(row) != 10 or not isinstance(row[4], datetime):
raise ValueError raise ValueError
return CurrentWorkplaceStatus( return CurrentWorkplaceStatus(
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=(
order_quantity_m2=_number(row[5]), good_quantity_m2=_number(row[6]), row[4].replace(tzinfo=_PLANT_TIMEZONE) if row[4].utcoffset() is None else row[4]
remaining_quantity_m2=_number(row[7]), remaining_time_hours=_number(row[8]), ),
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_rolls=_number(row[9]), remaining_rolls=_number(row[9]),
) )
except Exception: except Exception:
@@ -146,3 +163,270 @@ 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,
timezone: ZoneInfo | None = None,
) -> list[ProductionConfirmation]:
timezone = _PLANT_TIMEZONE if timezone is None else timezone
if not isinstance(timezone, ZoneInfo):
raise ValueError("timezone must be a ZoneInfo")
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(timezone).replace(tzinfo=None)
local_end = end.astimezone(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, timezone) for row in rows]
except Exception:
raise ErpReadError("ERP production confirmation returned an invalid row") from None
def search_orders(self, query: str, *, limit: int = 25) -> list["OrderConfirmationGroup"]:
query = _order_query(query)
if type(limit) is not int or not 1 <= limit <= 100:
raise ValueError("limit must be between 1 and 100")
pattern = "%" + query.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%"
rows = self._read_orders(_ORDER_SEARCH_SQL, (limit, pattern, query, query))
try:
return [_order_group(row) for row in rows]
except Exception:
raise ErpReadError("ERP production-order search returned an invalid row") from None
def get_order_confirmations(self, production_order: str) -> list["OrderConfirmationRow"]:
order = _order_query(production_order)
rows = self._read_orders(_ORDER_DETAIL_SQL, (order,))
try:
return [_order_confirmation(row) for row in rows]
except Exception:
raise ErpReadError("ERP production-order detail returned an invalid row") from None
def _read_orders(self, sql: str, parameters: tuple) -> list[tuple]:
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(sql, parameters)
return cursor.fetchall()
except Exception:
raise ErpReadError("ERP production-order read failed") from None
@dataclass(frozen=True, slots=True)
class OrderConfirmationGroup:
production_order: str
workplace: str
article_number: str | None
article_description: str | None
first_confirmation_local: datetime
last_confirmation_local: datetime
@dataclass(frozen=True, slots=True)
class OrderConfirmationRow:
production_order: str
workplace: str
article_number: str | None
article_description: str | None
timestamp_local: datetime
feedback_quantity_m2: float
_ORDER_SEARCH_SQL = """WITH matching_orders AS (
SELECT TOP (%s) [Fertigungsauftragsnummer]
FROM [dbo].[GRAFANA_PRODUCTION_CONFIRMATION]
WHERE [Fertigungsauftragsnummer] LIKE %s ESCAPE '\\' AND [Rückmeldemenge] > 0
GROUP BY [Fertigungsauftragsnummer]
ORDER BY CASE WHEN [Fertigungsauftragsnummer] = %s THEN 0 ELSE 1 END,
[Fertigungsauftragsnummer]
)
SELECT c.[Fertigungsauftragsnummer], c.[Arbeitsplatz], c.[Artikelnummer],
c.[Artikelbezeichnung], MIN(c.[Zeitstempel]), MAX(c.[Zeitstempel])
FROM [dbo].[GRAFANA_PRODUCTION_CONFIRMATION] AS c
JOIN matching_orders AS m ON m.[Fertigungsauftragsnummer] = c.[Fertigungsauftragsnummer]
WHERE c.[Rückmeldemenge] > 0
GROUP BY c.[Fertigungsauftragsnummer], c.[Arbeitsplatz], c.[Artikelnummer],
c.[Artikelbezeichnung]
ORDER BY CASE WHEN c.[Fertigungsauftragsnummer] = %s THEN 0 ELSE 1 END,
c.[Fertigungsauftragsnummer], c.[Arbeitsplatz], c.[Artikelnummer], c.[Artikelbezeichnung]"""
_ORDER_DETAIL_SQL = """SELECT [Fertigungsauftragsnummer], [Arbeitsplatz], [Artikelnummer],
[Artikelbezeichnung], [Zeitstempel], [Rückmeldemenge]
FROM [dbo].[GRAFANA_PRODUCTION_CONFIRMATION]
WHERE [Fertigungsauftragsnummer] = %s AND [Rückmeldemenge] > 0
ORDER BY [Zeitstempel], [Arbeitsplatz], [Artikelnummer], [Artikelbezeichnung],
[Rückmeldemenge]"""
def _order_query(value: str) -> str:
if (not isinstance(value, str) or not value.strip() or "\x00" in value
or len(value.strip()) > 80):
raise ValueError("production order query must be 1–80 non-NUL characters")
return value.strip()
def _order_group(row: tuple) -> OrderConfirmationGroup:
if len(row) != 6 or any(not isinstance(row[index], datetime)
or row[index].tzinfo is not None for index in (4, 5)):
raise ValueError
return OrderConfirmationGroup(_text(row[0]), _text(row[1]),
_text(row[2], nullable=True), _text(row[3], nullable=True),
row[4], row[5])
def _order_confirmation(row: tuple) -> OrderConfirmationRow:
if len(row) != 6 or not isinstance(row[4], datetime) or row[4].tzinfo is not None:
raise ValueError
quantity = _number(row[5])
if quantity is None or quantity <= 0:
raise ValueError
return OrderConfirmationRow(_text(row[0]), _text(row[1]),
_text(row[2], nullable=True), _text(row[3], nullable=True),
row[4], quantity)
def _production_confirmation(row: tuple[object, ...], timezone: ZoneInfo) -> 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=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),
)
_FIBER_BOOKING_SQL = """SELECT [Fertigungsauftragsnummer], [Rohstoffnummer],
[Rohstoffbezeichnung], [Fasermenge]
FROM [dbo].[GRAFANA_PRODUCTION_CONFIRMATION]
WHERE [Fertigungsauftragsnummer] = %s AND [Fasermenge] > 0
AND NULLIF(LTRIM(RTRIM([Rohstoffnummer])), '') IS NOT NULL
ORDER BY [Rohstoffnummer], [Rohstoffbezeichnung], [Fasermenge]"""
class ErpFiberBookingGateway:
"""Order-wide positive raw-material bookings; never a measured shift quantity."""
def __init__(self, settings: ErpSettings) -> None:
self._settings = settings
def get_fiber_bookings(self, production_order: str) -> list[FiberBooking]:
if (
not isinstance(production_order, str)
or not production_order.strip()
or "\x00" in production_order
):
raise ValueError("production_order must be a non-empty string without NUL bytes")
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(_FIBER_BOOKING_SQL, (production_order.strip(),))
rows = cursor.fetchall()
except Exception:
raise ErpReadError("ERP fiber booking read failed") from None
try:
return [
FiberBooking(
_text(row[0]),
_text(row[1], nullable=True),
_text(row[2], nullable=True),
_number(row[3]),
)
for row in rows
]
except Exception:
raise ErpReadError("ERP fiber booking returned an invalid row") from None
@@ -0,0 +1 @@
"""Output presenters independent of report composition and source access."""
@@ -0,0 +1,29 @@
"""Shared, server-rendered navigation between the two web workflows."""
from typing import Literal
Mode = Literal["shift", "order"]
MODE_NAV_CSS = """
.mode-nav{display:inline-flex;gap:.25rem;padding:.25rem;margin-bottom:1rem;
background:#e8eef3;border:1px solid #aab9c5;border-radius:.55rem}
.mode-nav a{display:block;padding:.55rem .85rem;border:1px solid transparent;
border-radius:.35rem;color:#182c3b;font-weight:600;text-decoration:none}
.mode-nav a:hover{background:#d4e0e9}
.mode-nav a[aria-current="page"]{background:#294d67;border-color:#294d67;color:white}
.mode-nav a[aria-current="page"]:hover{background:#294d67}
.mode-nav a:focus-visible{outline:3px solid #bf6525;outline-offset:2px}
"""
def render_mode_navigation(active: Mode) -> str:
if active not in ("shift", "order"):
raise ValueError("Unknown web workflow")
links = (("shift", "/", "Schichtbericht"),
("order", "/orders", "Fertigungsauftrag"))
items = "".join(
f'<a href="{href}"' + (' aria-current="page"' if mode == active else "")
+ f">{label}</a>"
for mode, href, label in links
)
return f'<nav class="mode-nav" aria-label="Bereich wählen">{items}</nav>'
@@ -0,0 +1,125 @@
"""Server-rendered, escaped production-order search and detail pages."""
from html import escape
from urllib.parse import urlencode
from production_analytics.presentation.mode_navigation import (
MODE_NAV_CSS,
render_mode_navigation,
)
from production_analytics.presentation.shift_report import _number
from production_analytics.service.production_order import (
ProductionOrderDetail,
ProductionOrderSearchResult,
)
SHIFT_LABELS = {"early": "Frühschicht", "late": "Spätschicht", "night": "Nachtschicht"}
def _page(title: str, body: str) -> str:
return f'''<!doctype html><html lang="de"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{escape(title)}</title><style>
body {{font:16px system-ui,sans-serif;background:#f4f6f8;color:#182c3b;margin:0}}
main {{max-width:1100px;margin:2rem auto;padding:1.5rem;background:white}}
form {{display:flex;flex-wrap:wrap;gap:.7rem;align-items:end;padding:1rem;background:#e8eef3}}
label {{display:grid;gap:.4rem}} input,button {{font:inherit;padding:.55rem}}
table {{width:100%;border-collapse:collapse}} th,td {{text-align:left;padding:.7rem;
border-bottom:1px solid #c9d1d8}} th {{background:#e8eef3}}
.table-scroll {{overflow-x:auto}} .metadata {{color:#526473;font-size:.9rem}}
.error {{padding:1rem;background:#ffe8e5;border-left:4px solid #a32920}}
{MODE_NAV_CSS}</style></head><body><main>{render_mode_navigation("order")}
{body}</main></body></html>'''
def _form(query: str) -> str:
return ('<form method="get" action="/orders"><label>Fertigungsauftrag (FA)'
f'<input type="search" name="q" value="{escape(query, quote=True)}"'
' maxlength="80" required></label><button type="submit">Suchen</button></form>')
def _text(value: str | None) -> str:
return escape(value) if value else "–"
def _period(value, timezone) -> str:
label = value.strftime("%d.%m.%Y %H:%M")
return escape(f"{label} ({timezone.key})" if timezone else f"{label} (ERP-Lokalzeit)")
def render_search(*, query: str = "", results: tuple[ProductionOrderSearchResult, ...] = (),
error: str | None = None, searched: bool = False) -> str:
body = "<h1>Fertigungsauftrag suchen</h1>" + _form(query)
if error:
body += f'<p class="error" role="alert">{escape(error)}</p>'
elif searched:
if not results:
body += "<p>Keine passenden Fertigungsaufträge gefunden.</p>"
else:
body += '<div class="table-scroll"><table><thead><tr><th>FA</th><th>Artikel</th>'
body += '<th>Artikelbezeichnung</th><th>Arbeitsplatz / Maschine</th>'
body += '<th>Erste Rückmeldung</th><th>Letzte Rückmeldung</th></tr></thead><tbody>'
for result in results:
href = "/order?" + urlencode({"production_order": result.production_order})
for placement in result.placements:
machine = placement.machine_name or "nicht zugeordnet"
link = (f'<a href="{escape(href, quote=True)}">'
f'{escape(result.production_order)}</a>')
body += "<tr>" + "".join(f"<td>{cell}</td>" for cell in (
link,
_text(placement.article_number), _text(placement.article_description),
escape(f"{placement.workplace} / {machine}"),
_period(placement.first_confirmation_local, placement.timezone),
_period(placement.last_confirmation_local, placement.timezone),
)) + "</tr>"
body += "</tbody></table></div>"
return _page("Fertigungsauftrag suchen", body)
def render_detail(*, detail: ProductionOrderDetail | None,
error: str | None = None) -> str:
if error:
return _page("Fertigungsauftrag", f'<p class="error" role="alert">{escape(error)}</p>')
if detail is None:
return _page("Fertigungsauftrag", "<p>Fertigungsauftrag nicht gefunden.</p>")
body = f"<h1>Fertigungsauftrag {escape(detail.production_order)}</h1>"
body += '<p class="metadata">Zeiten sind ERP-Rückmeldezeitpunkte, keine durchgehenden '
body += 'Maschinenlaufzeiten. Mengen sind positive Rückmeldemengen in m². '
body += 'Geschwindigkeit und Material beziehen sich auf angenäherte FA-Zeitfenster.</p>'
body += '<h2>Artikel und Arbeitsplätze</h2><div class="table-scroll"><table><thead><tr>'
body += '<th>Artikel</th><th>Artikelbezeichnung</th><th>Arbeitsplatz / Maschine</th>'
body += '<th>Erste Rückmeldung</th><th>Letzte Rückmeldung</th></tr></thead><tbody>'
for placement in detail.placements:
machine = placement.machine_name or f"nicht zugeordnet ({placement.mapping_status})"
body += "<tr>" + "".join(f"<td>{cell}</td>" for cell in (
_text(placement.article_number), _text(placement.article_description),
escape(f"{placement.workplace} / {machine}"),
_period(placement.first_confirmation_local, placement.timezone),
_period(placement.last_confirmation_local, placement.timezone),
)) + "</tr>"
body += '</tbody></table></div><h2>Schichten</h2>'
if not detail.shifts:
body += "<p>Keine Schichtzuordnung für konfigurierte Maschinen verfügbar.</p>"
else:
body += '<div class="table-scroll"><table><thead><tr><th>Standort</th><th>Maschine</th>'
body += '<th>Datum</th><th>Schicht</th><th>Produzierte Menge</th>'
body += '<th>Ø Geschwindigkeit</th><th>Materialverbrauch</th>'
body += '<th>Erste Rückmeldung</th><th>Letzte Rückmeldung</th><th>Bericht</th>'
body += '</tr></thead><tbody>'
for item in detail.shifts:
href = "/?" + urlencode({"date": item.date.isoformat(), "shift": item.shift,
"machine": item.machine_name})
body += "<tr>" + "".join(f"<td>{cell}</td>" for cell in (
escape(item.site.title()), escape(item.machine_name),
item.date.strftime("%d.%m.%Y"),
SHIFT_LABELS[item.shift], f"{item.produced_m2:,.2f} m²",
(f"{_number(item.average_speed_m_min)} m/min"
if item.average_speed_m_min is not None else "—"),
(f"{_number(item.material_consumption_kg)} kg"
if item.material_consumption_kg is not None else "—"),
escape(item.first_confirmation.strftime("%d.%m.%Y %H:%M %Z")),
escape(item.last_confirmation.strftime("%d.%m.%Y %H:%M %Z")),
f'<a href="{escape(href, quote=True)}">Schichtbericht</a>',
)) + "</tr>"
body += "</tbody></table></div>"
return _page(f"Fertigungsauftrag {detail.production_order}", body)
@@ -0,0 +1,309 @@
"""German operational shift slips with deterministic A4 PDF output."""
from collections import defaultdict
from dataclasses import dataclass
from io import BytesIO
from math import fsum
from pathlib import Path
from xml.sax.saxutils import escape
from production_analytics.calculations.shift_report import ShiftReport
def _number(value: float) -> str:
return f"{value:,.2f}".translate(str.maketrans({",": ".", ".": ","}))
def _duration(seconds: float) -> str:
hours, remainder = divmod(round(seconds, 1), 3600)
minutes, seconds = divmod(remainder, 60)
return f"{int(hours)} h {int(minutes):02d} min {seconds:04.1f} s".replace(".", ",")
@dataclass(frozen=True, slots=True)
class TextBlock:
text: str
style: str = "Normal"
@dataclass(frozen=True, slots=True)
class TableBlock:
headers: tuple[str, ...]
rows: tuple[tuple[str, ...], ...]
widths_mm: tuple[float, ...]
@dataclass(frozen=True, slots=True)
class MaterialPieBlock:
labels: tuple[str, ...]
consumption_kg: tuple[float, ...]
def present_report(
report: ShiftReport,
*,
include_single_material_chart: bool = False,
) -> tuple[TextBlock | TableBlock | MaterialPieBlock, ...]:
"""Format supplied values and material totals without source access or a clock."""
story = []
def text(value: str, style: str = "Normal") -> None:
story.append(TextBlock(value, style))
def table(headers: tuple[str, ...], rows: list[tuple], widths: list[float]) -> None:
story.append(TableBlock(headers, tuple(rows), tuple(widths)))
text("Schichtbericht", "Title")
text(f"Maschine: {report.display_name or report.machine_name}", "Heading2")
for label, timestamp in (("Schichtbeginn", report.start), ("Schichtende", report.end)):
text(f"{label}: {timestamp.astimezone(report.timezone):%d.%m.%Y %H:%M:%S %Z (%z)}")
text(f"Zeitzone: {report.timezone.key}")
text("Produktion", "Heading2")
if report.production is None:
text("Für diese Maschine nicht verfügbar.")
elif report.production.items:
table(
("Produktionsauftrag", "Artikelnummer", "Artikelbeschreibung", "Menge", "Rollen",
"Ø Geschwindigkeit", "Materialverbrauch"),
[
(
item.production_order,
item.article_number or "Nicht verfügbar",
item.article_description or "Nicht verfügbar",
f"{_number(item.produced_m2)} m²",
str(item.roll_count),
(f"{_number(item.average_speed_m_min)} m/min"
if item.average_speed_m_min is not None else "—"),
(f"{_number(item.material_consumption_kg)} kg"
if item.material_consumption_kg is not None else "—"),
)
for item in report.production.items
],
[28, 22, 44, 23, 13, 23, 25],
)
elif report.production is not None:
text("Keine Produktionsdaten vorhanden.")
if report.production is not None:
text(
f"Gesamtmenge: {_number(report.production.total_produced_m2)} m² | "
f"Rollen gesamt: {report.production.total_roll_count}"
)
text("Stillstand", "Heading2")
if report.downtime is None:
text("Für diese Maschine nicht verfügbar.")
else:
text(f"Stillstand gesamt: {_duration(report.downtime.total_downtime_seconds)}")
text("Zeit ohne erfassten Stillstand: " + _duration(report.downtime.non_downtime_seconds))
text("Top 3 Stillstandsgründe", "Heading3")
if report.top_downtime_reasons:
table(
("Stillstandsgrund", "Dauer"),
[
(view.display_name, _duration(view.reason.duration_seconds))
for view in report.top_downtime_reasons
],
[125, 53],
)
else:
text("Keine Stillstandsgründe vorhanden.")
if not report.downtime.events:
text("Keine Stillstandsereignisse vorhanden.")
text("Materialverbrauch", "Heading2")
if report.materials is None:
text("Für diese Maschine nicht verfügbar.")
else:
material_totals = defaultdict(list)
for item in report.materials.items:
material_totals[(item.material_number, item.material_name)].append(item.consumption_kg)
materials = [
(number, name, fsum(quantities))
for (number, name), quantities in sorted(
material_totals.items(),
key=lambda entry: (entry[0][1] or "", entry[0][0] or ""),
)
if fsum(quantities) != 0
]
if any(item.erp_booking_share is not None for item in report.materials.items):
allocation_totals = defaultdict(list)
for item in report.materials.items:
allocation_totals[
(
item.production_order,
item.material_number,
item.material_name,
item.erp_booking_share,
)
].append(item.consumption_kg)
rows = []
for (order, number, name, share), quantities in sorted(
allocation_totals.items(),
key=lambda entry: (
entry[0][0],
entry[0][2] or "",
entry[0][1] or "",
-1 if entry[0][3] is None else entry[0][3],
),
):
quantity = fsum(quantities)
if quantity != 0:
rows.append(
(
order,
name or number or "Materialzuordnung fehlt",
number or "–",
f"{_number(quantity)} kg",
f"{share * 100:.0f}%" if share is not None else "–",
)
)
if rows:
table(
("Produktionsauftrag", "Materialname", "Materialnummer", "Verbrauch",
"ERP-Anteil"),
rows,
[32, 66, 28, 30, 22],
)
else:
text("Keine Materialverbrauchsdaten vorhanden.")
text(
"Verbrauchsaufteilung geschätzt nach ERP-Buchungsverhältnis; "
"Gesamtverbrauch aus ENLYZE."
)
elif materials:
table(
("Materialname", "Materialnummer", "Verbrauch"),
[
(
name or number or "Materialzuordnung fehlt",
number or "–",
f"{_number(quantity)} kg",
)
for number, name, quantity in materials
],
[110, 38, 30],
)
else:
text("Keine Materialverbrauchsdaten vorhanden.")
text(f"Materialverbrauch gesamt: {_number(report.materials.total_consumption_kg)} kg")
positive_materials = [
(number, name, quantity) for number, name, quantity in materials if quantity > 0
]
if len(positive_materials) >= (1 if include_single_material_chart else 2):
base_labels = [
name or number or "Materialzuordnung fehlt"
for number, name, _ in positive_materials
]
labels = tuple(
f"{label} ({number or 'ohne Materialnummer'})"
if base_labels.count(label) > 1
else label
for label, (number, _, _) in zip(base_labels, positive_materials)
)
story.append(
MaterialPieBlock(labels, tuple(quantity for _, _, quantity in positive_materials))
)
return tuple(story)
def render_pdf(report: ShiftReport) -> bytes:
"""Repeatable bytes with the same ReportLab version and invariant metadata."""
from reportlab.graphics.charts.piecharts import Pie
from reportlab.graphics.shapes import Drawing, Rect
from reportlab.lib import colors
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.units import mm
from reportlab.pdfgen.canvas import Canvas
from reportlab.platypus import Paragraph, SimpleDocTemplate, Spacer, Table, TableStyle
styles = getSampleStyleSheet()
styles["Normal"].fontSize = 9
styles["Normal"].leading = 12
def paragraph(value: str, style: str = "Normal") -> Paragraph:
return Paragraph(escape(value).replace("\n", "<br/>"), styles[style])
story = []
for block in present_report(report):
if isinstance(block, TextBlock):
story.extend([paragraph(block.text, block.style), Spacer(1, 3 * mm)])
elif isinstance(block, MaterialPieBlock):
palette = tuple(
colors.HexColor(value)
for value in ("#496a81", "#8aa399", "#c4ad7a", "#9a869f", "#8399b0", "#b78e7c")
)
drawing = Drawing(65 * mm, 60 * mm)
pie = Pie()
pie.x, pie.y = 5 * mm, 2 * mm
pie.width = pie.height = 55 * mm
pie.data = list(block.consumption_kg)
pie.labels = []
pie.slices.strokeColor = colors.white
pie.slices.strokeWidth = 0.5
legend_rows = []
for index, label in enumerate(block.labels):
color = palette[index % len(palette)]
pie.slices[index].fillColor = color
swatch = Drawing(4 * mm, 4 * mm)
swatch.add(Rect(0, 0, 4 * mm, 4 * mm, fillColor=color, strokeColor=None))
legend_rows.append([swatch, paragraph(label)])
drawing.add(pie)
legend = Table(legend_rows, colWidths=[8 * mm, 101 * mm])
legend.setStyle(TableStyle([("VALIGN", (0, 0), (-1, -1), "TOP")]))
chart = Table([[drawing, legend]], colWidths=[65 * mm, 113 * mm], splitInRow=1)
chart.setStyle(
TableStyle(
[
("VALIGN", (0, 0), (-1, -1), "TOP"),
("LEFTPADDING", (0, 0), (-1, -1), 0),
("RIGHTPADDING", (0, 0), (-1, -1), 0),
]
)
)
story.extend([chart, Spacer(1, 4 * mm)])
else:
cells = [[paragraph(value) for value in row] for row in [block.headers, *block.rows]]
result = Table(cells, colWidths=[width * mm for width in block.widths_mm], repeatRows=1)
result.setStyle(
TableStyle(
[
("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#e8eef3")),
("VALIGN", (0, 0), (-1, -1), "TOP"),
("LINEBELOW", (0, 0), (-1, -1), 0.3, colors.HexColor("#c9d1d8")),
("TOPPADDING", (0, 0), (-1, -1), 6),
("BOTTOMPADDING", (0, 0), (-1, -1), 6),
]
)
)
story.extend([result, Spacer(1, 4 * mm)])
buffer = BytesIO()
document = SimpleDocTemplate(
buffer,
pagesize=A4,
leftMargin=16 * mm,
rightMargin=16 * mm,
topMargin=16 * mm,
bottomMargin=16 * mm,
title="Schichtbericht",
author="Production Analytics",
pageCompression=0,
)
def canvas(*args, **kwargs):
kwargs["invariant"] = 1
return Canvas(*args, **kwargs)
def footer(canvas, document):
canvas.saveState()
canvas.setFont("Helvetica", 8)
canvas.drawRightString(A4[0] - 16 * mm, 10 * mm, f"Seite {document.page}")
canvas.restoreState()
document.build(story, canvasmaker=canvas, onFirstPage=footer, onLaterPages=footer)
return buffer.getvalue()
def write_pdf(report: ShiftReport, output: Path) -> None:
payload = render_pdf(report)
output.parent.mkdir(parents=True, exist_ok=True)
output.write_bytes(payload)
@@ -0,0 +1,149 @@
"""HTML formatting of the shared report presentation; no data-source access."""
from html import escape
from math import fsum
from urllib.parse import urlencode
from production_analytics.presentation.mode_navigation import (
MODE_NAV_CSS,
render_mode_navigation,
)
from production_analytics.presentation.shift_report import (
MaterialPieBlock,
TableBlock,
TextBlock,
_number,
present_report,
)
def _material_chart(block: MaterialPieBlock) -> str:
"""Draw supplied material slices; percentages are presentation geometry only.
No scripts or external assets: source labels are escaped HTML/SVG text.
The adjacent shared material table remains the textual source of truth.
"""
palette = ("#496a81", "#8aa399", "#c4ad7a", "#9a869f", "#8399b0", "#b78e7c")
total = fsum(block.consumption_kg)
slices, legend = [], []
offset = 0.0
for index, (label, kg) in enumerate(zip(block.labels, block.consumption_kg)):
percent = kg / total * 100
color = palette[index % len(palette)]
description = f"{label}: {_number(kg)} kg ({_number(percent)} %)"
slices.append(
f'<circle cx="60" cy="60" r="44" pathLength="100" fill="none" '
f'stroke="{color}" stroke-width="22" '
f'stroke-dasharray="{percent:.8f} {100 - percent:.8f}" '
f'stroke-dashoffset="{-offset:.8f}" transform="rotate(-90 60 60)">'
f"<title>{escape(description)}</title></circle>"
)
legend.append(
f'<li><span class="material-swatch" style="background:{color}" '
f'aria-hidden="true"></span><span>{escape(description)}</span></li>'
)
offset += percent
return (
'<figure class="material-chart"><figcaption>Verbrauchsanteile nach Material</figcaption>'
'<svg viewBox="0 0 120 120" role="img" aria-label="Materialverbrauch in kg">'
"<title>Verbrauchsanteile nach Material; Werte in der Legende</title>"
+ "".join(slices)
+ '</svg><ul class="material-legend">'
+ "".join(legend)
+ '</ul><p class="metadata">Anteile der positiven Verbrauchsmengen.</p></figure>'
)
def render_page(*, machines, labels, day, shift, machine, report, generated_at, error,
sites=None):
machine_labels = ((key, getattr(config, "display_name", key))
for key, config in machines.items())
def options(values, selected):
return "".join(
f'<option value="{escape(key, quote=True)}"'
+ (" selected" if key == selected else "")
+ f">{escape(label)}</option>"
for key, label in values
)
body = ""
if error:
body = f'<p class="error" role="alert">{escape(error)}</p>'
if report is not None:
body += (
f'<p class="metadata">Datenstand: {generated_at:%d.%m.%Y %H:%M:%S %Z} '
f"({report.timezone.key}). Quellen können nachträglich korrigiert werden.</p>"
)
material_open = False
details_open = False
for block in present_report(report, include_single_material_chart=True):
if isinstance(block, TextBlock):
if material_open and block.style == "Heading2":
body += ("</div>" if details_open else "") + "</div></section>"
material_open = details_open = False
if block.text == "Materialverbrauch" and block.style == "Heading2":
body += (
'<section class="material-section"><h2>Materialverbrauch</h2>'
'<div class="material-layout"><div class="material-details">'
)
material_open = details_open = True
continue
tag = {"Title": "h1", "Heading2": "h2", "Heading3": "h3"}.get(block.style, "p")
body += f"<{tag}>{escape(block.text)}</{tag}>"
elif isinstance(block, TableBlock):
body += '<div class="table-scroll"><table><thead><tr>'
body += "".join(f'<th scope="col">{escape(cell)}</th>' for cell in block.headers)
body += "</tr></thead><tbody>"
production_table = block.headers[:2] == ("Produktionsauftrag", "Artikelnummer")
for row in block.rows:
cells = []
for index, cell in enumerate(row):
if production_table and index == 0:
href = "/order?" + urlencode({"production_order": cell})
cells.append(
f'<td><a class="fa-link" href="{escape(href, quote=True)}">'
f"{escape(cell)}</a></td>"
)
else:
cells.append(f"<td>{escape(cell)}</td>")
body += "<tr>" + "".join(cells) + "</tr>"
body += "</tbody></table></div>"
elif isinstance(block, MaterialPieBlock):
body += "</div>" + _material_chart(block)
details_open = False
if material_open:
body += ("</div>" if details_open else "") + "</div></section>"
return f'''<!doctype html>
<html lang="de"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Live-Schichtberichte</title><style>
body {{font: 16px system-ui,sans-serif; background:#f4f6f8; color:#182c3b; margin:0}}
main {{max-width:1100px; margin:2rem auto; padding:1.5rem; background:white}}
form {{display:flex; flex-wrap:wrap; gap:1rem; align-items:end; padding:1rem;
background:#e8eef3}} label {{display:grid; gap:.4rem}}
input,select,button {{font:inherit; padding:.55rem}} button {{cursor:pointer}}
table {{width:100%; border-collapse:collapse}} th,td {{text-align:left; padding:.7rem;
border-bottom:1px solid #c9d1d8}} th {{background:#e8eef3}}
.table-scroll {{overflow-x:auto}} .metadata {{color:#526473; font-size:.9rem}}
.fa-link {{color:#17547a; font-weight:600; text-decoration:underline;
text-underline-offset:2px}} .fa-link:hover,.fa-link:focus-visible {{color:#0b3653}}
.material-layout {{display:grid; grid-template-columns:minmax(0, 1fr) 300px; gap:1.5rem}}
.material-chart {{margin:0; min-width:0}} .material-chart svg {{display:block;
width:220px; max-width:100%; margin:.75rem auto}}
.material-chart figcaption {{font-weight:600}} .material-legend {{list-style:none; padding:0}}
.material-legend li {{display:flex; gap:.5rem; margin:.6rem 0; overflow-wrap:anywhere}}
.material-swatch {{width:.9rem; height:.9rem; flex-shrink:0; margin-top:.2rem}}
@media(max-width:850px) {{.material-layout {{grid-template-columns:minmax(0, 1fr)}}}}
.error {{padding:1rem; background:#ffe8e5; border-left:4px solid #a32920}}
{MODE_NAV_CSS}</style></head><body><main>{render_mode_navigation("shift")}
<h1>Live-Schichtberichte</h1>
<form method="get" action="/">
<label>Datum (Schichtbeginn)<input type="date" name="date" required
value="{day.isoformat()}"></label>
<label>Schicht<select name="shift">{options(labels.items(), shift)}</select></label>
<label>Maschine<select name="machine">{options(machine_labels, machine)}
</select></label>
<button type="submit">Bericht anzeigen</button>
<button type="submit" name="format" value="pdf">Als PDF exportieren</button>
</form><p class="metadata">Nachtschicht: 22:00 Uhr am gewählten Datum bis 06:00 Uhr
am Folgetag. Jeder Aufruf liest die aktuellen Quelldaten.</p>{body}</main></body></html>'''
@@ -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)
@@ -0,0 +1,46 @@
"""Explicit K7 order adapter; generic measured material calculation stays ERP-free."""
import re
from collections import defaultdict
from dataclasses import replace
from math import fsum
from typing import Protocol
from production_analytics.calculations.fiber_allocation import (
FiberBooking,
allocate_fiber_materials,
)
from production_analytics.calculations.shift_material import ShiftMaterialSummary
class FiberBookingReader(Protocol):
def get_fiber_bookings(self, production_order: str) -> list[FiberBooking]: ...
class K7FiberAllocationService:
def __init__(self, reader: FiberBookingReader) -> None:
self.reader = reader
def allocate(self, measured: ShiftMaterialSummary) -> ShiftMaterialSummary:
bookings = {}
items = []
for item in measured.items:
match = re.fullmatch(r"(?:K 7-)?([0-9]+)", item.production_order.strip())
if match is None:
items.append(item)
continue
order = match[1]
if order not in bookings:
bookings[order] = self.reader.get_fiber_bookings(order)
items.extend(allocate_fiber_materials(item, bookings[order], erp_order=order))
# Keep the measured shift total, rather than replacing it with an ERP total.
return replace(measured, items=tuple(items))
def totals_by_order(self, allocated: ShiftMaterialSummary) -> dict[str, float]:
"""Sum the same allocated items shown in the shift material table by ERP FA."""
quantities = defaultdict(list)
for item in allocated.items:
match = re.fullmatch(r"(?:K 7-)?([0-9]+)", item.production_order.strip())
if match is not None:
quantities[match[1]].append(item.consumption_kg)
return {order: fsum(values) for order, values in quantities.items()}
@@ -0,0 +1,98 @@
"""Conservative historical attribution decisions and orchestration, without SQL."""
from dataclasses import dataclass
from datetime import datetime, time, timedelta
from zoneinfo import ZoneInfo
from production_analytics.context import build_enlyze_production_order
BERLIN = ZoneInfo("Europe/Berlin")
def reconciliation_window(now: datetime, lookback_days: int = 3):
"""Previous N complete Berlin calendar days, as a half-open interval."""
if now.utcoffset() is None or isinstance(lookback_days, bool) or lookback_days < 1:
raise ValueError("An aware clock and positive lookback-days are required")
end = datetime.combine(now.astimezone(BERLIN).date(), time(), BERLIN)
return end - timedelta(days=lookback_days), end
@dataclass(frozen=True)
class HistoricalRecord:
table: str
identity: tuple
machine_id: str
timestamp: datetime
production_order: str
run_id: str
@dataclass(frozen=True)
class Decision:
record: HistoricalRecord
order: str | None
reason: str
desired_run_id: str | None = None
def decide(record, runs, confirmations, workplace, format_template):
"""Keep physical counter/run identities; never infer boundaries from ERP points."""
candidates = [r for r in runs if r.machine_id == record.machine_id
and r.start.timestamp() <= record.timestamp.timestamp()
and (r.end is None or record.timestamp.timestamp() < r.end.timestamp())]
if len(candidates) != 1 or candidates[0].end is None:
return Decision(record, None, "unresolved: missing or overlapping closed ENLYZE runs")
run = candidates[0]
orders = {build_enlyze_production_order(c.production_order, format_template)
for c in confirmations if c.workplace == workplace and c.is_finished_goods
and run.start.timestamp() < c.timestamp.timestamp() < run.end.timestamp()}
if orders != {run.production_order}:
return Decision(record, None, "unresolved: ERP evidence missing or conflicts with ENLYZE")
return Decision(record, run.production_order,
f"closed ENLYZE run {run.uuid} [{run.start.isoformat()}, "
f"{run.end.isoformat()}) corroborated by ERP order {run.production_order}",
run.uuid)
def reconcile_machine(repository, source, erp, config, template, start, end, dry_run=False):
records = repository.read(config.machine_id, start, end)
runs = source.get_production_runs(config.machine_id)
# Query complete overlapping runs so partial-window evidence cannot conceal conflicts.
relevant = [r for r in runs if r.end is not None
and r.start.timestamp() < end.timestamp() and r.end.timestamp() > start.timestamp()]
evidence_start = min([start, *(r.start for r in relevant)], key=datetime.timestamp)
evidence_end = max([end, *(r.end for r in relevant)], key=datetime.timestamp)
confirmations = erp.get_confirmations(
workplace=config.erp_workplace, start=evidence_start, end=evidence_end,
)
decisions = [decide(r, runs, confirmations, config.erp_workplace, template) for r in records]
# Require complete, unambiguous evidence, allowing orders within a physical run.
decisions = repository.guard_runs(decisions)
applied = repository.apply(decisions) if not dry_run else 0
return decisions, applied
def grouped_counts(decisions):
"""Count physical identities and contiguous attribution segments, not snapshot rows."""
groups = {}
for d in decisions:
r = d.record
key = (r.table, r.machine_id, r.identity[0], r.run_id)
groups.setdefault(key, []).append(d)
proposed_runs = unresolved_runs = corrected_segments = unresolved_segments = 0
for peers in groups.values():
proposed_runs += any(d.order is not None and d.order != d.record.production_order
for d in peers)
unresolved_runs += any(d.order is None for d in peers)
streams = {}
for d in peers:
streams.setdefault(d.record.identity[3:], []).append(d)
for stream in streams.values():
previous = object()
for d in sorted(stream, key=lambda d: d.record.timestamp.timestamp()):
state = (d.order, d.order is not None and d.order != d.record.production_order)
if state != previous:
unresolved_segments += d.order is None
corrected_segments += state[1]
previous = state
return (len(groups), proposed_runs, corrected_segments, unresolved_runs, unresolved_segments)
@@ -0,0 +1,116 @@
"""Nightly reconciliation composition and operator output."""
from datetime import datetime
import yaml
from production_analytics.context import build_enlyze_production_order
from production_analytics.enlyze.exploration import ExplorationClient, ExplorationSettings
from production_analytics.enlyze.gateway import EnlyzeApiGateway
from production_analytics.erp import ErpProductionConfirmationGateway, ErpSettings
from production_analytics.service.historical_reconcile import (
BERLIN,
grouped_counts,
reconcile_machine,
reconciliation_window,
)
from production_analytics.service.postgres_historical_reconcile import PostgresHistoricalRepository
from production_analytics.service.postgres_material import PostgresSettings
from production_analytics.service.shift_report_config import (
_StrictLoader,
load_shift_report_machines,
)
def _summarize_decisions(name, decisions, dry_run, verbose):
"""Print run and source stream summaries from existing decisions."""
corrections = {}
unresolved = {}
for decision in decisions:
record = decision.record
if decision.order is None:
if verbose:
print(f"Unresolved {name} {record.identity}: {decision.reason}")
# Keep distinct physical runs and source streams separate, even when
# they share the same unresolved reason.
key = (decision.reason, record.table, record.identity[0], record.run_id,
record.identity[3:])
groups = unresolved
elif decision.order != record.production_order:
if verbose:
print(f"{'Proposed' if dry_run else 'Corrected'} {name} "
f"{record.table} {record.identity}: "
f"{record.production_order} -> {decision.order}; {decision.reason}")
prefix = "closed ENLYZE run "
run_uuid = (decision.reason[len(prefix):].split(" [", 1)[0]
if decision.reason.startswith(prefix) else "unknown")
key = (record.production_order, decision.order, run_uuid)
groups = corrections
else:
continue
if key not in groups:
groups[key] = [0, record.timestamp, record.timestamp]
group = groups[key]
group[0] += 1
group[1] = min(group[1], record.timestamp)
group[2] = max(group[2], record.timestamp)
action = "proposed" if dry_run else "corrected"
for (old, new, run_uuid), (count, _first, _last) in corrections.items():
print(f"{name} | {action}: {old} -> {new} | ENLYZE run {run_uuid} | "
f"{count} records")
for (reason, table, calculation, run_id, stream), (count, first, last) in unresolved.items():
source = f"{table}/{calculation}"
if stream:
source += "/" + "/".join(map(str, stream))
print(f"{name} | {reason} | physical run {run_id} | source {source} | "
f"{count} records | {first.isoformat()} -> {last.isoformat()}")
def run(args, environment):
start, end = reconciliation_window(datetime.now(BERLIN), args.lookback_days)
machines = {name: config for name, config in load_shift_report_machines(args.config).items()
if config.capabilities.material}
with args.order_formats.open(encoding="utf-8") as stream:
formats = yaml.load(stream, Loader=_StrictLoader)
if not isinstance(formats, dict) or set(formats) != set(machines):
raise ValueError("Order formats must map every material machine name exactly once")
for template in formats.values():
if not isinstance(template, str):
raise ValueError("Order formats must be strings")
build_enlyze_production_order("1", template)
repository = PostgresHistoricalRepository(PostgresSettings.from_environment(environment))
source = EnlyzeApiGateway(ExplorationClient(ExplorationSettings.from_environment(environment)))
erp = ErpProductionConfirmationGateway(ErpSettings.from_environment(environment))
print("Historical reconciliation" + (" (DRY RUN)" if args.dry_run else ""))
print(f"Window: {start.isoformat()} to {end.isoformat()} (exclusive)")
grouped = [0] * 5
inspected = corrections = unresolved = unchanged = failures = 0
for name, config in machines.items():
try:
decisions, applied = reconcile_machine(
repository, source, erp, config, formats[name], start, end, args.dry_run,
)
grouped = [a + b for a, b in zip(grouped, grouped_counts(decisions))]
inspected += len(decisions)
proposed = 0
for d in decisions:
if d.order is None:
unresolved += 1
elif d.order == d.record.production_order:
unchanged += 1
else:
proposed += 1
_summarize_decisions(name, decisions, args.dry_run, getattr(args, "verbose", False))
corrections += proposed if args.dry_run else applied
except Exception as exc:
failures += 1
print(f"FAILED {name}: {type(exc).__name__}: {exc}; machine transaction rolled back")
print(f"Machines checked: {len(machines)}\nRecords inspected: {inspected}")
print(f"Corrections {'proposed' if args.dry_run else 'applied'}: {corrections}")
print(f"Ambiguous/unresolved: {unresolved}\nUnchanged: {unchanged}\nFailures: {failures}")
print(f"Physical runs inspected: {grouped[0]}\nRuns with proposed corrections: {grouped[1]}")
label = "proposed" if args.dry_run else "corrected"
print(f"Order segments {label}: {grouped[2]}")
print(f"Unresolved runs: {grouped[3]}\nUnresolved segments: {grouped[4]}")
return 1 if failures else 0
@@ -1,18 +1,45 @@
"""ERP nominal-width resolution for an explicitly matched production order.""" """ERP nominal-width resolution for an explicitly matched production order."""
import logging
from production_analytics.calculations.config import finite_number
from production_analytics.context import build_enlyze_production_order, extract_nominal_width_m from production_analytics.context import build_enlyze_production_order, extract_nominal_width_m
from production_analytics.erp import ErpWorkplaceStatusGateway from production_analytics.erp import ErpReadError, ErpWorkplaceStatusGateway
logger = logging.getLogger(__name__)
class ErpNominalWidthProvider: class ErpNominalWidthProvider:
def __init__( def __init__(
self, gateway: ErpWorkplaceStatusGateway, *, workplace: str, format_template: str, self, gateway: ErpWorkplaceStatusGateway, *, workplace: str, format_template: str,
fallback_nominal_width_m: float | None = None,
) -> None: ) -> None:
self.gateway = gateway self.gateway = gateway
self.workplace = workplace self.workplace = workplace
self.format_template = format_template self.format_template = format_template
self.fallback_nominal_width_m = (
None if fallback_nominal_width_m is None else finite_number(
fallback_nominal_width_m, "fallback_nominal_width_m", positive=True,
)
)
self._warned_fallback_orders: set[str] = set()
def __call__(self, production_order: str) -> float: def __call__(self, production_order: str) -> float:
try:
return self._resolve_erp_width(production_order)
except (ValueError, ErpReadError) as exc:
if self.fallback_nominal_width_m is None:
raise
if production_order not in self._warned_fallback_orders:
logger.warning(
"ERP nominal-width resolution failed for ENLYZE production order %r: %s; "
"using fallback nominal width %s m",
production_order, exc, self.fallback_nominal_width_m,
)
self._warned_fallback_orders.add(production_order)
return self.fallback_nominal_width_m
def _resolve_erp_width(self, production_order: str) -> float:
status = self.gateway.get_current_workplace_status(self.workplace) status = self.gateway.get_current_workplace_status(self.workplace)
if (status is None if (status is None
or status.workplace.strip().casefold() != self.workplace.strip().casefold() or status.workplace.strip().casefold() != self.workplace.strip().casefold()
@@ -61,15 +61,21 @@ class MaterialPollingService:
nominal_width_provider: Callable[[str], float] | None = None, nominal_width_provider: Callable[[str], float] | None = None,
process_application_calculation_id: str | None = None, process_application_calculation_id: str | None = None,
application_writer: MaterialApplicationWriter | None = None, application_writer: MaterialApplicationWriter | None = None,
specific_discharge_kg_per_signal_unit_m: float | None = None,
) -> None: ) -> None:
if application_variable_ids and rotational_speed_variable_ids: if application_variable_ids and rotational_speed_variable_ids:
raise ValueError("Material source modes are mutually exclusive") raise ValueError("Material source modes are mutually exclusive")
if specific_discharge_kg_per_signal_unit_m is not None and not application_variable_ids:
raise ValueError("Signal discharge requires source signals")
self._signal_discharge = specific_discharge_kg_per_signal_unit_m
if process_application_calculation_id is not None and ( if process_application_calculation_id is not None and (
not rotational_speed_variable_ids or not gate_variable_id not (rotational_speed_variable_ids
or specific_discharge_kg_per_signal_unit_m is not None)
or not gate_variable_id
or gate_threshold <= 0 or application_writer is None or gate_threshold <= 0 or application_writer is None
): ):
raise ValueError( raise ValueError(
"Process application requires rotational source, positive gate and writer" "Process application requires calibrated source, positive gate and writer"
) )
self._process_application_calculation_id = process_application_calculation_id self._process_application_calculation_id = process_application_calculation_id
self._application_writer = application_writer self._application_writer = application_writer
@@ -171,6 +177,8 @@ class MaterialPollingService:
source_options = dict( source_options = dict(
application_variable_ids=self._application_variable_ids, nominal_width_m=width, application_variable_ids=self._application_variable_ids, nominal_width_m=width,
) )
if self._signal_discharge is not None:
source_options["specific_discharge_kg_per_signal_unit_m"] = self._signal_discharge
if self._rotational_speed_variable_ids: if self._rotational_speed_variable_ids:
source_options = dict( source_options = dict(
rotational_speed_variable_ids=self._rotational_speed_variable_ids, rotational_speed_variable_ids=self._rotational_speed_variable_ids,
@@ -3,6 +3,7 @@
import math import math
import os import os
import tempfile import tempfile
from hashlib import sha256
from pathlib import Path from pathlib import Path
from urllib.parse import urlsplit from urllib.parse import urlsplit
@@ -76,15 +77,24 @@ def build_material_runner(
) from exc ) from exc
postgres_settings = PostgresSettings.from_environment(environment) postgres_settings = PostgresSettings.from_environment(environment)
source_options = {} source_options = {}
if calculation.source_mode in {"area_application", "rotational_discharge"}: if calculation.source_mode in {
"area_application", "rotational_discharge", "linear_signal_discharge",
}:
source_options = dict( source_options = dict(
application_variable_ids=calculation.application_signal_refs, application_variable_ids=calculation.application_signal_refs,
nominal_width_provider=ErpNominalWidthProvider( nominal_width_provider=ErpNominalWidthProvider(
ErpWorkplaceStatusGateway(ErpSettings.from_secret_file(erp_secrets_file)), ErpWorkplaceStatusGateway(ErpSettings.from_secret_file(erp_secrets_file)),
workplace=calculation.erp_workplace, workplace=calculation.erp_workplace,
format_template=calculation.production_order_format, format_template=calculation.production_order_format,
fallback_nominal_width_m=calculation.fallback_nominal_width_m,
), ),
) )
if calculation.source_mode == "linear_signal_discharge":
source_options["specific_discharge_kg_per_signal_unit_m"] = (
calculation.specific_discharge_kg_per_signal_unit_m
)
# Legacy runners retain their checkpoints; new calibrated sources are isolated.
state_directory = state_directory / sha256(calculation.id.encode("utf-8")).hexdigest()
if calculation.source_mode == "rotational_discharge": if calculation.source_mode == "rotational_discharge":
source_options.pop("application_variable_ids") source_options.pop("application_variable_ids")
source_options.update( source_options.update(
@@ -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,31 @@ 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 effective machine intervals intersecting [start, end)."""
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, attributed_start, attributed_end
FROM production_downtime_events
WHERE machine_id = %s AND COALESCE(attributed_start, source_start) < %s
AND (COALESCE(attributed_end, source_end) IS NULL
OR COALESCE(attributed_end, source_end) > %s)
ORDER BY COALESCE(attributed_start, 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,139 @@
"""Transactional attribution-only updates with an atomic audit trail."""
from contextlib import nullcontext
from dataclasses import replace
import psycopg
from psycopg import sql
from psycopg.types.json import Jsonb
from production_analytics.service.historical_reconcile import HistoricalRecord
TABLES = {
"material_consumption_snapshots": ("calculation_id", "machine_id", "timestamp"),
"material_application_snapshots": ("calculation_id", "machine_id", "timestamp"),
"channel_material_consumption_snapshots": (
"calculation_id", "machine_id", "timestamp", "extruder", "doser_channel",
),
}
class PostgresHistoricalRepository:
def __init__(self, settings):
self.settings = settings
def connect(self):
s = self.settings
return psycopg.connect(host=s.host, port=s.port, dbname=s.dbname, user=s.user,
password=s.password, connect_timeout=10,
options="-c statement_timeout=30000")
def read(self, machine_id, start, end):
result = []
with self.connect() as connection:
for table, keys in TABLES.items():
rows = connection.execute(sql.SQL(
"SELECT {}, production_order, run_id FROM {} "
"WHERE machine_id = %s AND timestamp >= %s AND timestamp < %s"
).format(sql.SQL(', ').join(map(sql.Identifier, keys)), sql.Identifier(table)),
(machine_id, start, end)).fetchall()
result.extend(HistoricalRecord(table, tuple(row[:-2]), machine_id, row[2],
row[-2], row[-1]) for row in rows)
return result
def guard_runs(self, decisions, connection=None):
"""Reject partial run repairs, including historical rows outside the window."""
groups = {}
for d in decisions:
r = d.record
groups.setdefault((r.table, r.machine_id, r.identity[0], r.run_id), []).append(d)
blocked = set()
context = self.connect() if connection is None else nullcontext(connection)
with context as connection:
for key, peers in groups.items():
corrections = [d for d in peers if d.order is not None
and d.order != d.record.production_order]
if not corrections:
continue
table, machine, calculation, run = key
count = connection.execute(sql.SQL(
"SELECT count(*) FROM {} WHERE machine_id = %s "
"AND calculation_id = %s AND run_id = %s"
).format(sql.Identifier(table)), (machine, calculation, run)).fetchone()[0]
if count != len(peers) or any(d.order is None for d in peers):
blocked.add(key)
return [replace(d, order=None,
reason="unresolved: partial or unresolved cumulative run")
if (d.record.table, d.record.machine_id, d.record.identity[0],
d.record.run_id) in blocked else d for d in decisions]
def apply(self, decisions):
count = 0
with self.connect() as connection:
# Serialize this job; concurrent changes fail rather than silently overwrite.
connection.execute("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE")
connection.execute("SELECT pg_advisory_xact_lock(704301)")
if self.guard_runs(decisions, connection) != decisions:
raise RuntimeError("Historical run changed concurrently; retry reconciliation")
for d in decisions:
r = d.record
if d.order is None or d.order == r.production_order:
continue
keys = TABLES[r.table]
predicate = sql.SQL(' AND ').join(
sql.SQL('{} = %s').format(sql.Identifier(k)) for k in keys)
action = "updated"
retained_run_id = None
if r.table == "material_application_snapshots":
source = connection.execute(sql.SQL(
"SELECT application_g_m2 FROM {} WHERE {} "
"AND production_order = %s AND run_id = %s FOR UPDATE"
).format(sql.Identifier(r.table), predicate),
(*r.identity, r.production_order, r.run_id)).fetchone()
if source is None:
raise RuntimeError(
"Historical record changed concurrently; retry reconciliation"
)
target = connection.execute(
"""SELECT run_id, application_g_m2 IS NOT DISTINCT FROM %s
FROM material_application_snapshots
WHERE calculation_id = %s AND machine_id = %s
AND timestamp = %s AND production_order = %s FOR UPDATE""",
(source[0], *r.identity, d.order)).fetchone()
if target is not None:
if (not target[1] or d.desired_run_id is None
or target[0] != d.desired_run_id):
raise RuntimeError(
"Historical application collision has conflicting measurement "
"or unexpected target run; machine transaction rolled back"
)
deleted = connection.execute(sql.SQL(
"DELETE FROM {} WHERE {} AND production_order = %s "
"AND run_id = %s RETURNING timestamp"
).format(sql.Identifier(r.table), predicate),
(*r.identity, r.production_order, r.run_id)).fetchone()
if deleted is None:
raise RuntimeError(
"Historical record changed concurrently; retry reconciliation"
)
action = "deduplicated"
retained_run_id = target[0]
if action == "updated":
changed = connection.execute(sql.SQL(
"UPDATE {} SET production_order = %s WHERE {} "
"AND production_order = %s AND run_id = %s RETURNING timestamp"
).format(sql.Identifier(r.table), predicate),
(d.order, *r.identity, r.production_order, r.run_id)).fetchone()
if changed is None:
raise RuntimeError(
"Historical record changed concurrently; retry reconciliation"
)
connection.execute(
"""INSERT INTO historical_assignment_audit
(machine_id, source_table, record_identity, previous_order, new_order,
run_id, reason, action, retained_run_id)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)""",
(r.machine_id, r.table, Jsonb(dict(zip(keys, map(str, r.identity)))),
r.production_order, d.order, r.run_id, d.reason, action, retained_run_id))
count += 1
return count
@@ -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,326 @@
"""Order-oriented view of positive ERP production confirmations."""
from collections import defaultdict
from collections.abc import Mapping
from dataclasses import dataclass, replace
from datetime import UTC, date, datetime
from math import fsum
from typing import Literal, Protocol
from zoneinfo import ZoneInfo
from production_analytics.calculations.shift_material import ShiftMaterialSummary
from production_analytics.calculations.shift_report import shift_containing
from production_analytics.enlyze.exploration import ExplorationError
from production_analytics.erp.gateway import (
ErpReadError,
OrderConfirmationGroup,
OrderConfirmationRow,
ProductionConfirmation,
)
from production_analytics.service.postgres_shift_material import ShiftMaterialReadError
from production_analytics.service.shift_material import (
ShiftChannelMaterialService,
ShiftMaterialService,
)
from production_analytics.service.shift_report_config import ShiftReportMachineConfig
from production_analytics.service.shift_speed import ShiftSpeedService
class ProductionOrderReader(Protocol):
def search_orders(self, query: str, *, limit: int = 25) -> list[OrderConfirmationGroup]: ...
def get_order_confirmations(self, production_order: str) -> list[OrderConfirmationRow]: ...
def get_confirmations(self, *, workplace: str, start: datetime, end: datetime,
timezone: ZoneInfo) -> list[ProductionConfirmation]: ...
class MaterialAllocator(Protocol):
def allocate(self, measured: ShiftMaterialSummary) -> ShiftMaterialSummary: ...
def totals_by_order(self, allocated: ShiftMaterialSummary) -> dict[str, float]: ...
@dataclass(frozen=True, slots=True)
class ProductionOrderPlacement:
workplace: str
machine_name: str | None
site: str | None
timezone: ZoneInfo | None
article_number: str | None
article_description: str | None
first_confirmation_local: datetime
last_confirmation_local: datetime
mapping_status: Literal["configured", "unknown", "ambiguous"]
@dataclass(frozen=True, slots=True)
class ProductionOrderSearchResult:
production_order: str
placements: tuple[ProductionOrderPlacement, ...]
@dataclass(frozen=True, slots=True)
class ProductionOrderSegment:
start: datetime
end: datetime
@dataclass(frozen=True, slots=True)
class ProductionOrderShiftKpi:
segments: tuple[ProductionOrderSegment, ...]
average_speed_m_min: float | None
material_consumption_kg: float | None
@dataclass(frozen=True, slots=True)
class ProductionOrderShift:
production_order: str
machine_name: str
workplace: str
site: str
timezone: ZoneInfo
date: date
shift: Literal["early", "late", "night"]
shift_start: datetime
shift_end: datetime
first_confirmation: datetime
last_confirmation: datetime
produced_m2: float
segments: tuple[ProductionOrderSegment, ...] = ()
average_speed_m_min: float | None = None
material_consumption_kg: float | None = None
@dataclass(frozen=True, slots=True)
class ProductionOrderDetail:
production_order: str
placements: tuple[ProductionOrderPlacement, ...]
shifts: tuple[ProductionOrderShift, ...]
class ProductionOrderService:
"""Resolve workplace and site timezone before assigning confirmation timestamps."""
def __init__(self, gateway: ProductionOrderReader,
machines: Mapping[str, ShiftReportMachineConfig], *,
speed: ShiftSpeedService | None = None,
materials: ShiftMaterialService | None = None,
channel_materials: ShiftChannelMaterialService | None = None,
material_allocators: Mapping[str, MaterialAllocator] | None = None) -> None:
self.gateway = gateway
self.speed = speed
self.materials = materials
self.channel_materials = channel_materials
self.material_allocators = dict(material_allocators or {})
self.machines = dict(machines)
workplace_map = defaultdict(list)
for name, config in machines.items():
workplace_map[config.erp_workplace].append((name, config))
self._workplaces = dict(workplace_map)
def _machine(self, workplace: str):
matches = self._workplaces.get(workplace, ())
return matches[0] if len(matches) == 1 else None
def _placement(self, workplace: str, article_number: str | None,
article_description: str | None, first: datetime,
last: datetime) -> ProductionOrderPlacement:
resolved = self._machine(workplace)
status = ("ambiguous" if len(self._workplaces.get(workplace, ())) > 1 else "unknown")
return ProductionOrderPlacement(
workplace=workplace, machine_name=resolved[0] if resolved else None,
site=resolved[1].site if resolved else None,
timezone=resolved[1].timezone if resolved else None,
article_number=article_number, article_description=article_description,
first_confirmation_local=first, last_confirmation_local=last,
mapping_status="configured" if resolved else status,
)
def search(self, query: str, *, limit: int = 25) -> tuple[ProductionOrderSearchResult, ...]:
query = _order_input(query)
if type(limit) is not int or not 1 <= limit <= 100:
raise ValueError("limit must be between 1 and 100")
groups = self.gateway.search_orders(query, limit=limit)
by_order = defaultdict(list)
for group in groups:
by_order[group.production_order].append(self._placement(
group.workplace, group.article_number, group.article_description,
group.first_confirmation_local, group.last_confirmation_local))
orders = sorted(by_order, key=lambda order: (order != query, order))[:limit]
return tuple(ProductionOrderSearchResult(
order, tuple(sorted(by_order[order], key=lambda placement: (
placement.workplace, placement.article_number or "",
placement.article_description or "")))) for order in orders)
def detail(self, production_order: str) -> ProductionOrderDetail | None:
order = _order_input(production_order)
rows = self.gateway.get_order_confirmations(order)
if not rows:
return None
placements = defaultdict(list)
shifts = defaultdict(list)
for row in rows:
if row.production_order != order:
raise ValueError("ERP returned a different production order")
placements[(row.workplace, row.article_number,
row.article_description)].append(row)
resolved = self._machine(row.workplace)
if resolved is None:
continue
name, config = resolved
timestamp = row.timestamp_local.replace(tzinfo=config.timezone, fold=0)
day, shift, start, end = shift_containing(timestamp, config.timezone)
shifts[(name, day, shift, start, end)].append(row)
place_models = tuple(self._placement(workplace, article, description,
min(row.timestamp_local for row in grouped),
max(row.timestamp_local for row in grouped))
for (workplace, article, description), grouped in sorted(
placements.items(), key=lambda item: tuple(
value or "" for value in item[0])))
shift_models = []
for (name, day, shift, start, end), grouped in shifts.items():
config = self._machine(grouped[0].workplace)[1]
stamps = [row.timestamp_local.replace(tzinfo=config.timezone, fold=0)
for row in grouped]
shift_models.append(ProductionOrderShift(
production_order=order, machine_name=name, workplace=config.erp_workplace,
site=config.site, timezone=config.timezone, date=day, shift=shift,
shift_start=start, shift_end=end,
first_confirmation=min(stamps, key=lambda value: value.astimezone(UTC)),
last_confirmation=max(stamps, key=lambda value: value.astimezone(UTC)),
produced_m2=fsum(row.feedback_quantity_m2 for row in grouped),
))
shift_models.sort(key=lambda item: (item.shift_start.astimezone(UTC),
item.machine_name))
enriched = []
for item in shift_models:
kpi = self.for_shift(machine_name=item.machine_name, start=item.shift_start,
end=item.shift_end, orders=(item.production_order,))[
item.production_order]
enriched.append(replace(item, segments=kpi.segments,
average_speed_m_min=kpi.average_speed_m_min,
material_consumption_kg=kpi.material_consumption_kg))
return ProductionOrderDetail(order, place_models, tuple(enriched))
def for_shift(self, *, machine_name: str, start: datetime, end: datetime,
orders: tuple[str, ...],
allocated_shift_materials: ShiftMaterialSummary | None = None,
) -> dict[str, ProductionOrderShiftKpi]:
"""Attribute one machine shift to all requested FAs with shared segmentation."""
if machine_name not in self.machines:
raise ValueError("Unknown machine")
if not orders:
return {}
config = self.machines[machine_name]
confirmations = self.gateway.get_confirmations(
workplace=config.erp_workplace, start=start, end=end, timezone=config.timezone)
by_order = _segments_by_order(
confirmations, workplace=config.erp_workplace, timezone=config.timezone,
start=start, end=end)
allocator = self.material_allocators.get(machine_name)
allocated_totals = None
if allocator is not None and config.material is not None:
try:
if allocated_shift_materials is None:
service = (self.channel_materials if config.material.mode == "channel"
else self.materials)
if service is not None:
measured = service.summarize(
machine_id=config.machine_id,
calculation_ids=config.material.calculation_ids,
start=start, end=end,
)
allocated_shift_materials = allocator.allocate(measured)
if allocated_shift_materials is not None:
allocated_totals = allocator.totals_by_order(allocated_shift_materials)
except (ShiftMaterialReadError, ErpReadError):
allocated_totals = None
result = {}
for order in dict.fromkeys(orders):
segments = by_order.get(order, ())
if allocator is not None:
material = allocated_totals.get(order) if allocated_totals is not None else None
elif segments:
material = self._material_for_segments(config, segments)
else:
material = None
result[order] = ProductionOrderShiftKpi(
segments=segments,
average_speed_m_min=self._speed_for_segments(config, segments) if segments
else None,
material_consumption_kg=material,
)
return result
def _speed_for_segments(self, config: ShiftReportMachineConfig,
segments: tuple[ProductionOrderSegment, ...]) -> float | None:
if config.speed is None or self.speed is None:
return None
try:
summaries = [self.speed.summarize(config=config.speed, start=part.start,
end=part.end) for part in segments]
except ExplorationError:
return None
count = sum(summary.active_sample_count for summary in summaries)
if count == 0:
return None
return fsum(summary.average_line_speed_m_min * (summary.active_sample_count / count)
for summary in summaries if summary.active_sample_count)
def _material_for_segments(self, config: ShiftReportMachineConfig,
segments: tuple[ProductionOrderSegment, ...]) -> float | None:
if config.material is None:
return None
service = (self.channel_materials if config.material.mode == "channel"
else self.materials)
if service is None:
return None
try:
measured = [service.summarize(
machine_id=config.machine_id,
calculation_ids=config.material.calculation_ids,
start=part.start, end=part.end,
) for part in segments]
except (ShiftMaterialReadError, ErpReadError):
return None
return fsum(summary.total_consumption_kg for summary in measured)
def _segments_by_order(
confirmations: list[ProductionConfirmation], *, workplace: str, timezone: ZoneInfo,
start: datetime, end: datetime,
) -> dict[str, tuple[ProductionOrderSegment, ...]]:
"""Partition one shift at midpoints between adjacent FA confirmation runs."""
first = start.astimezone(UTC)
last = end.astimezone(UTC)
ordered = sorted(
((row.timestamp.astimezone(UTC), row.production_order) for row in confirmations
if row.workplace == workplace and row.is_finished_goods
and first <= row.timestamp.astimezone(UTC) < last),
key=lambda entry: (entry[0], entry[1]),
)
if not ordered:
return {}
runs = []
for stamp, order in ordered:
if not runs or runs[-1][0] != order:
runs.append([order, stamp, stamp])
else:
runs[-1][2] = stamp
boundaries = [first]
for before, after in zip(runs, runs[1:]):
midpoint = before[2] + (after[1] - before[2]) / 2
boundaries.append(max(first, min(midpoint, last)))
boundaries.append(last)
by_order = defaultdict(list)
for index, run in enumerate(runs):
if boundaries[index] < boundaries[index + 1]:
by_order[run[0]].append(ProductionOrderSegment(
boundaries[index].astimezone(timezone),
boundaries[index + 1].astimezone(timezone)))
return {order: tuple(segments) for order, segments in by_order.items()}
def _order_input(value: str) -> str:
if (not isinstance(value, str) or not value.strip() or "\x00" in value
or len(value.strip()) > 80):
raise ValueError("production order must be 1–80 non-NUL characters")
return value.strip()
@@ -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,35 @@
"""Compose historical ERP reads with pure shift-production aggregation."""
from datetime import datetime
from typing import Protocol
from zoneinfo import ZoneInfo
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,
timezone: ZoneInfo | None = None,
) -> list[ProductionConfirmation]: ...
class ShiftProductionService:
def __init__(self, gateway: ProductionConfirmationReader) -> None:
self.gateway = gateway
def summarize(
self, *, workplace: str, start: datetime, end: datetime,
timezone: ZoneInfo | None = None,
) -> ShiftProductionSummary:
workplace = validate_shift_window(workplace=workplace, start=start, end=end)
kwargs = {"workplace": workplace, "start": start, "end": end}
if timezone is not None:
kwargs["timezone"] = timezone
confirmations = self.gateway.get_confirmations(**kwargs)
return aggregate_shift_production(confirmations, workplace=workplace, start=start, end=end)
@@ -0,0 +1,104 @@
"""Sequential composition of validated services; mandatory failures propagate."""
from collections.abc import Mapping
from dataclasses import replace
from datetime import datetime
from types import MappingProxyType
from typing import Protocol
from production_analytics.calculations.shift_material import ShiftMaterialSummary
from production_analytics.calculations.shift_report import ShiftReport
from production_analytics.calculations.shift_speed import validate_speed_window
from production_analytics.service.production_order import ProductionOrderService
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 ShiftMaterialAllocator(Protocol):
def allocate(self, measured: ShiftMaterialSummary) -> ShiftMaterialSummary: ...
class ShiftReportService:
def __init__(
self,
*,
machines: Mapping[str, ShiftReportMachineConfig],
production: ShiftProductionService,
downtime: ShiftDowntimeService,
materials: ShiftMaterialService,
channel_materials: ShiftChannelMaterialService,
speed: ShiftSpeedService,
material_allocators: Mapping[str, ShiftMaterialAllocator] | None = None,
order_kpis: ProductionOrderService | None = None,
) -> None:
self.machines = MappingProxyType(dict(machines))
self.production = production
self.downtime = downtime
self.materials = materials
self.channel_materials = channel_materials
self.speed = speed
self.material_allocators = MappingProxyType(dict(material_allocators or {}))
self.order_kpis = order_kpis
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(config.timezone), end.astimezone(config.timezone)
production = self.production.summarize(
workplace=config.erp_workplace,
start=start,
end=end,
timezone=config.timezone,
) if config.capabilities.production else None
downtime = (self.downtime.summarize(machine_id=config.machine_id, start=start, end=end)
if config.capabilities.downtime else None)
materials = None
if config.material is not None:
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,
)
if machine_name in self.material_allocators:
materials = self.material_allocators[machine_name].allocate(materials)
speed = (self.speed.summarize(config=config.speed, start=start, end=end)
if config.speed is not None else None)
if (production is not None and production.items and self.order_kpis is not None
and (config.speed is not None or config.material is not None)):
kpis = self.order_kpis.for_shift(
machine_name=machine_name, start=start, end=end,
orders=tuple(item.production_order for item in production.items),
allocated_shift_materials=(materials if machine_name in self.material_allocators
else None),
)
production = replace(production, items=tuple(
replace(item,
average_speed_m_min=kpis[item.production_order].average_speed_m_min,
material_consumption_kg=kpis[item.production_order].material_consumption_kg)
for item in production.items
))
return ShiftReport(
machine_name=machine_name,
machine_id=config.machine_id,
display_name=config.display_name,
site=config.site,
timezone=config.timezone,
start=start,
end=end,
production=production,
downtime=downtime,
materials=materials,
speed=speed,
)
@@ -0,0 +1,231 @@
"""Strict, self-contained configuration for shift-report composition."""
from collections.abc import Mapping
from dataclasses import dataclass
from pathlib import Path
from types import MappingProxyType
from typing import Literal
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
import yaml
from production_analytics.calculations.shift_speed import NumericDwellGate, ShiftSpeedConfig
@dataclass(frozen=True, slots=True)
class ShiftReportSiteConfig:
display_name: str
timezone: ZoneInfo
def __post_init__(self) -> None:
_text(self.display_name, "site.display_name")
if not isinstance(self.timezone, ZoneInfo):
raise ValueError("site.timezone must be a valid IANA timezone")
@dataclass(frozen=True, slots=True)
class ShiftReportCapabilities:
production: bool
downtime: bool
material: bool
speed: bool
def __post_init__(self) -> None:
if any(type(value) is not bool for value in (
self.production, self.downtime, self.material, self.speed,
)):
raise ValueError("capabilities must contain booleans")
if not any((self.production, self.downtime, self.material, self.speed)):
raise ValueError("at least one capability must be enabled")
@dataclass(frozen=True, slots=True)
class ShiftReportMaterialConfig:
mode: Literal["cumulative", "channel"]
calculation_ids: tuple[str, ...]
allocation: Literal["none", "erp_fiber_share"] = "none"
def __post_init__(self) -> None:
if self.mode not in ("cumulative", "channel"):
raise ValueError("material.mode must be cumulative or channel")
if self.allocation not in ("none", "erp_fiber_share"):
raise ValueError("material.allocation must be none or erp_fiber_share")
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:
display_name: str
site: str
machine_id: str | None
erp_workplace: str
capabilities: ShiftReportCapabilities
timezone: ZoneInfo
material: ShiftReportMaterialConfig | None = None
speed: ShiftSpeedConfig | None = None
def __post_init__(self) -> None:
for name in ("display_name", "site", "erp_workplace"):
_text(getattr(self, name), name)
if not isinstance(self.timezone, ZoneInfo):
raise ValueError("machine timezone must be a valid IANA timezone")
if not isinstance(self.capabilities, ShiftReportCapabilities):
raise ValueError("capabilities must be a ShiftReportCapabilities")
if self.machine_id is not None:
_text(self.machine_id, "machine_id")
elif any((self.capabilities.downtime, self.capabilities.material,
self.capabilities.speed)):
raise ValueError("machine_id is required for downtime, material, or speed")
if self.capabilities.material != (self.material is not None):
raise ValueError("material configuration must match material capability")
if self.capabilities.speed != (self.speed is not None):
raise ValueError("speed configuration must match speed capability")
if self.material is not None and not isinstance(self.material, ShiftReportMaterialConfig):
raise ValueError("material must be a ShiftReportMaterialConfig")
if self.speed is not None:
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")
@dataclass(frozen=True, slots=True)
class ShiftReportConfig:
sites: Mapping[str, ShiftReportSiteConfig]
machines: Mapping[str, ShiftReportMachineConfig]
def __post_init__(self) -> None:
object.__setattr__(self, "sites", MappingProxyType(dict(self.sites)))
object.__setattr__(self, "machines", MappingProxyType(dict(self.machines)))
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_config(path: str | Path) -> ShiftReportConfig:
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, {"sites", "machines"}, "Shift-report configuration")
raw_sites = document["sites"]
if not isinstance(raw_sites, dict) or not raw_sites:
raise ValueError("sites must be a non-empty mapping")
sites = {}
for key, entry in raw_sites.items():
_text(key, "site key")
entry = _fields(entry, {"display_name", "timezone"}, f"site {key}")
_text(entry["timezone"], "site.timezone")
try:
timezone = ZoneInfo(entry["timezone"])
except (ZoneInfoNotFoundError, ValueError, TypeError) as exc:
raise ValueError("site.timezone must be a valid IANA timezone") from exc
sites[key] = ShiftReportSiteConfig(entry["display_name"], timezone)
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")
required = {"display_name", "site", "erp_workplace", "capabilities"}
if not isinstance(entry, dict) or not required <= set(entry) or set(entry) - (
required | {"machine_id", "material", "speed"}
):
raise ValueError(f"{name} has missing or unknown fields")
capabilities = _fields(entry["capabilities"],
{"production", "downtime", "material", "speed"},
"capabilities")
capabilities = ShiftReportCapabilities(**capabilities)
_text(entry["site"], "site")
if entry["site"] not in sites:
raise ValueError(f"{name} references an unknown site")
if capabilities.material != ("material" in entry):
raise ValueError("material configuration must match material capability")
if capabilities.speed != ("speed" in entry):
raise ValueError("speed configuration must match speed capability")
material = None
if capabilities.material:
material_entry = entry["material"]
if not isinstance(material_entry, dict) or not {"mode", "calculation_ids"} <= set(
material_entry
) or set(material_entry) - {"mode", "calculation_ids", "allocation"}:
raise ValueError("material has missing or unknown fields")
ids = material_entry["calculation_ids"]
if not isinstance(ids, list):
raise ValueError("material.calculation_ids must be a list")
material = ShiftReportMaterialConfig(
material_entry["mode"], tuple(ids), material_entry.get("allocation", "none")
)
speed = None
if capabilities.speed:
speed_entry = entry["speed"]
required_speed = {"signal_ref", "signal", "unit"}
optional_speed = {"production_gate_m_min", "running_signal_ref", "running_when",
"numeric_dwell_gate"}
if (not isinstance(speed_entry, dict) or not required_speed <= set(speed_entry)
or set(speed_entry) - (required_speed | optional_speed)):
raise ValueError("speed has missing or unknown fields")
if "running_when" in speed_entry and not speed_entry.get("running_signal_ref"):
raise ValueError("speed.running_when requires running_signal_ref")
dwell = None
if "numeric_dwell_gate" in speed_entry:
dwell_entry = _fields(
speed_entry["numeric_dwell_gate"],
{"signal_ref", "threshold", "comparison", "minimum_duration_seconds"},
"numeric_dwell_gate",
)
dwell = NumericDwellGate(**dwell_entry)
speed = ShiftSpeedConfig(
machine_id=entry.get("machine_id"), speed_signal_ref=speed_entry["signal_ref"],
signal=speed_entry["signal"], unit=speed_entry["unit"],
production_gate_m_min=speed_entry.get("production_gate_m_min"),
running_signal_ref=speed_entry.get("running_signal_ref"),
running_when=speed_entry.get("running_when", True),
numeric_dwell_gate=dwell,
)
result[name] = ShiftReportMachineConfig(
display_name=entry["display_name"], site=entry["site"],
machine_id=entry.get("machine_id"), erp_workplace=entry["erp_workplace"],
capabilities=capabilities, timezone=sites[entry["site"]].timezone,
material=material, speed=speed,
)
ids = [config.machine_id for config in result.values() if config.machine_id is not None]
if len(set(ids)) != len(ids):
raise ValueError("Shift-report machine IDs must be unique")
return ShiftReportConfig(sites, result)
def load_shift_report_machines(path: str | Path) -> dict[str, ShiftReportMachineConfig]:
"""Compatibility view used by report entry points and historical reconciliation."""
return dict(load_shift_report_config(path).machines)
@@ -0,0 +1,60 @@
"""Construct read-only sources for one explicit shift report."""
from collections.abc import Mapping
from production_analytics.enlyze.exploration import ExplorationClient, ExplorationSettings
from production_analytics.enlyze.gateway import EnlyzeApiGateway
from production_analytics.erp import (
ErpFiberBookingGateway,
ErpProductionConfirmationGateway,
ErpSettings,
)
from production_analytics.service.fiber_allocation import K7FiberAllocationService
from production_analytics.service.postgres_downtime import PostgresDowntimeRepository
from production_analytics.service.postgres_material import PostgresSettings
from production_analytics.service.postgres_shift_material import (
PostgresShiftChannelMaterialRepository,
PostgresShiftMaterialRepository,
)
from production_analytics.service.production_order import ProductionOrderService
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 import ShiftReportService
from production_analytics.service.shift_report_config import ShiftReportMachineConfig
from production_analytics.service.shift_speed import ShiftSpeedService
def build_shift_report_service(
machines: Mapping[str, ShiftReportMachineConfig],
environment: Mapping[str, str],
) -> ShiftReportService:
postgres = PostgresSettings.from_environment(environment)
erp = ErpSettings.from_environment(environment)
enlyze = ExplorationSettings.from_environment(environment)
allocators = {
name: K7FiberAllocationService(ErpFiberBookingGateway(erp))
for name, config in machines.items()
if config.material is not None and config.material.allocation == "erp_fiber_share"
}
confirmation_gateway = ErpProductionConfirmationGateway(erp)
materials = ShiftMaterialService(PostgresShiftMaterialRepository(postgres))
channel_materials = ShiftChannelMaterialService(
PostgresShiftChannelMaterialRepository(postgres))
speed = ShiftSpeedService(EnlyzeApiGateway(ExplorationClient(enlyze)))
order_kpis = ProductionOrderService(
confirmation_gateway, machines, speed=speed, materials=materials,
channel_materials=channel_materials, material_allocators=allocators)
return ShiftReportService(
machines=machines,
material_allocators=allocators,
order_kpis=order_kpis,
production=ShiftProductionService(confirmation_gateway),
downtime=ShiftDowntimeService(PostgresDowntimeRepository(postgres)),
materials=materials,
channel_materials=channel_materials,
speed=speed,
)
@@ -0,0 +1,41 @@
"""Compose bounded ENLYZE speed reads with the pure running-speed KPI."""
from datetime import UTC, datetime, timedelta
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,
running_signal_ref: str | None = None,
numeric_gate_signal_ref: str | None = None,
) -> 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)
kwargs = {"machine_id": config.machine_id, "speed_signal_ref": config.speed_signal_ref,
"start": start, "end": end}
if config.running_signal_ref is not None:
kwargs["running_signal_ref"] = config.running_signal_ref
if config.numeric_dwell_gate is not None:
kwargs["numeric_gate_signal_ref"] = config.numeric_dwell_gate.signal_ref
dwell = timedelta(seconds=config.numeric_dwell_gate.minimum_duration_seconds)
kwargs["start"] = start.astimezone(UTC) - dwell
kwargs["end"] = end.astimezone(UTC) + dwell
samples = self.gateway.get_speed_samples(**kwargs)
return aggregate_shift_speed(samples, config=config, start=start, end=end)
+193
View File
@@ -0,0 +1,193 @@
"""Read-only live shift-report WSGI interface; no report cache or persistence."""
import argparse
import os
from collections.abc import Callable, Mapping
from datetime import UTC, datetime
from pathlib import Path
from urllib.parse import parse_qs
from wsgiref.simple_server import make_server
from production_analytics.calculations.shift_report import (
most_recent_completed_shift,
shift_report_window,
)
from production_analytics.presentation.production_order_html import render_detail, render_search
from production_analytics.presentation.shift_report import render_pdf
from production_analytics.presentation.shift_report_html import render_page
from production_analytics.service.shift_report_config import load_shift_report_config
from production_analytics.service.shift_report_runtime import build_shift_report_service
SHIFT_LABELS = {"early": "Frühschicht", "late": "Spätschicht", "night": "Nachtschicht"}
def create_app(machines: Mapping, service_factory: Callable, *, sites: Mapping | None = None,
clock=None, order_service_factory: Callable | None = None):
"""Inject the configured service factory and clock without connecting at startup."""
clock = clock or (lambda: datetime.now(UTC))
def app(environ, start_response):
headers = [("Cache-Control", "no-store"), ("X-Content-Type-Options", "nosniff")]
status = "200 OK"
content_type = "text/html; charset=utf-8"
path = environ.get("PATH_INFO", "/")
if path in ("/orders", "/order"):
status, payload = _order_response(environ, path, order_service_factory)
if status == "405 Method Not Allowed":
headers.append(("Allow", "GET"))
payload = payload.encode("utf-8")
headers.extend([("Content-Type", content_type), ("Content-Length", str(len(payload)))])
start_response(status, headers)
return [payload]
now = clock()
machine = next(iter(machines))
timezone = machines[machine].timezone
day, shift = most_recent_completed_shift(now, timezone)
error = None
report = None
generated_at = None
if path != "/":
status, error = "404 Not Found", "Seite nicht gefunden."
elif environ.get("REQUEST_METHOD", "GET") != "GET":
status, error = "405 Method Not Allowed", "Diese Anfrage wird nicht unterstützt."
headers.append(("Allow", "GET"))
else:
try:
params = parse_qs(
environ.get("QUERY_STRING", ""), keep_blank_values=True, max_num_fields=10
)
if any(len(values) != 1 for values in params.values()):
raise ValueError
from datetime import date
machine = params.get("machine", [machine])[0]
if machine not in machines:
raise ValueError
timezone = machines[machine].timezone
default_day, default_shift = most_recent_completed_shift(now, timezone)
day = date.fromisoformat(params.get("date", [default_day.isoformat()])[0])
shift = params.get("shift", [default_shift])[0]
output = params.get("format", ["html"])[0]
if shift not in SHIFT_LABELS:
raise ValueError
if output not in ("html", "pdf"):
raise ValueError
start, end = shift_report_window(day, shift, timezone)
except (ValueError, OverflowError):
status = "400 Bad Request"
error = "Ungültige Auswahl. Bitte Datum, Schicht und Maschine prüfen."
else:
try:
report = service_factory().build(machine_name=machine, start=start, end=end)
generated_at = clock().astimezone(timezone)
if output == "pdf":
payload = render_pdf(report)
content_type = "application/pdf"
# Filename excludes externally configured machine names.
headers.append(
(
"Content-Disposition",
f'attachment; filename="Schichtbericht-{day}-{shift}.pdf"',
)
)
else:
payload = None
except Exception:
status = "503 Service Unavailable"
error = (
"Schichtbericht konnte nicht erstellt werden. "
"Bitte später erneut versuchen oder die Datenquellen prüfen lassen."
)
report = None
if error or content_type != "application/pdf":
payload = render_page(
machines=machines,
sites=sites,
labels=SHIFT_LABELS,
day=day,
shift=shift,
machine=machine,
report=report,
generated_at=generated_at,
error=error,
).encode("utf-8")
headers.extend([("Content-Type", content_type), ("Content-Length", str(len(payload)))])
start_response(status, headers)
return [payload]
return app
def _order_response(environ, path: str, service_factory: Callable | None) -> tuple[str, str]:
if environ.get("REQUEST_METHOD", "GET") != "GET":
return "405 Method Not Allowed", render_search(error="Nur GET-Anfragen sind erlaubt.")
try:
params = parse_qs(environ.get("QUERY_STRING", ""), keep_blank_values=True,
max_num_fields=10)
key = "q" if path == "/orders" else "production_order"
if set(params) - {key} or any(len(values) != 1 for values in params.values()):
raise ValueError
if path == "/orders" and key not in params:
return "200 OK", render_search()
value = params[key][0].strip()
if not value or "\x00" in value or len(value) > 80:
raise ValueError
except (ValueError, KeyError):
message = "Bitte eine gültige Fertigungsauftragsnummer eingeben."
if path == "/orders":
return "400 Bad Request", render_search(error=message)
return "400 Bad Request", render_detail(detail=None, error=message)
try:
if service_factory is None:
raise RuntimeError("Order service unavailable")
service = service_factory()
if path == "/orders":
return "200 OK", render_search(query=value, results=service.search(value),
searched=True)
detail = service.detail(value)
return ("200 OK" if detail is not None else "404 Not Found"), render_detail(detail=detail)
except Exception:
message = "Fertigungsauftrag konnte nicht geladen werden. Bitte später erneut versuchen."
if path == "/orders":
return "503 Service Unavailable", render_search(query=value, error=message)
return "503 Service Unavailable", render_detail(detail=None, error=message)
def main(argv=None):
from production_analytics.enlyze.exploration import load_secret_file
parser = argparse.ArgumentParser(description="Live-Schichtberichte")
parser.add_argument("--host", default="127.0.0.1")
parser.add_argument(
"--port", type=int, default=int(os.environ.get("SHIFT_REPORT_PORT", "8087"))
)
parser.add_argument("--config", type=Path, default=Path("config/shift-report-machines.yaml"))
parser.add_argument("--secrets-file", type=Path, default=Path("secrets/enlyze.env"))
parser.add_argument("--erp-secrets-file", type=Path, default=Path("secrets/erp.env"))
parser.add_argument("--db-secrets-file", type=Path, default=Path("secrets/postgres.env"))
args = parser.parse_args(argv)
config = load_shift_report_config(args.config)
machines = config.machines
def service():
environment = dict(os.environ)
for path in (args.secrets_file, args.erp_secrets_file, args.db_secrets_file):
environment.update(load_secret_file(path))
return build_shift_report_service(machines, environment)
def order_service():
environment = dict(os.environ)
for path in (args.secrets_file, args.erp_secrets_file, args.db_secrets_file):
environment.update(load_secret_file(path))
sources = build_shift_report_service(machines, environment)
return sources.order_kpis
app = create_app(machines, service, sites=config.sites,
order_service_factory=order_service)
with make_server(args.host, args.port, app) as server:
print(f"Schichtberichte: http://{args.host}:{args.port}/", flush=True)
server.serve_forever()
if __name__ == "__main__":
main()
+105 -1
View File
@@ -16,6 +16,7 @@ from production_analytics.calculations.material_consumption import (
area_application_rate_kg_per_hour, area_application_rate_kg_per_hour,
) )
from production_analytics.enlyze.gateway import EnlyzeApiGateway, EnlyzeProductionRun from production_analytics.enlyze.gateway import EnlyzeApiGateway, EnlyzeProductionRun
from production_analytics.erp import ErpReadError
from production_analytics.service.material_context import ErpNominalWidthProvider from production_analytics.service.material_context import ErpNominalWidthProvider
from production_analytics.service.material_polling import MaterialPollingService from production_analytics.service.material_polling import MaterialPollingService
from production_analytics.service.material_state_store import JsonMaterialStateStore from production_analytics.service.material_state_store import JsonMaterialStateStore
@@ -69,7 +70,7 @@ def test_missing_or_invalid_spreader_fails(bad):
) )
def width_provider(): def width_provider(fallback_nominal_width_m=None):
erp = Mock() erp = Mock()
erp.get_current_workplace_status.return_value = SimpleNamespace( erp.get_current_workplace_status.return_value = SimpleNamespace(
workplace='Bento 1', production_order='12026000814', article_number='180305', workplace='Bento 1', production_order='12026000814', article_number='180305',
@@ -77,9 +78,111 @@ def width_provider():
) )
return ErpNominalWidthProvider( return ErpNominalWidthProvider(
erp, workplace='Bento 1', format_template='Bento 1-{production_order}', erp, workplace='Bento 1', format_template='Bento 1-{production_order}',
fallback_nominal_width_m=fallback_nominal_width_m,
) )
def test_erp_width_takes_priority_over_fallback(caplog):
provider = width_provider(5.0)
provider.gateway.get_current_workplace_status.return_value.article_description = '4,00 x 40 m'
assert provider('Bento 1-12026000814') == 4.0
assert not caplog.records
@pytest.mark.parametrize('fallback', [None, 5.0])
def test_combined_order_width_fallback(fallback, caplog):
provider = width_provider(fallback)
order = 'Bento 1-12026001005-Bento 1-12026001014'
if fallback is None:
with pytest.raises(ValueError, match='ERP context does not match the production order'):
provider(order)
assert not caplog.records
else:
assert provider(order) == 5.0
assert len(caplog.records) == 1
assert caplog.records[0].levelname == 'WARNING'
assert 'ERP nominal-width resolution failed' in caplog.text
assert order in caplog.text
assert 'fallback nominal width 5.0 m' in caplog.text
def test_fallback_warns_once_per_order_per_provider(caplog):
provider = width_provider(5.0)
first_order = 'Bento 1-12026001005-Bento 1-12026001014'
second_order = 'Bento 1-12026001015'
for order in (first_order, first_order, second_order, second_order, first_order):
assert provider(order) == 5.0
assert len(caplog.records) == 2
assert all(record.levelname == 'WARNING' for record in caplog.records)
assert first_order in caplog.records[0].getMessage()
assert second_order in caplog.records[1].getMessage()
# A fresh provider has its own warning history.
assert width_provider(5.0)(first_order) == 5.0
assert len(caplog.records) == 3
def test_erp_resolution_still_runs_after_fallback(caplog):
provider = width_provider(5.0)
order = 'Bento 1-12026000814'
status = provider.gateway.get_current_workplace_status.return_value
status.article_description = None
assert provider(order) == 5.0
status.article_description = '4,00 x 40 m'
assert provider(order) == 4.0
status.article_description = None
assert provider(order) == 5.0
assert len(caplog.records) == 1
@pytest.mark.parametrize('failure', ['missing_status', 'missing_width', 'read_error'])
@pytest.mark.parametrize('fallback', [None, 5.0])
def test_other_erp_width_failures(failure, fallback):
provider = width_provider(fallback)
gateway = provider.gateway
if failure == 'missing_status':
gateway.get_current_workplace_status.return_value = None
elif failure == 'missing_width':
gateway.get_current_workplace_status.return_value.article_description = None
else:
gateway.get_current_workplace_status.side_effect = ErpReadError('ERP read failed')
if fallback is None:
with pytest.raises(ErpReadError if failure == 'read_error' else ValueError):
provider('Bento 1-12026000814')
else:
assert provider('Bento 1-12026000814') == 5.0
@pytest.mark.parametrize('value', [0, -1, float('nan'), float('inf'), -float('inf'),
True, '5.0', None, [], {}])
def test_invalid_fallback_configuration(tmp_path, value):
with open('config/bento1-material-consumption.yaml') as stream:
document = yaml.safe_load(stream)
document['calculations'][0]['fallback_nominal_width_m'] = value
path = tmp_path / 'config.yaml'
path.write_text(yaml.safe_dump(document))
with pytest.raises(CalculationConfigError, match='fallback_nominal_width_m'):
load_material_calculation(path)
@pytest.mark.parametrize('path', [
'config/bento1-material-consumption.yaml',
'config/bento1-spreader3-material-consumption.yaml',
])
def test_bento_fallback_configuration(path):
assert load_material_calculation(path).fallback_nominal_width_m == 5.0
def test_direct_mass_rate_rejects_width_fallback(tmp_path):
with open('config/k7-material-consumption.yaml') as stream:
document = yaml.safe_load(stream)
document['calculations'][0]['fallback_nominal_width_m'] = 5.0
path = tmp_path / 'config.yaml'
path.write_text(yaml.safe_dump(document))
with pytest.raises(CalculationConfigError, match='width-based source mode'):
load_material_calculation(path)
@pytest.mark.parametrize('configured,returned', [ @pytest.mark.parametrize('configured,returned', [
('Bento 1', 'BENTO 1'), ('Bento 1', 'BENTO 1'),
('Bento 1', ' \tBENTO 1\n'), ('Bento 1', ' \tBENTO 1\n'),
@@ -195,6 +298,7 @@ def test_bento_rpm_bootstrap_and_persistent_resume(tmp_path, inter_run_gap_secon
def test_k7_config_defaults_remain_direct(): def test_k7_config_defaults_remain_direct():
config = load_material_calculation('config/k7-material-consumption.yaml') config = load_material_calculation('config/k7-material-consumption.yaml')
assert config.source_mode == 'direct_mass_rate' assert config.source_mode == 'direct_mass_rate'
assert config.fallback_nominal_width_m is None
assert config.rotational_speed_signal_refs == () assert config.rotational_speed_signal_refs == ()
assert config.application_signal_refs == () assert config.application_signal_refs == ()
assert config.gate_threshold == 0.5 assert config.gate_threshold == 0.5
+203 -1
View File
@@ -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)
]
+16 -1
View File
@@ -3,7 +3,7 @@ import json
import os import os
import tempfile import tempfile
import unittest import unittest
from contextlib import redirect_stdout from contextlib import redirect_stderr, redirect_stdout
from pathlib import Path from pathlib import Path
from unittest.mock import patch from unittest.mock import patch
@@ -12,6 +12,21 @@ from production_analytics.enlyze.exploration import ExplorationResponse
class CliTests(unittest.TestCase): class CliTests(unittest.TestCase):
def test_power_meter_config_error_returns_controlled_exit_code(self) -> None:
with tempfile.TemporaryDirectory() as temporary_directory:
missing_config = Path(temporary_directory) / "missing.yaml"
error_output = io.StringIO()
with redirect_stderr(error_output):
result = main([
"run", "power-meter", "--config", str(missing_config), "--meter", "B2",
"--start", "2026-10-01T10:00:00Z", "--end", "2026-10-01T10:10:00Z",
])
self.assertEqual(result, 2)
self.assertIn(
"Config/startup error: Cannot read power-meter configuration", error_output.getvalue()
)
@patch.dict(os.environ, {"ENLYZE_BASE_URL": "https://enlyze.example"}, clear=True) @patch.dict(os.environ, {"ENLYZE_BASE_URL": "https://enlyze.example"}, clear=True)
@patch("production_analytics.cli.__main__.ExplorationClient.get") @patch("production_analytics.cli.__main__.ExplorationClient.get")
def test_raw_prints_and_saves_sanitized_response(self, get_mock: object) -> None: def test_raw_prints_and_saves_sanitized_response(self, get_mock: object) -> None:
+95
View File
@@ -0,0 +1,95 @@
"""Configured downtime runners share the existing machine and order contracts."""
from datetime import timedelta
from pathlib import Path
import pytest
from production_analytics.context import build_enlyze_production_order
from production_analytics.service import downtime_runtime
from production_analytics.service.downtime_runtime import load_downtime_config
from production_analytics.service.shift_report_config import load_shift_report_config
ROOT = Path(__file__).resolve().parents[1]
NEW_RUNNERS = (
("e4", "E4", "12026001013", "E 4-12026001013"),
("gitter1", "Gitter 1", "82026400869", "Gitter 1-82026400869"),
("gitter2", "Gitter 2", "82026400909", "Gitter 2-82026400909"),
("gitter3", "Gitter 3", "82026400900", "Gitter 3-82026400900"),
("gitter4", "Gitter 4", "82026400876", "Gitter 4-82026400876"),
("k5", "K5", "82026400921", "K 5-82026400921"),
("secumat12", "Secumat 1/2", "82026400920", "Sec 1/2-82026400920"),
("secumat3", "Secumat 3", "82026400912", "Sec 3-82026400912"),
)
@pytest.mark.parametrize("slug,name,erp_order,enlyze_order", NEW_RUNNERS)
def test_new_downtime_config_matches_report_machine_and_verified_order(
slug, name, erp_order, enlyze_order,
):
config = load_downtime_config(ROOT / "config" / f"{slug}-downtime.yaml")
report_config = load_shift_report_config(ROOT / "config" / "shift-report-machines.yaml")
machine = report_config.machines[name]
assert (config.machine_id, config.erp_workplace) == (
machine.machine_id, machine.erp_workplace,
)
assert build_enlyze_production_order(erp_order, config.production_order_format) == enlyze_order
assert (config.poll_interval_seconds, config.lookback_hours,
config.full_reconciliation_hours, config.completion_tolerance_m2) == (
300, 48, 24, 0.001,
)
assert machine.capabilities.production and machine.capabilities.downtime
assert not machine.capabilities.material and machine.material is None
speed_enabled = name in {"Gitter 1", "Gitter 2", "Gitter 3", "Gitter 4", "K5"}
assert machine.capabilities.speed is speed_enabled
assert (machine.speed is not None) is speed_enabled
unit = ROOT / "deploy" / "systemd" / f"production-analytics-downtime-{slug}.service"
text = unit.read_text(encoding="utf-8")
assert f"--config {ROOT / 'config' / f'{slug}-downtime.yaml'}" in text
assert "run downtime-reconcile" in text
assert "--secrets-file" in text and "--erp-secrets-file" in text
def test_existing_downtime_configs_and_capabilities_are_unchanged():
machines = load_shift_report_config(ROOT / "config" / "shift-report-machines.yaml").machines
for slug, name in (("bento1", "B1"), ("e1", "E1"), ("k7", "K7")):
config = load_downtime_config(ROOT / "config" / f"{slug}-downtime.yaml")
assert config.machine_id == machines[name].machine_id
assert machines[name].capabilities.downtime
assert (config.poll_interval_seconds, config.lookback_hours,
config.full_reconciliation_hours, config.completion_tolerance_m2) == (
300, 48, 24, 0.001,
)
@pytest.mark.parametrize("slug,name,erp_order,enlyze_order", NEW_RUNNERS)
def test_existing_generic_runtime_builds_each_new_runner(
monkeypatch, slug, name, erp_order, enlyze_order,
):
monkeypatch.setattr(downtime_runtime, "load_secret_file", lambda path: {})
for settings in (downtime_runtime.ExplorationSettings,
downtime_runtime.ErpSettings, downtime_runtime.PostgresSettings):
monkeypatch.setattr(settings, "from_environment", lambda env: object())
runner = downtime_runtime.build_downtime_runner(
ROOT / "config" / f"{slug}-downtime.yaml",
secrets_file=ROOT / "secrets" / "enlyze.env",
erp_secrets_file=ROOT / "secrets" / "erp.env",
)
report_config = load_shift_report_config(ROOT / "config" / "shift-report-machines.yaml")
machine = report_config.machines[name]
assert runner.machine_id == runner.service.machine_id == machine.machine_id
assert runner.service.workplace == machine.erp_workplace
assert runner.interval == 300
assert runner.service.lookback == timedelta(hours=48)
assert runner.service.full_reconciliation_interval == timedelta(hours=24)
assert runner.service.tolerance == 0.001
assert build_enlyze_production_order(
erp_order, runner.service.production_order_format) == enlyze_order
def test_only_expected_machines_have_downtime_enabled():
machines = load_shift_report_config(ROOT / "config" / "shift-report-machines.yaml").machines
assert {name for name, config in machines.items() if config.capabilities.downtime} == {
"B1", "E1", "K7", *(name for _, name, _, _ in NEW_RUNNERS),
}
+76
View File
@@ -0,0 +1,76 @@
import traceback
from decimal import Decimal
from unittest.mock import MagicMock
import pytest
from test_erp_gateway import ENV
from production_analytics.erp import ErpFiberBookingGateway, ErpReadError, ErpSettings
@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 = [("12026000994 ", "41070418 ", "Fiber ", Decimal("6877.80"))]
return connect, connection, cursor
def gateway():
return ErpFiberBookingGateway(ErpSettings.from_environment(ENV))
def test_order_query_is_parameterized_positive_and_not_shift_bounded(db):
connect, connection, cursor = db
rows = gateway().get_fiber_bookings("12026000994")
assert len(rows) == 1
assert rows[0].production_order == "12026000994"
assert rows[0].material_number == "41070418"
assert rows[0].material_name == "Fiber"
assert rows[0].quantity_kg == 6877.8
sql, parameters = cursor.execute.call_args.args
assert parameters == ("12026000994",)
assert "[Fertigungsauftragsnummer] = %s" in sql
assert "[Fasermenge] > 0" in sql
assert "NULLIF(LTRIM(RTRIM([Rohstoffnummer])), '') IS NOT NULL" in sql
assert "Zeitstempel" not in sql
assert "12026000994" not in sql
connect.assert_called_once_with(
server="localhost",
port=49601,
database="NV_DWH",
user=ENV["ERP_DB_USER"],
password=ENV["ERP_DB_PASSWORD"],
login_timeout=10,
timeout=10,
)
connection.commit.assert_not_called()
connection.cursor.return_value.__exit__.assert_called_once()
connect.return_value.__exit__.assert_called_once()
def test_no_rows_returns_empty(db):
db[2].fetchall.return_value = []
assert gateway().get_fiber_bookings("123") == []
@pytest.mark.parametrize("order", [None, "", " ", "\x00"])
def test_invalid_order_rejected_before_connect(db, order):
with pytest.raises(ValueError):
gateway().get_fiber_bookings(order)
db[0].assert_not_called()
def test_read_failure_does_not_expose_credentials(db):
db[2].execute.side_effect = RuntimeError(ENV["ERP_DB_PASSWORD"])
with pytest.raises(ErpReadError, match="read failed") as caught:
gateway().get_fiber_bookings("123")
assert ENV["ERP_DB_PASSWORD"] not in "".join(traceback.format_exception(caught.value))
def test_invalid_numeric_row_rejected(db):
db[2].fetchall.return_value = [("123", "M1", "Fiber", float("nan"))]
with pytest.raises(ErpReadError, match="invalid row"):
gateway().get_fiber_bookings("123")
+17 -3
View File
@@ -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)
+335
View File
@@ -0,0 +1,335 @@
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
@pytest.mark.parametrize("timezone_name,expected_utc_hour", [
("Europe/Berlin", 6), ("Asia/Kuala_Lumpur", 0),
])
def test_explicit_site_timezone_interprets_naive_sql_rows(
db, timezone_name, expected_utc_hour,
):
timezone = ZoneInfo(timezone_name)
start = datetime(2026, 10, 19, 6, tzinfo=timezone)
end = datetime(2026, 10, 19, 14, tzinfo=timezone)
local_row = datetime(2026, 10, 19, 8, 20)
db[2].fetchall.return_value = [(*ROW[:2], local_row, *ROW[3:])]
confirmation = read(start=start.astimezone(UTC), end=end.astimezone(UTC),
timezone=timezone)[0]
assert db[2].execute.call_args.args[1] == (
"BENTO 1", datetime(2026, 10, 19, 6), datetime(2026, 10, 19, 14),
)
assert confirmation.timestamp == local_row.replace(tzinfo=timezone)
assert confirmation.timestamp.tzinfo is timezone
assert confirmation.timestamp.astimezone(UTC).hour == expected_utc_hour
def test_malaysia_evening_confirmation_remains_local_evening(db):
malaysia = ZoneInfo("Asia/Kuala_Lumpur")
local_row = datetime(2026, 10, 19, 18)
db[2].fetchall.return_value = [(*ROW[:2], local_row, *ROW[3:])]
confirmation = read(
start=datetime(2026, 10, 19, 14, tzinfo=malaysia),
end=datetime(2026, 10, 19, 22, tzinfo=malaysia), timezone=malaysia,
)[0]
assert confirmation.timestamp.hour == 18
assert confirmation.timestamp.astimezone(UTC) == datetime(2026, 10, 19, 10, tzinfo=UTC)
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()
+250
View File
@@ -0,0 +1,250 @@
from dataclasses import replace
from math import fsum
from unittest.mock import Mock
import pytest
from test_shift_report import END, START, composition
from production_analytics.calculations.fiber_allocation import (
FiberBooking,
allocate_fiber_materials,
)
from production_analytics.calculations.shift_material import ShiftMaterialSummary
from production_analytics.presentation.shift_report import (
MaterialPieBlock,
TableBlock,
present_report,
render_pdf,
)
from production_analytics.service.fiber_allocation import K7FiberAllocationService
ORDER = "12026000994"
NAMES = ("PP 1A, weiß, 6,0, hf - 90- Drittland", "PP 1A, weiß, 6,0, hf - 90")
BOOKINGS = (
FiberBooking(ORDER, "41070418", NAMES[0], 6878),
FiberBooking(ORDER, "41070419", NAMES[1], 3122),
)
def measured_item(order=f"K 7-{ORDER}", quantity=3468.77):
_, stubs, _, _ = composition("K7")
return replace(
stubs["materials"].result.items[0], production_order=order, consumption_kg=quantity
)
def test_ratios_allocate_measured_mass_without_rounding():
item = measured_item()
allocated = allocate_fiber_materials(item, BOOKINGS, erp_order=ORDER)
assert [value.material_number for value in allocated] == ["41070418", "41070419"]
assert [value.erp_booking_share for value in allocated] == pytest.approx([0.6878, 0.3122])
assert [value.consumption_kg for value in allocated] == pytest.approx(
[2385.819006, 1082.950994]
)
assert fsum(value.consumption_kg for value in allocated) == pytest.approx(item.consumption_kg)
assert allocated[0].consumption_kg != pytest.approx(item.consumption_kg * 0.69)
assert all(value.baseline_timestamp == item.baseline_timestamp for value in allocated)
assert all(value.end_timestamp == item.end_timestamp for value in allocated)
assert all(value.baseline_missing == item.baseline_missing for value in allocated)
assert item.material_number is None
def test_duplicate_bookings_aggregate_by_number_and_name():
allocated = allocate_fiber_materials(
measured_item(),
[
FiberBooking(ORDER, "M1", "Fiber", 20),
FiberBooking(ORDER, "M1", "Fiber", 30),
FiberBooking(ORDER, "M2", "Fiber", 50),
],
erp_order=ORDER,
)
assert len(allocated) == 2
assert [item.material_number for item in allocated] == ["M1", "M2"]
assert [item.erp_booking_share for item in allocated] == [0.5, 0.5]
@pytest.mark.parametrize(
"bookings",
[
[],
[FiberBooking(ORDER, "181900", "Product", 0)],
[
FiberBooking(ORDER, "M1", "Fiber", -1),
FiberBooking(ORDER, "", "Fiber", 10),
FiberBooking(ORDER, None, "Fiber", 10),
FiberBooking(ORDER, "M1", "Fiber", None),
],
],
)
def test_no_usable_bookings_preserves_unassigned_measured_item(bookings):
item = measured_item()
assert allocate_fiber_materials(item, bookings, erp_order=ORDER) == (item,)
def test_invalid_rows_ignored_and_single_material_has_full_share():
allocated = allocate_fiber_materials(
measured_item(),
[
FiberBooking(ORDER, "M1", "Fiber", 25),
FiberBooking(ORDER, "M2", "Fiber", 0),
FiberBooking(ORDER, "M3", "Fiber", -10),
FiberBooking(ORDER, " ", "Fiber", 100),
FiberBooking(ORDER, "M4", "Fiber", float("nan")),
FiberBooking("other", "M5", "Fiber", 1000),
],
erp_order=ORDER,
)
assert len(allocated) == 1
assert allocated[0].material_number == "M1"
assert allocated[0].erp_booking_share == 1
assert allocated[0].consumption_kg == 3468.77
def test_order_aware_service_preserves_totals_runs_and_caches_order_reads():
reader = Mock()
reader.get_fiber_bookings.side_effect = lambda order: (
BOOKINGS if order == ORDER else [FiberBooking(order, "M3", "Other fiber", 1)]
)
items = (
measured_item(quantity=100),
replace(measured_item(quantity=200), run_id="run2"),
measured_item("K 7-123", 400),
)
measured = ShiftMaterialSummary(items[0].machine_id, START, END, 700, items)
allocated = K7FiberAllocationService(reader).allocate(measured)
assert allocated.total_consumption_kg == measured.total_consumption_kg
assert fsum(item.consumption_kg for item in allocated.items) == pytest.approx(700)
assert len(allocated.items) == 5
assert allocated.items[-1].material_number == "M3"
assert allocated.items[-1].production_order == "K 7-123"
assert reader.get_fiber_bookings.call_count == 2
assert measured.items == items
@pytest.mark.parametrize("order", ["K 7-123-K 7-456", "unknown", ""])
def test_ambiguous_order_never_queries_or_invents_recipe(order):
reader = Mock()
item = measured_item(order)
measured = ShiftMaterialSummary(item.machine_id, START, END, item.consumption_kg, (item,))
allocated = K7FiberAllocationService(reader).allocate(measured)
assert allocated.items == measured.items
reader.get_fiber_bookings.assert_not_called()
@pytest.mark.parametrize("machine", ["B1", "E1", "K7"])
def test_report_wiring_applies_adapter_only_to_k7(machine):
service, stubs, _, _ = composition(machine)
reader = Mock()
reader.get_fiber_bookings.return_value = BOOKINGS
service.material_allocators = {"K7": K7FiberAllocationService(reader)}
stubs["materials"].result = (
replace(stubs["materials"].result, items=(measured_item(quantity=42),))
if machine == "K7"
else stubs["materials"].result
)
value = service.build(machine_name=machine, start=START, end=END)
if machine == "K7":
assert len(value.materials.items) == 2
reader.get_fiber_bookings.assert_called_once_with(ORDER)
else:
reader.get_fiber_bookings.assert_not_called()
assert (
value.materials is stubs["channel_materials" if machine == "E1" else "materials"].result
)
def test_same_allocation_behavior_for_differently_named_machine():
service, stubs, _, config = composition("K7")
service.machines = {"Synthetic": config}
reader = Mock()
reader.get_fiber_bookings.return_value = BOOKINGS
service.material_allocators = {"Synthetic": K7FiberAllocationService(reader)}
item = measured_item(quantity=42)
stubs["materials"].result = replace(stubs["materials"].result, items=(item,))
report = service.build(machine_name="Synthetic", start=START, end=END)
assert len(report.materials.items) == 2
assert sum(part.consumption_kg for part in report.materials.items) == pytest.approx(42)
reader.get_fiber_bookings.assert_called_once_with(ORDER)
def test_pdf_displays_whole_shares_and_estimation_note():
service, stubs, _, _ = composition("K7")
item = measured_item()
stubs["materials"].result = replace(
stubs["materials"].result, items=(item,), total_consumption_kg=item.consumption_kg
)
reader = Mock()
reader.get_fiber_bookings.return_value = BOOKINGS
service.material_allocators = {"K7": K7FiberAllocationService(reader)}
report = service.build(machine_name="K7", start=START, end=END)
blocks = present_report(report)
table = next(
block for block in blocks if isinstance(block, TableBlock) and "ERP-Anteil" in block.headers
)
rows = {row[2]: row for row in table.rows}
assert rows["41070418"][1:] == (NAMES[0], "41070418", "2.385,82 kg", "69%")
assert rows["41070419"][1:] == (NAMES[1], "41070419", "1.082,95 kg", "31%")
assert any(
getattr(block, "text", "")
== "Verbrauchsaufteilung geschätzt nach ERP-Buchungsverhältnis; Gesamtverbrauch aus ENLYZE."
for block in blocks
)
chart = next(block for block in blocks if isinstance(block, MaterialPieBlock))
assert fsum(chart.consumption_kg) == pytest.approx(3468.77)
def test_source_ratios_retain_precision_beyond_displayed_percentage():
bookings = (replace(BOOKINGS[0], quantity_kg=6877.8), replace(BOOKINGS[1], quantity_kg=3122.2))
allocated = allocate_fiber_materials(measured_item(), bookings, erp_order=ORDER)
assert [item.consumption_kg for item in allocated] == pytest.approx(
[2385.7496306, 1083.0203694]
)
assert [f"{item.erp_booking_share * 100:.0f}%" for item in allocated] == ["69%", "31%"]
assert fsum(item.consumption_kg for item in allocated) == pytest.approx(3468.77)
def test_pdf_keeps_different_order_shares_separate_and_combines_material_pie():
service, stubs, _, _ = composition("K7")
items = (measured_item(quantity=100), measured_item("K 7-123", 200))
stubs["materials"].result = replace(
stubs["materials"].result, items=items, total_consumption_kg=300
)
reader = Mock()
reader.get_fiber_bookings.side_effect = lambda order: (
BOOKINGS if order == ORDER else [replace(BOOKINGS[0], production_order=order)]
)
service.material_allocators = {"K7": K7FiberAllocationService(reader)}
report = service.build(machine_name="K7", start=START, end=END)
blocks = present_report(report)
table = next(
block for block in blocks if isinstance(block, TableBlock) and "ERP-Anteil" in block.headers
)
assert len(table.rows) == 3
assert {(row[0], row[-1]) for row in table.rows} == {
(f"K 7-{ORDER}", "69%"),
(f"K 7-{ORDER}", "31%"),
("K 7-123", "100%"),
}
chart = next(block for block in blocks if isinstance(block, MaterialPieBlock))
assert len(chart.labels) == 2
assert sorted(chart.consumption_kg) == pytest.approx([31.22, 268.78])
assert render_pdf(report) == render_pdf(report)
def test_missing_erp_data_keeps_pdf_unassigned_and_measured_total():
service, stubs, _, _ = composition("K7")
stubs["materials"].result = replace(
stubs["materials"].result, items=(measured_item(),), total_consumption_kg=3468.77
)
reader = Mock()
reader.get_fiber_bookings.return_value = []
service.material_allocators = {"K7": K7FiberAllocationService(reader)}
report = service.build(machine_name="K7", start=START, end=END)
table = next(
block
for block in present_report(report)
if isinstance(block, TableBlock) and "Materialname" in block.headers
)
assert table.rows == (("Materialzuordnung fehlt", "–", "3.468,77 kg"),)
assert report.materials.total_consumption_kg == 3468.77
+548
View File
@@ -0,0 +1,548 @@
from dataclasses import replace
from datetime import UTC, datetime
from types import SimpleNamespace
from unittest.mock import MagicMock
import pytest
from production_analytics.enlyze.gateway import EnlyzeProductionRun
from production_analytics.service.historical_reconcile import (
Decision,
HistoricalRecord,
decide,
reconcile_machine,
reconciliation_window,
)
from production_analytics.service.postgres_historical_reconcile import PostgresHistoricalRepository
def at(hour=12):
return datetime(2026, 10, 13, hour, tzinfo=UTC)
def record(order="old", machine="generic"):
return HistoricalRecord("material_consumption_snapshots", ("calc", machine, at()),
machine, at(), order, "retained-counter-run")
def run(order="Machine-123", machine="generic"):
return EnlyzeProductionRun("source-run", machine, None, order, at(10), at(14))
def confirmation(order="123", hour=12):
return SimpleNamespace(production_order=order, workplace="workplace",
timestamp=at(hour), is_finished_goods=True)
def decision(r=None, runs=None, confirmations=None):
return decide(r or record(), runs if runs is not None else [run()],
confirmations if confirmations is not None else [confirmation()],
"workplace", "Machine-{production_order}")
def test_correct_and_stale_assignments():
assert decision(record("Machine-123")).order == "Machine-123"
d = decision()
assert d.order == "Machine-123"
assert d.record.run_id == "retained-counter-run"
@pytest.mark.parametrize("machine", ["arbitrary-machine", "another-machine"])
def test_machine_independent(machine):
assert decision(record(machine=machine), [run(machine=machine)]).order == "Machine-123"
@pytest.mark.parametrize("runs, confirmations", [
([run(), run("Machine-456")], [confirmation()]),
([run()], [confirmation(), confirmation("456")]),
([], [confirmation()]),
([replace(run(), end=None)], [confirmation()]),
([run(), replace(run(), end=None)], [confirmation()]),
([run()], []),
])
def test_ambiguous_or_missing_evidence(runs, confirmations):
assert decision(runs=runs, confirmations=confirmations).order is None
def test_previous_order_at_start_is_ignored_when_current_order_is_inside():
start = confirmation("1030", 10)
current = confirmation("12026001032")
d = decide(record("K 7-12026001030", "reference-machine"),
[replace(run("K 7-12026001032", "reference-machine"),
start=at(10), end=at(14))], [start, current],
"workplace", "K 7-{production_order}")
assert d.order == "K 7-12026001032"
def test_interior_conflicting_order_remains_unresolved():
assert decision(confirmations=[confirmation("123"), confirmation("456", 13)]).order is None
def test_correct_order_at_start_without_interior_evidence_is_unresolved():
boundary = confirmation("123", 10)
assert decision(confirmations=[boundary]).order is None
def test_correct_order_strictly_inside_run_reconciles():
assert decision(confirmations=[confirmation("123", 11)]).order == "Machine-123"
def test_confirmation_at_run_end_is_ignored():
end = confirmation("123", 14)
assert decision(confirmations=[end]).order is None
def test_shared_boundary_confirmation_corroborates_neither_adjacent_run():
left = replace(run("Machine-123"), start=at(10), end=at(12))
right = replace(run("Machine-456"), uuid="right", start=at(12), end=at(14))
boundary = confirmation("123", 12)
left_record = replace(record(), timestamp=at(11))
right_record = replace(record(), timestamp=at(13))
assert decide(left_record, [left, right], [boundary], "workplace",
"Machine-{production_order}").order is None
assert decide(right_record, [left, right], [boundary], "workplace",
"Machine-{production_order}").order is None
def test_k7_repaired_1030_to_1032_boundary_case_is_correctable():
r = record("K 7-12026001030", "reference-machine")
run_start = at(11)
k7_run = replace(run("K 7-12026001032", "reference-machine"),
start=run_start, end=at(17))
previous = confirmation("12026001030", 11)
d = decide(r, [k7_run], [previous, confirmation("12026001032", 12)],
"workplace", "K 7-{production_order}")
assert d.order == "K 7-12026001032"
d = decide(r, [k7_run], [confirmation("12026001032"), confirmation("12026001037", 13)],
"workplace", "K 7-{production_order}")
assert d.order is None
def test_calendar_days_and_berlin_dst():
start, end = reconciliation_window(datetime(2026, 10, 15, 2, 30, tzinfo=UTC))
assert start.isoformat() == "2026-10-12T00:00:00+02:00"
assert end.isoformat() == "2026-10-15T00:00:00+02:00"
start, end = reconciliation_window(datetime(2026, 10, 27, tzinfo=UTC))
assert (end.timestamp() - start.timestamp()) / 3600 == 73
# UTC date still previous day; use Berlin's date.
assert reconciliation_window(datetime(2026, 10, 14, 23, tzinfo=UTC))[1].day == 15
@pytest.mark.parametrize("days", [0, -1, True])
def test_invalid_window(days):
with pytest.raises(ValueError):
reconciliation_window(at(), days)
def test_dry_run_and_source_failure():
repository = MagicMock()
repository.read.return_value = [record()]
repository.guard_runs.side_effect = lambda decisions: decisions
source = MagicMock()
source.get_production_runs.return_value = [run()]
erp = MagicMock()
erp.get_confirmations.return_value = [confirmation()]
config = SimpleNamespace(machine_id="generic", erp_workplace="workplace")
decisions, applied = reconcile_machine(repository, source, erp, config,
"Machine-{production_order}", at(11), at(13), True)
assert decisions[0].order == "Machine-123" and applied == 0
repository.apply.assert_not_called()
assert erp.get_confirmations.call_args.kwargs["start"] == at(10)
assert erp.get_confirmations.call_args.kwargs["end"] == at(14)
source.get_production_runs.side_effect = RuntimeError("source unavailable")
with pytest.raises(RuntimeError, match="source unavailable"):
reconcile_machine(repository, source, erp, config, "Machine-{production_order}",
at(11), at(13))
repository.apply.assert_not_called()
def repository_with_connection():
repository = PostgresHistoricalRepository(None)
connection = MagicMock()
repository.connect = MagicMock()
repository.connect.return_value.__enter__.return_value = connection
return repository, connection
def test_atomic_update_audit_and_repeated_run():
repository, connection = repository_with_connection()
connection.execute.return_value.fetchone.side_effect = [(1,), (at(),)]
assert repository.apply([decision()]) == 1
calls = connection.execute.call_args_list
assert len(calls) == 5 # isolation, lock, run guard, update, audit
update_args = calls[3].args[1]
assert update_args == ("Machine-123", "calc", "generic", at(), "old", "retained-counter-run")
audit_args = calls[4].args[1]
assert audit_args[0] == "generic"
assert audit_args[3:6] == ("old", "Machine-123", "retained-counter-run")
connection.reset_mock()
assert repository.apply([decision(record("Machine-123"))]) == 0
assert connection.execute.call_count == 2 # no update or audit
def test_concurrent_change_fails_without_audit():
repository, connection = repository_with_connection()
connection.execute.return_value.fetchone.side_effect = [(1,), None]
with pytest.raises(RuntimeError, match="concurrently"):
repository.apply([decision()])
assert connection.execute.call_count == 4
assert repository.connect.return_value.__exit__.call_args.args[0] is RuntimeError
def test_partial_and_split_run_guard():
repository, connection = repository_with_connection()
connection.execute.return_value.fetchone.return_value = (2,)
assert repository.guard_runs([decision()])[0].order is None
d = decision()
other = replace(d, record=replace(d.record, timestamp=at(13)), order="Machine-456")
assert repository.guard_runs([d, other]) == [d, other]
assert all(d.order is None for d in repository.guard_runs([d, replace(other, order=None)]))
connection.execute.return_value.fetchone.return_value = (1,)
assert repository.guard_runs([decision()])[0].order == "Machine-123"
def test_database_failure_propagates():
repository = PostgresHistoricalRepository(None)
repository.connect = MagicMock(side_effect=RuntimeError("database unavailable"))
with pytest.raises(RuntimeError, match="database unavailable"):
repository.read("machine", at(10), at(14))
def test_cli_defaults():
from production_analytics.cli.__main__ import _parser
args = _parser().parse_args(["historical-reconcile", "--dry-run"])
assert args.lookback_days == 3 and args.dry_run and not args.verbose
assert _parser().parse_args(["historical-reconcile", "--verbose"]).verbose
assert _parser().parse_args(["historical-reconcile", "--dry-run", "--verbose"]).verbose
@pytest.mark.parametrize("split", [False, True])
def test_end_to_end_dry_run_idempotency_and_physical_values(sqlite_schema, split):
import sqlite3
database = sqlite3.connect(":memory:")
database.executescript(sqlite_schema)
database.execute(
"INSERT INTO material_consumption_snapshots VALUES (?, ?, ?, ?, ?, ?)",
(at().isoformat(), "calc", "generic", "old", "retained-counter-run", 1234.5),
)
if split:
database.execute("DELETE FROM material_consumption_snapshots")
database.executemany(
"INSERT INTO material_consumption_snapshots VALUES (?, ?, ?, ?, ?, ?)",
[(at(hour).isoformat(), "calc", "generic", "OLD", "R1", value)
for hour, value in zip([10, 11, 12, 13], [1000, 1010, 1025, 1040])],
)
class Connection:
def __enter__(self):
return self
def __exit__(self, exc_type, *_):
database.rollback() if exc_type else database.commit()
def execute(self, statement, parameters=()):
statement = statement if isinstance(statement, str) else statement.as_string()
if statement.startswith(("SET TRANSACTION", "SELECT pg_advisory")):
return None
parameters = tuple(
str(p.obj) if hasattr(p, "obj") else p.isoformat()
if isinstance(p, datetime) else p for p in parameters
)
return database.execute(statement.replace("%s", "?"), parameters)
class Repository(PostgresHistoricalRepository):
def connect(self):
return Connection()
def read(self, machine_id, start, end):
return [replace(r, timestamp=datetime.fromisoformat(r.timestamp),
identity=(*r.identity[:2], datetime.fromisoformat(r.identity[2])))
for r in super().read(machine_id, start, end)]
repository = Repository(None)
source = SimpleNamespace(get_production_runs=lambda machine: [run()])
erp = SimpleNamespace(get_confirmations=lambda **kwargs: [confirmation()])
config = SimpleNamespace(machine_id="generic", erp_workplace="workplace")
if split:
source = SimpleNamespace(get_production_runs=lambda machine: [
replace(run("1032"), start=at(10), end=at(12)),
replace(run("1037"), uuid="second", start=at(12), end=at(14)),
])
erp = SimpleNamespace(get_confirmations=lambda **kwargs: [
confirmation("1032", 11), confirmation("1037", 13)])
template = "{production_order}" if split else "Machine-{production_order}"
args = (repository, source, erp, config, template, at(10), at(14))
decisions, count = reconcile_machine(*args, dry_run=True)
assert count == 0 and decisions[0].order == ("1032" if split else "Machine-123")
assert database.execute("SELECT count(*) FROM historical_assignment_audit").fetchone() == (0,)
assert database.execute(
"SELECT production_order FROM material_consumption_snapshots"
).fetchone() == (("OLD",) if split else ("old",))
assert reconcile_machine(*args)[1] == (4 if split else 1)
assert reconcile_machine(*args)[1] == 0
assert database.execute("SELECT count(*) FROM historical_assignment_audit").fetchone() == (
4 if split else 1,)
if split:
from production_analytics.calculations.shift_material import (
ShiftMaterialSnapshot,
aggregate_shift_material,
)
from production_analytics.service.historical_reconcile import grouped_counts
assert grouped_counts(decisions) == (1, 1, 2, 0, 0)
rows = database.execute(
"SELECT timestamp, calculation_id, machine_id, production_order, run_id, "
"consumption_kg FROM material_consumption_snapshots ORDER BY timestamp"
).fetchall()
snapshots = [ShiftMaterialSnapshot(datetime.fromisoformat(r[0]), *r[1:]) for r in rows]
assert [(r.timestamp.hour, r.run_id, r.consumption_kg) for r in snapshots] == [
(10, "R1", 1000), (11, "R1", 1010), (12, "R1", 1025), (13, "R1", 1040)]
summary = aggregate_shift_material(snapshots, machine_id="generic",
calculation_ids=("calc",), start=at(10), end=at(14))
assert [(i.production_order, i.consumption_kg) for i in summary.items] == [
("1032", 10), ("1037", 30)]
assert summary.total_consumption_kg == 40
return
assert database.execute(
"SELECT timestamp, run_id, consumption_kg, production_order "
"FROM material_consumption_snapshots"
).fetchone() == (at().isoformat(), "retained-counter-run", 1234.5, "Machine-123")
def test_erp_failure_never_becomes_no_changes():
repository = MagicMock()
repository.read.return_value = [record()]
source = SimpleNamespace(get_production_runs=lambda machine: [run()])
erp = MagicMock()
erp.get_confirmations.side_effect = RuntimeError("ERP offline")
with pytest.raises(RuntimeError, match="ERP offline"):
reconcile_machine(repository, source, erp,
SimpleNamespace(machine_id="generic", erp_workplace="workplace"),
"Machine-{production_order}", at(10), at(14))
repository.apply.assert_not_called()
def test_runtime_reports_machine_failures_and_continues(monkeypatch, capsys):
from pathlib import Path
from production_analytics.service import historical_runtime
for factory in ("PostgresHistoricalRepository", "EnlyzeApiGateway",
"ExplorationClient", "ErpProductionConfirmationGateway"):
monkeypatch.setattr(historical_runtime, factory, MagicMock())
for settings in (historical_runtime.PostgresSettings, historical_runtime.ErpSettings,
historical_runtime.ExplorationSettings):
monkeypatch.setattr(settings, "from_environment", MagicMock())
reconcile = MagicMock(side_effect=[RuntimeError("source offline"), ([], 0), ([], 0)])
monkeypatch.setattr(historical_runtime, "reconcile_machine", reconcile)
args = SimpleNamespace(lookback_days=3, dry_run=True,
config=Path("config/shift-report-machines.yaml"),
order_formats=Path("config/historical-order-formats.yaml"))
assert historical_runtime.run(args, {}) == 1
assert reconcile.call_count == 3
output = capsys.readouterr().out
assert "Physical runs inspected:" in output and "Unresolved segments:" in output
assert "Order segments proposed:" in output
assert "DRY RUN" in output and "FAILED B1" in output and "Failures: 1" in output
assert "source offline" in output
@pytest.mark.parametrize("dry_run", [True, False])
@pytest.mark.parametrize("verbose", [True, False])
def test_runtime_groups_record_output_and_preserves_totals(monkeypatch, capsys, dry_run, verbose):
from datetime import timedelta
from pathlib import Path
from production_analytics.service import historical_runtime
for factory in ("PostgresHistoricalRepository", "EnlyzeApiGateway",
"ExplorationClient", "ErpProductionConfirmationGateway"):
monkeypatch.setattr(historical_runtime, factory, MagicMock())
for settings in (historical_runtime.PostgresSettings, historical_runtime.ErpSettings,
historical_runtime.ExplorationSettings):
monkeypatch.setattr(settings, "from_environment", MagicMock())
start = at(10)
correction_reason = ("closed ENLYZE run e0f474e0-1234 "
"[2026-10-13T10:00:00+00:00, 2026-10-13T14:00:00+00:00) "
"corroborated by ERP order K 7-12026001032")
corrections = [
Decision(HistoricalRecord(
"material_consumption_snapshots", ("calc", "machine", start + timedelta(seconds=i)),
"machine", start + timedelta(seconds=i), "K 7-12026001030", "counter-run",
), "K 7-12026001032", correction_reason)
for i in range(1964)
]
unresolved = [
Decision(HistoricalRecord(
"material_application_snapshots", ("application", "machine",
start + timedelta(seconds=i)),
"machine", start + timedelta(seconds=i), "B 1-42", "application-run",
), None, "unresolved: missing or overlapping closed ENLYZE runs")
for i in range(8421)
]
reconcile = MagicMock(side_effect=[(corrections, 1964 if not dry_run else 0),
(unresolved, 0), ([], 0)])
monkeypatch.setattr(historical_runtime, "reconcile_machine", reconcile)
args = SimpleNamespace(lookback_days=3, dry_run=dry_run, verbose=verbose,
config=Path("config/shift-report-machines.yaml"),
order_formats=Path("config/historical-order-formats.yaml"))
assert historical_runtime.run(args, {}) == 0
output = capsys.readouterr().out
correction_action = "proposed" if dry_run else "corrected"
assert (f"B1 | {correction_action}: K 7-12026001030 -> K 7-12026001032 | "
"ENLYZE run e0f474e0-1234 | 1964 records") in output
assert ("E1 | unresolved: missing or overlapping closed ENLYZE runs | "
"physical run application-run | source material_application_snapshots/application | "
"8421 records | 2026-10-13T10:00:00+00:00 -> "
"2026-10-13T12:20:20+00:00") in output
assert output.count("1964 records") == 1
assert output.count("8421 records") == 1
if verbose:
assert output.count("Proposed B1 " if dry_run else "Corrected B1 ") == 1964
assert output.count("Unresolved E1 ") == 8421
else:
assert "Proposed B1 " not in output
assert "Corrected B1 " not in output
assert "Unresolved E1 " not in output
assert "('calc', 'machine'" not in output
assert len(output.splitlines()) == 15
assert "Machines checked: 3\nRecords inspected: 10385" in output
assert f"Corrections {'proposed' if dry_run else 'applied'}: 1964" in output
assert "Ambiguous/unresolved: 8421\nUnchanged: 0\nFailures: 0" in output
assert "Physical runs inspected: 2\nRuns with proposed corrections: 1" in output
assert f"Order segments {correction_action}: 1" in output
assert "Unresolved runs: 1\nUnresolved segments: 1" in output
def test_grouped_counts_distinguish_rows_runs_and_segments():
from production_analytics.service.historical_reconcile import grouped_counts
d = decision()
decisions = [replace(d, record=replace(d.record, timestamp=at(hour)), order=order)
for hour, order in [(10, "A"), (11, "A"), (12, "B"), (13, None)]]
assert grouped_counts(decisions) == (1, 1, 2, 1, 1)
assert grouped_counts([]) == (0, 0, 0, 0, 0)
@pytest.mark.parametrize("calculation", [
"bento1-fresh-bentonite-application", "bento1-spreader3-application",
])
def test_application_collision_deduplicates_audits_and_is_idempotent(
sqlite_schema, calculation,
):
database, repository = application_repository(sqlite_schema)
for hour in (11, 12, 13):
insert_application(database, calculation, hour, "old", "old-run", 4730.169159683733)
insert_application(database, calculation, hour, "Machine-123", "source-run",
4730.169159683733)
args = application_reconcile_args(repository)
decisions, count = reconcile_machine(*args, dry_run=True)
assert count == 0 and len([d for d in decisions if d.order != d.record.production_order]) == 3
assert application_rows(database, calculation) == 6
assert database.execute("SELECT count(*) FROM historical_assignment_audit").fetchone() == (0,)
assert reconcile_machine(*args)[1] == 3
assert application_rows(database, calculation) == 3
assert database.execute(
"SELECT production_order, run_id, application_g_m2 FROM material_application_snapshots "
"WHERE calculation_id = ? ORDER BY timestamp", (calculation,)
).fetchall() == [("Machine-123", "source-run", 4730.169159683733)] * 3
assert database.execute(
"SELECT previous_order, new_order, run_id, retained_run_id, action, reason, "
"record_identity FROM historical_assignment_audit ORDER BY id"
).fetchall() == [
("old", "Machine-123", "old-run", "source-run", "deduplicated",
decisions[0].reason, str({"calculation_id": calculation, "machine_id": "generic",
"timestamp": str(at(hour))}))
for hour in (11, 12, 13)
]
assert reconcile_machine(*args)[1] == 0
def test_application_without_target_updates_normally(sqlite_schema):
database, repository = application_repository(sqlite_schema)
insert_application(database, "calc", 12, "old", "old-run", 42.5)
assert reconcile_machine(*application_reconcile_args(repository))[1] == 1
assert database.execute(
"SELECT production_order, run_id, application_g_m2 FROM material_application_snapshots"
).fetchone() == ("Machine-123", "old-run", 42.5)
assert database.execute(
"SELECT action, retained_run_id FROM historical_assignment_audit"
).fetchone() == ("updated", None)
@pytest.mark.parametrize("target_value,target_run", [
(99.0, "source-run"), (42.5, "unexpected-run"),
])
def test_application_collision_rolls_back_whole_machine(
sqlite_schema, target_value, target_run,
):
database, repository = application_repository(sqlite_schema)
for hour in (11, 12):
insert_application(database, "calc", hour, "old", "old-run", 42.5)
insert_application(database, "calc", hour, "Machine-123", "source-run" if hour == 11
else target_run, 42.5 if hour == 11 else target_value)
with pytest.raises(RuntimeError, match="conflicting measurement|unexpected target run"):
reconcile_machine(*application_reconcile_args(repository))
assert application_rows(database, "calc") == 4
assert database.execute("SELECT count(*) FROM historical_assignment_audit").fetchone() == (0,)
def application_repository(sqlite_schema):
import sqlite3
database = sqlite3.connect(":memory:")
database.executescript(sqlite_schema)
class Connection:
def __enter__(self):
return self
def __exit__(self, exc_type, *_):
database.rollback() if exc_type else database.commit()
def execute(self, statement, parameters=()):
statement = statement if isinstance(statement, str) else statement.as_string()
if statement.startswith(("SET TRANSACTION", "SELECT pg_advisory")):
return None
parameters = tuple(
str(p.obj) if hasattr(p, "obj") else p.isoformat()
if isinstance(p, datetime) else p for p in parameters
)
return database.execute(statement.replace(" FOR UPDATE", "").replace("%s", "?"),
parameters)
class Repository(PostgresHistoricalRepository):
def connect(self):
return Connection()
def read(self, machine_id, start, end):
return [replace(r, timestamp=datetime.fromisoformat(r.timestamp),
identity=(*r.identity[:2], datetime.fromisoformat(r.identity[2])))
for r in super().read(machine_id, start, end)]
return database, Repository(None)
def insert_application(database, calculation, hour, order, run_id, value):
database.execute("INSERT INTO material_application_snapshots VALUES (?, ?, ?, ?, ?, ?)",
(at(hour).isoformat(), calculation, "generic", order, run_id, value))
database.commit()
def application_rows(database, calculation):
return database.execute(
"SELECT count(*) FROM material_application_snapshots WHERE calculation_id = ?",
(calculation,),
).fetchone()[0]
def application_reconcile_args(repository):
source = SimpleNamespace(get_production_runs=lambda machine: [run()])
erp = SimpleNamespace(get_confirmations=lambda **kwargs: [confirmation()])
config = SimpleNamespace(machine_id="generic", erp_workplace="workplace")
return repository, source, erp, config, "Machine-{production_order}", at(10), at(14)
+237
View File
@@ -0,0 +1,237 @@
from datetime import UTC, datetime, timedelta
from fractions import Fraction
from hashlib import sha256
from pathlib import Path
from unittest.mock import Mock, patch
import pytest
import yaml
from production_analytics.calculations.config import (
CalculationConfigError,
load_material_calculation,
)
from production_analytics.calculations.material_application import linear_signal_discharge_g_m2
from production_analytics.calculations.material_consumption import (
MaterialConsumptionIntegrator,
MaterialIntegratorConfig,
)
from production_analytics.enlyze.gateway import EnlyzeApiGateway, EnlyzeProductionRun
from production_analytics.service.material_runtime import build_material_runner
CONFIG = 'config/bento1-spreader3-material-consumption.yaml'
NOW = datetime(2026, 9, 9, tzinfo=UTC)
def configured_samples(width=5, gates=None):
config = load_material_calculation(CONFIG)
client = Mock()
times = [0, 10, 20, 40, 61, 71]
gates = gates if gates is not None else [2.3, 0.3, 0, 2.3, 2.3, 2.3]
client.post_json.return_value.body = {'data': {
'columns': ['time', *config.application_signal_refs, config.gate_signal_ref],
'records': [[(NOW + timedelta(seconds=t)).isoformat(), 3.3032, gate]
for t, gate in zip(times, gates, strict=True)],
}}
samples = EnlyzeApiGateway(client).get_material_samples(
machine_id=config.machine_ref, rate_variable_id='unused',
gate_variable_id=config.gate_signal_ref, start=NOW, end=NOW + timedelta(seconds=71),
application_variable_ids=config.application_signal_refs, nominal_width_m=width,
specific_discharge_kg_per_signal_unit_m=config.specific_discharge_kg_per_signal_unit_m,
process_application_gate_threshold=config.gate_threshold,
)
assert client.post_json.call_args.args[1]['variables'] == [
{'uuid': ref} for ref in (*config.application_signal_refs, config.gate_signal_ref)]
return samples
def test_reference_and_zero():
config = load_material_calculation(CONFIG)
assert config.calibration_ref == 'bento1-spreader-3-bentonite'
factor = config.specific_discharge_kg_per_signal_unit_m
assert linear_signal_discharge_g_m2([3.3032], factor, 2.3, 0.3) == pytest.approx(540, abs=0.01)
assert linear_signal_discharge_g_m2([0], factor, 2.3, 0.3) == 0
@pytest.mark.parametrize('width', [1, 4.85, 5, 100])
def test_application_independent_of_width_and_consumption_formula(width):
samples = configured_samples(width)
assert samples[0].application_g_m2 == pytest.approx(540, abs=0.01)
assert samples[0].material_rate_kg_per_hour == pytest.approx(samples[0].application_g_m2 * width * 2.3 / 1000 * 60)
assert samples[1].application_g_m2 is None
assert samples[2].application_g_m2 is None
def test_gate_and_gap():
state = MaterialConsumptionIntegrator(MaterialIntegratorConfig(0.3, 20)).process_many(
configured_samples())
# 0→10 and 61→71 only: inactive preceding gates and the 21s gap are excluded.
assert state.integrated_running_seconds == 20
assert state.cumulative_consumption_kg == pytest.approx(3.3032 * 0.376 * 5 * 20 / 60)
@pytest.mark.parametrize('field,value,message', [
('type', 'rotational_discharge', 'incompatible type'),
('unit', 'kg_per_rev_m', 'incompatible unit'),
('value', 0, 'greater than zero'),
('value', -1, 'greater than zero'),
('value', float('nan'), 'finite'),
('value', float('inf'), 'finite'),
('value', True, 'finite number'),
])
def test_incompatible_calibration(tmp_path, field, value, message):
document = yaml.safe_load(Path('config/material-calibrations.yaml').read_text())
document['calibrations']['bento1-spreader-3-bentonite'][field] = value
(tmp_path / 'material-calibrations.yaml').write_text(yaml.safe_dump(document))
path = tmp_path / 'config.yaml'
path.write_text(Path(CONFIG).read_text())
with pytest.raises(CalculationConfigError, match=message):
load_material_calculation(path)
def test_missing_calibration_reference(tmp_path):
document = yaml.safe_load(Path(CONFIG).read_text())
del document['calculations'][0]['calibration_ref']
path = tmp_path / 'config.yaml'
path.write_text(yaml.safe_dump(document))
with pytest.raises(CalculationConfigError, match='requires calibration_ref'):
load_material_calculation(path)
def test_runtime_isolation_and_disjoint_runs(tmp_path, monkeypatch):
monkeypatch.setenv('ENLYZE_BASE_URL', 'https://example.invalid/api/')
for key, value in dict(HOST='localhost', PORT='5432', DB='analytics',
USER='user', PASSWORD='test').items():
monkeypatch.setenv(f'POSTGRES_{key}', value)
secrets = tmp_path / 'secret.env'
secrets.write_text('ENLYZE_API_KEY=test\n')
configs = [load_material_calculation(path) for path in (
CONFIG, 'config/bento1-material-consumption.yaml', 'config/k7-material-consumption.yaml')]
with patch('production_analytics.service.material_runtime.ErpSettings'):
runners = [build_material_runner(c, poll_interval_seconds=10,
state_directory=tmp_path / 'state', secrets_file=secrets) for c in configs]
separate, fresh, k7 = runners
assert separate.calculation_id == 'bento1-spreader3-consumption'
assert fresh.service._specific_discharge == 2.75
assert fresh.service._rotational_speed_variable_ids == configs[1].rotational_speed_signal_refs
assert fresh.service._signal_discharge is None
assert k7.service._signal_discharge is None
assert k7.service._process_application_calculation_id is None
assert separate.service._signal_discharge == (
configs[0].specific_discharge_kg_per_signal_unit_m)
assert separate.service._nominal_width_provider.format_template == 'Bento 1-{production_order}'
assert separate.service._nominal_width_provider.fallback_nominal_width_m == 5.0
machine = configs[0].machine_ref
order = 'Bento 1-test'
separate_path = separate.service._state_store.store._path(machine, order)
fresh_path = fresh.service._state_store.store._path(machine, order)
assert separate_path != fresh_path
assert separate_path.parent.name == sha256(configs[0].id.encode()).hexdigest()
gateway = Mock()
old = EnlyzeProductionRun('old', machine, None, order, NOW, NOW + timedelta(seconds=10))
current = EnlyzeProductionRun('new', machine, None, order,
NOW + timedelta(seconds=15), None)
gateway.get_open_production_run.return_value = current
gateway.get_production_runs.return_value = [old, current]
samples = configured_samples()
def window(**kwargs):
assert kwargs['specific_discharge_kg_per_signal_unit_m'] == pytest.approx(
0.376)
from dataclasses import replace
return [replace(samples[0], timestamp=kwargs['start']),
replace(samples[0], timestamp=kwargs['end'])]
gateway.get_material_samples.side_effect = window
service = separate.service
service._gateway = gateway
service._nominal_width_provider = lambda order: 5
service._application_writer = Mock()
result = service.poll_once(now=NOW + timedelta(seconds=25))
assert result.state.integrated_running_seconds == 20 # no bridging the 5s run gap
assert result.state.cumulative_consumption_kg == pytest.approx(3.3032 * 0.376 * 5 / 3)
assert not fresh_path.exists() # no fresh-bentonite state or aggregation written
written_ids = {c.kwargs['calculation_id']
for c in service._application_writer.write.call_args_list}
assert written_ids == {'bento1-spreader3-application'}
@pytest.mark.parametrize('signals,factor', [
([], 1), ([float('nan')], 1), ([1], 0), ([1], float('inf')), ([1e308], 10),
])
def test_invalid_linear_inputs(signals, factor):
with pytest.raises(ValueError):
linear_signal_discharge_g_m2(signals, factor, 2.3, 0.3)
@pytest.mark.parametrize('signal,speed,expected', [(3.3032, 2.3, 540),
(8.999, 4.999, 676.860172034407)])
def test_discharge_physics(signal, speed, expected):
from production_analytics.calculations.material_consumption import (
linear_signal_discharge_rate_kg_per_hour,
)
factor = load_material_calculation(CONFIG).specific_discharge_kg_per_signal_unit_m
assert factor == pytest.approx(0.376)
width = 5
flow = linear_signal_discharge_rate_kg_per_hour([signal], width, factor) / 60
application = linear_signal_discharge_g_m2([signal], factor, speed, 0.3)
assert application == pytest.approx(expected, abs=0.01)
assert flow == pytest.approx(application * width * speed / 1000)
faster_application = linear_signal_discharge_g_m2([signal], factor, speed * 2, 0.3)
assert faster_application == pytest.approx(application / 2)
assert faster_application * width * speed * 2 / 1000 == pytest.approx(flow)
assert linear_signal_discharge_rate_kg_per_hour([0], width, factor) == 0
assert linear_signal_discharge_rate_kg_per_hour([signal / 2, signal / 2], width,
factor) / 60 == pytest.approx(flow)
@pytest.mark.parametrize('speed', [0, -1, 0.3])
def test_inactive_speed(speed):
factor = load_material_calculation(CONFIG).specific_discharge_kg_per_signal_unit_m
assert linear_signal_discharge_g_m2([3.3032], factor, speed, 0.3) is None
@pytest.mark.parametrize('speed', [float('nan'), float('inf')])
def test_invalid_speed(speed):
factor = load_material_calculation(CONFIG).specific_discharge_kg_per_signal_unit_m
with pytest.raises(ValueError, match='line speed'):
linear_signal_discharge_g_m2([3.3032], factor, speed, 0.3)
@pytest.mark.parametrize('gate', [None, '', 0])
def test_missing_gate_config(tmp_path, gate):
document = yaml.safe_load(Path(CONFIG).read_text())
document['calculations'][0]['gate_signal_ref'] = gate
path = tmp_path / 'config.yaml'
path.write_text(yaml.safe_dump(document))
with pytest.raises(CalculationConfigError, match='gate_signal_ref'):
load_material_calculation(path)
def test_gateway_speed_changes_only_application():
samples = configured_samples(gates=[2.3, 4.6, 0, -1, 0.3, 2.3])
assert samples[0].application_g_m2 == pytest.approx(540, abs=0.01)
assert samples[1].application_g_m2 == pytest.approx(270, abs=0.01)
assert [sample.material_rate_kg_per_hour for sample in samples] == pytest.approx(
[3.3032 * 0.376 * 5 * 60] * 6)
assert all(sample.application_g_m2 is None for sample in samples[2:5])
@pytest.mark.parametrize('speed', [None, True, float('nan'), float('inf')])
def test_gateway_invalid_speed(speed):
with pytest.raises(ValueError, match='rate and gate must be'):
configured_samples(gates=[speed] * 6)
@pytest.mark.parametrize('width', [None, 0, -1, float('nan'), float('inf')])
def test_gateway_requires_valid_width(width):
with pytest.raises(ValueError, match='width'):
configured_samples(width=width)
@pytest.mark.parametrize('threshold', [0, -1, float('nan'), float('inf')])
def test_invalid_speed_threshold(threshold):
with pytest.raises(ValueError, match='speed gate threshold'):
linear_signal_discharge_g_m2([3.3032], 0.376, 2.3, threshold)
+215
View File
@@ -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
+2 -1
View File
@@ -12,7 +12,8 @@ def test_b2_config_has_only_verified_signals() -> None:
config = load_power_meter_config("config/power-meters.example.yaml", "B2") config = load_power_meter_config("config/power-meters.example.yaml", "B2")
assert config.machine_uuid == "0d7955e9-5cde-4e14-9af7-5b041dc796f0" assert config.machine_uuid == "0d7955e9-5cde-4e14-9af7-5b041dc796f0"
assert config.signals.energy_total == "0f5c0853-1aa7-4fa3-b267-ea2669024e46" assert config.signals.energy_total == "0f5c0853-1aa7-4fa3-b267-ea2669024e46"
assert config.signals.power_outages is None assert config.signals.power_outages == "ea1f1f51-1758-4818-8ec3-fbb4b76d1a77"
assert dict(config.signals.phase_active_power)["L2"] == "d9ae584e-551b-44b8-a822-3cf9554e77e4"
def test_counter_reset_starts_new_epoch() -> None: def test_counter_reset_starts_new_epoch() -> None:
+287
View File
@@ -0,0 +1,287 @@
"""Order search, shift assignment, and read-only web routes use fake ERP rows."""
from datetime import date, datetime
from unittest.mock import MagicMock
from urllib.parse import urlencode
from wsgiref.util import setup_testing_defaults
from zoneinfo import ZoneInfo
import pytest
from production_analytics import web
from production_analytics.erp.gateway import (
ErpProductionConfirmationGateway,
ErpSettings,
OrderConfirmationGroup,
OrderConfirmationRow,
ProductionConfirmation,
)
from production_analytics.presentation.production_order_html import render_detail, render_search
from production_analytics.service.production_order import ProductionOrderService
from production_analytics.service.shift_report_config import load_shift_report_machines
ORDER = "82026400900"
BERLIN = ZoneInfo("Europe/Berlin")
MALAYSIA = ZoneInfo("Asia/Kuala_Lumpur")
MACHINES = load_shift_report_machines("config/shift-report-machines.yaml")
def row(hour, minute, *, workplace="GITTERIII", day=19, amount=10,
order=ORDER, article="A"):
return OrderConfirmationRow(order, workplace, article, "Article name",
datetime(2026, 10, day, hour, minute), amount)
class FakeGateway:
def __init__(self, rows=(), groups=(), shift_rows=None):
self.rows = list(rows)
self.shift_rows = list(rows if shift_rows is None else shift_rows)
self.groups = list(groups)
self.calls = []
def search_orders(self, query, *, limit=25):
self.calls.append(("search", query, limit))
return self.groups
def get_order_confirmations(self, production_order):
self.calls.append(("detail", production_order))
return self.rows
def get_confirmations(self, *, workplace, start, end, timezone):
self.calls.append(("shift", workplace, start, end, timezone))
return [ProductionConfirmation(
workplace=value.workplace, production_order=value.production_order,
timestamp=value.timestamp_local.replace(tzinfo=timezone),
article_number=value.article_number,
article_description=value.article_description,
roll_number=None, production_quantity_m2=None,
feedback_quantity_m2=value.feedback_quantity_m2,
raw_material_number=None, raw_material_description=None, batch_number=None,
raw_material_quantity=None, tenant=None,
) for value in self.shift_rows if value.workplace == workplace and
start <= value.timestamp_local.replace(tzinfo=timezone) < end]
def group(order=ORDER, workplace="GITTERIII", article="A"):
return OrderConfirmationGroup(order, workplace, article, "Article name",
datetime(2026, 10, 19, 6), datetime(2026, 10, 19, 14))
def test_search_trims_and_collapses_rows_by_fa_with_multiple_workplaces():
gateway = FakeGateway(groups=[group(workplace="BENTO 1"), group(),
group("82026400901"), group(article="B")])
result = ProductionOrderService(gateway, MACHINES).search(" 82026400900 ")
assert gateway.calls == [("search", ORDER, 25)]
assert [entry.production_order for entry in result] == [ORDER, "82026400901"]
assert len(result[0].placements) == 3
assert {place.machine_name for place in result[0].placements} == {"B1", "Gitter 3"}
assert {place.timezone for place in result[0].placements} == {BERLIN}
def test_search_limit_and_order_are_deterministic_even_with_unsorted_gateway():
groups = [group("8202642"), group("8202641"), group("8202643"), group("8202641")]
service = ProductionOrderService(FakeGateway(groups=groups), MACHINES)
assert [value.production_order for value in service.search("820264", limit=2)] == [
"8202641", "8202642"]
assert [value.production_order for value in service.search("8202642", limit=2)] == [
"8202642", "8202641"]
@pytest.mark.parametrize("query", ["", " ", "\x00", "x" * 81])
def test_blank_or_invalid_search_never_queries_gateway(query):
gateway = FakeGateway()
with pytest.raises(ValueError):
ProductionOrderService(gateway, MACHINES).search(query)
assert gateway.calls == []
def test_unknown_workplace_is_visible_without_shift_assignment():
gateway = FakeGateway(rows=[row(7, 0, workplace="UNCONFIGURED")],
groups=[group(workplace="UNCONFIGURED")])
service = ProductionOrderService(gateway, MACHINES)
placement = service.search(ORDER)[0].placements[0]
assert placement.mapping_status == "unknown"
assert placement.machine_name is placement.site is placement.timezone is None
detail = service.detail(ORDER)
assert detail.placements[0].mapping_status == "unknown"
assert detail.shifts == ()
def test_ambiguous_workplace_is_visible_without_arbitrary_machine_choice():
from dataclasses import replace
machines = {"B1": MACHINES["B1"],
"Other": replace(MACHINES["B1"], display_name="Other")}
service = ProductionOrderService(FakeGateway(rows=[row(7, 0, workplace="BENTO 1")],
groups=[group(workplace="BENTO 1")]), machines)
assert service.search(ORDER)[0].placements[0].mapping_status == "ambiguous"
assert service.detail(ORDER).shifts == ()
def test_one_shift_aggregates_positive_feedback_and_confirmation_bounds():
service = ProductionOrderService(FakeGateway(rows=[row(6, 1, amount=2),
row(13, 59, amount=3)]), MACHINES)
detail = service.detail(ORDER)
assert len(detail.shifts) == 1
item = detail.shifts[0]
assert (item.machine_name, item.site, item.date, item.shift, item.produced_m2) == (
"Gitter 3", "adorf", date(2026, 10, 19), "early", 5)
assert (item.first_confirmation.hour, item.last_confirmation.hour) == (6, 13)
assert (item.shift_start.hour, item.shift_end.hour) == (6, 14)
def test_two_shifts_and_night_across_midnight():
rows = [row(13, 59), row(14, 0), row(22, 0), row(5, 59, day=20),
row(6, 0, day=20)]
shifts = ProductionOrderService(FakeGateway(rows=rows), MACHINES).detail(ORDER).shifts
assert [(item.date, item.shift, item.produced_m2) for item in shifts] == [
(date(2026, 10, 19), "early", 10),
(date(2026, 10, 19), "late", 10),
(date(2026, 10, 19), "night", 20),
(date(2026, 10, 20), "early", 10),
]
assert shifts[2].shift_end == datetime(2026, 10, 20, 6, tzinfo=BERLIN)
def test_same_fa_on_multiple_machines_uses_each_site_timezone():
rows = [row(7, 0), row(7, 0, workplace="K1", amount=4)]
shifts = ProductionOrderService(FakeGateway(rows=rows), MACHINES).detail(ORDER).shifts
assert len(shifts) == 2
assert {(item.machine_name, item.timezone) for item in shifts} == {
("Gitter 3", BERLIN), ("K1", MALAYSIA)}
assert shifts[0].shift_start.astimezone(ZoneInfo("UTC")) != (
shifts[1].shift_start.astimezone(ZoneInfo("UTC")))
def test_malaysia_before_six_belongs_to_previous_night_start_date():
shift = ProductionOrderService(FakeGateway(rows=[row(5, 45, workplace="K1",
day=20)]), MACHINES).detail(ORDER).shifts[0]
assert (shift.date, shift.shift, shift.timezone) == (
date(2026, 10, 19), "night", MALAYSIA)
assert shift.shift_start == datetime(2026, 10, 19, 22, tzinfo=MALAYSIA)
assert shift.shift_end == datetime(2026, 10, 20, 6, tzinfo=MALAYSIA)
def web_request(app, path, query="", method="GET"):
env = {}
setup_testing_defaults(env)
env.update(PATH_INFO=path, QUERY_STRING=query, REQUEST_METHOD=method)
result = []
body = b"".join(app(env, lambda status, headers: result.append((status, headers))))
return result[0][0], body.decode()
def test_search_and_detail_web_pages_and_encoded_report_link():
gateway = FakeGateway(rows=[row(7, 0)], groups=[group()])
service = ProductionOrderService(gateway, MACHINES)
app = web.create_app(MACHINES, lambda: None,
order_service_factory=lambda: service)
status, text = web_request(app, "/orders")
assert status == "200 OK" and "Fertigungsauftrag suchen" in text
assert gateway.calls == []
status, text = web_request(app, "/orders", urlencode({"q": " 820264 "}))
assert status == "200 OK" and ORDER in text and "/order?production_order=" in text
status, text = web_request(app, "/order", urlencode({"production_order": ORDER}))
assert status == "200 OK"
assert '<a href="/orders" aria-current="page">Fertigungsauftrag</a>' in text
assert "Article name" in text and "10.00 m²" in text
assert "Schichtbericht" in text
assert "/?date=2026-10-19&amp;shift=early&amp;machine=Gitter+3" in text
@pytest.mark.parametrize("html", [render_search(), render_detail(detail=None)],
ids=["search", "detail"])
def test_order_pages_mark_order_mode_active(html):
assert '<nav class="mode-nav" aria-label="Bereich wählen">' in html
assert '<a href="/">Schichtbericht</a>' in html
assert '<a href="/orders" aria-current="page">Fertigungsauftrag</a>' in html
assert html.split("</style>", 1)[1].count('aria-current="page"') == 1
assert ".mode-nav a:focus-visible" in html
def test_order_pages_escape_erp_text():
unsafe = "<script>alert(1)</script>"
gateway = FakeGateway(
rows=[OrderConfirmationRow(ORDER, "GITTERIII", "A", unsafe,
datetime(2026, 10, 19, 7), 1)],
groups=[OrderConfirmationGroup(ORDER, "GITTERIII", "A", unsafe,
datetime(2026, 10, 19, 7),
datetime(2026, 10, 19, 7))],
)
app = web.create_app(MACHINES, lambda: None,
order_service_factory=lambda: ProductionOrderService(gateway, MACHINES))
for path, query in (("/orders", "q=820264"), ("/order", f"production_order={ORDER}")):
assert "<script>" not in web_request(app, path, query)[1]
assert "&lt;script&gt;" in web_request(app, path, query)[1]
@pytest.mark.parametrize("path,query,status", [
("/orders", "q=", "400 Bad Request"),
("/order", "", "400 Bad Request"),
("/order", "production_order=", "400 Bad Request"),
("/orders", "q=a&q=b", "400 Bad Request"),
("/orders", "extra=1", "400 Bad Request"),
])
def test_malformed_web_parameters_do_not_query(path, query, status):
gateway = FakeGateway()
service = ProductionOrderService(gateway, MACHINES)
app = web.create_app(MACHINES, lambda: None, order_service_factory=lambda: service)
actual, _ = web_request(app, path, query)
assert actual == status
assert gateway.calls == []
def test_order_web_errors_are_safe():
def fail():
raise RuntimeError("password=secret.internal")
app = web.create_app(MACHINES, lambda: None, order_service_factory=fail)
status, body = web_request(app, "/orders", "q=820264")
assert status == "503 Service Unavailable"
assert "secret.internal" not in body
assert web_request(app, "/order", "production_order=820264")[0] == (
"503 Service Unavailable")
assert web_request(app, "/orders", "q=820264", method="POST")[0] == (
"405 Method Not Allowed")
def test_missing_order_returns_404_without_source_details():
gateway = FakeGateway()
app = web.create_app(MACHINES, lambda: None, order_service_factory=lambda: (
ProductionOrderService(gateway, MACHINES)))
status, body = web_request(app, "/order", f"production_order={ORDER}")
assert status == "404 Not Found"
assert "nicht gefunden" in body
def test_gateway_search_is_parameterized_bounded_and_escapes_like(monkeypatch):
connect = MagicMock()
monkeypatch.setattr("production_analytics.erp.gateway.pymssql.connect", connect)
cursor = connect.return_value.__enter__.return_value.cursor.return_value.__enter__.return_value
cursor.fetchall.return_value = [
(ORDER, "GITTERIII", "A", "Article name", datetime(2026, 10, 19, 6),
datetime(2026, 10, 19, 14)),
(ORDER, "K1", "A", "Article name", datetime(2026, 10, 19, 6),
datetime(2026, 10, 19, 14)),
]
gateway = ErpProductionConfirmationGateway(ErpSettings("host", 1433, "db", "u", "p"))
result = gateway.search_orders(" 820264%_ ", limit=12)
assert len(result) == 2
sql, params = cursor.execute.call_args.args
assert "TOP (%s)" in sql and "GROUP BY" in sql
assert params == (12, "%820264\\%\\_%", "820264%_", "820264%_")
assert "820264%_" not in sql
assert connect.return_value.__exit__.called
def test_gateway_detail_uses_exact_fa_and_reuses_positive_feedback_semantics(monkeypatch):
connect = MagicMock()
monkeypatch.setattr("production_analytics.erp.gateway.pymssql.connect", connect)
cursor = connect.return_value.__enter__.return_value.cursor.return_value.__enter__.return_value
cursor.fetchall.return_value = [(ORDER, "GITTERIII", "A", "Article name",
datetime(2026, 10, 19, 7), 3)]
gateway = ErpProductionConfirmationGateway(ErpSettings("host", 1433, "db", "u", "p"))
assert gateway.get_order_confirmations(" " + ORDER + " ")[0].feedback_quantity_m2 == 3
sql, params = cursor.execute.call_args.args
assert params == (ORDER,)
assert "[Fertigungsauftragsnummer] = %s" in sql
assert "[Rückmeldemenge] > 0" in sql
+380
View File
@@ -0,0 +1,380 @@
"""Approximate FA windows feed existing speed and material services."""
from dataclasses import replace
from datetime import datetime
from math import fsum
from types import SimpleNamespace
import pytest
from test_production_order import BERLIN, MACHINES, FakeGateway, row
from test_shift_report import composition
from production_analytics.calculations.fiber_allocation import FiberBooking
from production_analytics.calculations.shift_material import (
ShiftMaterialItem,
ShiftMaterialSnapshot,
ShiftMaterialSummary,
)
from production_analytics.enlyze.exploration import ExplorationError
from production_analytics.presentation.production_order_html import render_detail
from production_analytics.presentation.shift_report import TableBlock, present_report
from production_analytics.service.fiber_allocation import K7FiberAllocationService
from production_analytics.service.postgres_shift_material import ShiftMaterialReadError
from production_analytics.service.production_order import ProductionOrderService
from production_analytics.service.shift_material import ShiftMaterialService
A, B, C = "FA-A", "FA-B", "FA-C"
class Speed:
def __init__(self, count=2, error=None):
self.calls = []
self.count = count
self.error = error
def summarize(self, *, config, start, end):
self.calls.append((config, start, end))
if self.error:
raise self.error
speed = float(start.hour + 1) if self.count else None
return SimpleNamespace(average_line_speed_m_min=speed,
active_sample_count=self.count)
class Material:
def __init__(self, value=0, error=None):
self.calls = []
self.value = value
self.error = error
def summarize(self, *, machine_id, calculation_ids, start, end):
self.calls.append((machine_id, calculation_ids, start, end))
if self.error:
raise self.error
value = self.value(start, end) if callable(self.value) else self.value
return SimpleNamespace(total_consumption_kg=value, items=())
def service(selected, all_rows, *, speed=None, materials=None, machines=MACHINES):
return ProductionOrderService(FakeGateway(rows=selected, shift_rows=all_rows), machines,
speed=speed, materials=materials)
def b1(hour, minute=0, *, order=A, day=19, amount=10):
return row(hour, minute, workplace="BENTO 1", order=order, day=day, amount=amount)
def windows(detail):
return [(part.start, part.end) for shift in detail.shifts for part in shift.segments]
def test_one_fa_occupies_full_shift_and_sources_receive_segment_window():
speed, material = Speed(), Material(12)
detail = service([b1(9)], [b1(9)], speed=speed, materials=material).detail(A)
shift = detail.shifts[0]
assert windows(detail) == [(datetime(2026, 10, 19, 6, tzinfo=BERLIN),
datetime(2026, 10, 19, 14, tzinfo=BERLIN))]
assert speed.calls[0][1:] == windows(detail)[0]
assert material.calls[0][2:] == windows(detail)[0]
assert (shift.average_speed_m_min, shift.material_consumption_kg) == (7, 12)
def test_two_fas_have_distinct_nonoverlapping_windows_and_kpis():
a, b = b1(7, order=A), b1(11, order=B)
speed, material = Speed(), Material(lambda start, end: 5 if start.hour == 6 else 12)
service_a = service([a], [a, b], speed=speed, materials=material)
service_b = service([b], [a, b], speed=speed, materials=material)
first, second = service_a.detail(A).shifts[0], service_b.detail(B).shifts[0]
assert first.segments[0].start.hour == 6
assert first.segments[0].end.hour == 9
assert second.segments[0].start == first.segments[0].end
assert second.segments[0].end.hour == 14
assert (first.average_speed_m_min, second.average_speed_m_min) == (7, 10)
assert (first.material_consumption_kg, second.material_consumption_kg) == (5, 12)
assert speed.calls[0][1:] == (first.segments[0].start, first.segments[0].end)
assert material.calls[1][2:] == (second.segments[0].start, second.segments[0].end)
def test_shift_report_and_order_detail_use_same_kpi_attribution():
a, b = b1(7, order=A), b1(11, order=B)
speed, material = Speed(), Material(lambda start, end: 5 if start.hour == 6 else 12)
order_service = service([a], [a, b], speed=speed, materials=material)
start = datetime(2026, 10, 19, 6, tzinfo=BERLIN)
end = datetime(2026, 10, 19, 14, tzinfo=BERLIN)
shift_kpis = order_service.for_shift(machine_name="B1", start=start, end=end,
orders=(A, B))
detail = order_service.detail(A).shifts[0]
assert shift_kpis[A].segments == detail.segments
assert shift_kpis[A].average_speed_m_min == detail.average_speed_m_min
assert shift_kpis[A].material_consumption_kg == detail.material_consumption_kg
assert shift_kpis[B].segments[0].start == shift_kpis[A].segments[0].end
assert shift_kpis[A].material_consumption_kg + shift_kpis[B].material_consumption_kg == 17
def test_three_sequential_fas_and_midpoints_are_clamped():
a, b, c = b1(6, order=A), b1(9, order=B), b1(13, order=C)
details = [service([selected], [a, b, c]).detail(selected.production_order)
for selected in (a, b, c)]
segments = [detail.shifts[0].segments[0] for detail in details]
assert [part.start.strftime("%H:%M") for part in segments] == ["06:00", "07:30", "11:00"]
assert [part.end.strftime("%H:%M") for part in segments] == ["07:30", "11:00", "14:00"]
assert all(left.end == right.start for left, right in zip(segments, segments[1:]))
def test_repeated_adjacent_fa_rows_keep_one_segment_and_sum_production():
a1, a2, b = b1(7, order=A, amount=3), b1(8, order=A, amount=4), b1(10, order=B)
detail = service([a1, a2], [a1, a2, b]).detail(A)
assert len(detail.shifts) == len(detail.shifts[0].segments) == 1
assert detail.shifts[0].produced_m2 == 7
assert detail.shifts[0].segments[0].end.hour == 9
def test_alternating_fa_confirmation_runs_remain_two_disjoint_segments():
a1, b, a2 = b1(7, order=A), b1(9, order=B), b1(11, order=A)
speed, material = Speed(), Material(4)
detail = service([a1, a2], [a1, b, a2], speed=speed, materials=material).detail(A)
parts = detail.shifts[0].segments
assert len(parts) == 2
assert parts[0].end.hour == 8 and parts[1].start.hour == 10
assert parts[0].end < parts[1].start
assert len(speed.calls) == len(material.calls) == 2
assert detail.shifts[0].material_consumption_kg == 8
assert detail.shifts[0].average_speed_m_min == 9
def test_simultaneous_three_fa_tie_gives_middle_order_unavailable_kpis():
a, b, c = (b1(9, order=order) for order in (A, B, C))
speed, material = Speed(), Material(4)
shift = service([b], [a, b, c], speed=speed, materials=material).detail(B).shifts[0]
assert shift.produced_m2 == 10
assert shift.segments == ()
assert shift.average_speed_m_min is shift.material_consumption_kg is None
assert speed.calls == material.calls == []
def test_cross_shift_and_night_keep_separate_kpis():
first = b1(21, order=A)
second = b1(1, order=A, day=20)
speed, material = Speed(), Material(3)
detail = service([first, second], [first, second], speed=speed, materials=material).detail(A)
assert [(item.date.day, item.shift) for item in detail.shifts] == [
(19, "late"), (19, "night")]
assert detail.shifts[0].segments[0].end.hour == 22
assert detail.shifts[1].segments[0].start.hour == 22
assert detail.shifts[1].segments[0].end == datetime(2026, 10, 20, 6, tzinfo=BERLIN)
assert [item.material_consumption_kg for item in detail.shifts] == [3, 3]
assert len(speed.calls) == len(material.calls) == 2
def test_disabled_capabilities_never_query_optional_sources():
k1 = row(7, 0, workplace="K1", order=A)
speed, material = Speed(), Material(10)
shift = service([k1], [k1], speed=speed, materials=material).detail(A).shifts[0]
assert shift.average_speed_m_min is shift.material_consumption_kg is None
assert speed.calls == material.calls == []
gitter = row(7, 0, workplace="GITTERIII", order=A)
service([gitter], [gitter], speed=speed, materials=material).detail(A)
assert len(speed.calls) == 1 and material.calls == []
@pytest.mark.parametrize("workplace,machine", [("GITTERIII", "Gitter 3"), ("K5", "K5")])
def test_machine_speed_gate_configuration_is_forwarded_unchanged(workplace, machine):
confirmation = row(7, 0, workplace=workplace, order=A)
speed = Speed()
shift = service([confirmation], [confirmation], speed=speed).detail(A).shifts[0]
assert speed.calls[0][0] is MACHINES[machine].speed
assert shift.average_speed_m_min == 7
def test_channel_material_uses_existing_channel_path():
e1 = row(7, 0, workplace="1568705", order=A)
cumulative, channel = Material(99), Material(6)
order_service = ProductionOrderService(
FakeGateway(rows=[e1]), MACHINES, materials=cumulative,
channel_materials=channel)
shift = order_service.detail(A).shifts[0]
assert shift.material_consumption_kg == 6
assert cumulative.calls == [] and len(channel.calls) == 1
def test_order_aware_allocator_uses_full_shift_summary():
k7 = row(7, 0, workplace="K7", order=A)
material = Material(9)
class Allocator:
def __init__(self):
self.calls = []
def allocate(self, measured):
self.calls.append(measured)
return measured
def totals_by_order(self, allocated):
return {A: allocated.total_consumption_kg}
allocator = Allocator()
order_service = ProductionOrderService(
FakeGateway(rows=[k7]), MACHINES, materials=material,
material_allocators={"K7": allocator})
shift = order_service.detail(A).shifts[0]
assert shift.material_consumption_kg == 9
assert len(allocator.calls) == 1
assert material.calls[0][2:] == (shift.shift_start, shift.shift_end)
def test_k7_compact_material_matches_allocated_shift_items_not_time_segments():
first_order, second_order = "12026001032", "12026001037"
start = datetime(2026, 10, 13, 14, tzinfo=BERLIN)
end = datetime(2026, 10, 13, 22, tzinfo=BERLIN)
config = MACHINES["K7"]
template = ShiftMaterialItem(
source="material_consumption_snapshots",
calculation_id=config.material.calculation_ids[0], machine_id=config.machine_id,
production_order=f"K 7-{first_order}", run_id="run", consumption_kg=3317.58,
baseline_timestamp=start, end_timestamp=end, baseline_missing=False,
)
measured = ShiftMaterialSummary(
config.machine_id, start, end, 5180.94,
(template, replace(template, production_order=f"K 7-{second_order}",
consumption_kg=1863.36)),
)
class Bookings:
def get_fiber_bookings(self, order):
amounts = ((2288.71, 1028.87) if order == first_order else (1312.62, 550.74))
return [FiberBooking(order, str(index), f"Fiber {index}", amount)
for index, amount in enumerate(amounts)]
allocator = K7FiberAllocationService(Bookings())
service, stubs, _, _ = composition("K7")
stubs["materials"].result = measured
first = row(15, 0, day=13, workplace="K7", order=first_order)
second = row(20, 0, day=13, workplace="K7", order=second_order)
order_service = ProductionOrderService(
FakeGateway(rows=[first], shift_rows=[first, second]), MACHINES,
speed=Speed(), materials=stubs["materials"],
material_allocators={"K7": allocator},
)
service.order_kpis = order_service
service.material_allocators = {"K7": allocator}
production = stubs["production"].result
production_items = tuple(
replace(production.items[0], production_order=order,
first_confirmation_at=start, last_confirmation_at=start)
for order in (first_order, second_order)
)
stubs["production"].result = replace(production, items=production_items)
report = service.build(machine_name="K7", start=start, end=end)
assert [item.material_consumption_kg for item in report.production.items] == pytest.approx(
[3317.58, 1863.36])
assert report.materials.total_consumption_kg == pytest.approx(5180.94)
assert fsum(item.consumption_kg for item in report.materials.items) == pytest.approx(5180.94)
assert len(report.materials.items) == 4
assert [item.consumption_kg for item in report.materials.items] == pytest.approx(
[2288.71, 1028.87, 1312.62, 550.74])
material_calls = [kwargs for name, kwargs in stubs["materials"].calls if name == "materials"]
assert material_calls == [{"machine_id": config.machine_id,
"calculation_ids": config.material.calculation_ids,
"start": start, "end": end}]
table = next(block for block in present_report(report)
if isinstance(block, TableBlock) and "Ø Geschwindigkeit" in block.headers)
assert [entry[-1] for entry in table.rows] == ["3.317,58 kg", "1.863,36 kg"]
material_table = next(block for block in present_report(report)
if isinstance(block, TableBlock) and "ERP-Anteil" in block.headers)
assert [entry[3] for entry in material_table.rows] == [
"2.288,71 kg", "1.028,87 kg", "1.312,62 kg", "550,74 kg"]
assert len(order_service.speed.calls) == 2
assert order_service.speed.calls[0][2] == order_service.speed.calls[1][1]
assert order_service.detail(first_order).shifts[0].material_consumption_kg == pytest.approx(
3317.58)
def test_k7_allocated_zero_remains_zero_and_absent_order_is_unavailable():
start = datetime(2026, 10, 13, 14, tzinfo=BERLIN)
end = datetime(2026, 10, 13, 22, tzinfo=BERLIN)
config = MACHINES["K7"]
item = ShiftMaterialItem(
source="material_consumption_snapshots",
calculation_id=config.material.calculation_ids[0], machine_id=config.machine_id,
production_order="K 7-12026001032", run_id="run", consumption_kg=0,
baseline_timestamp=start, end_timestamp=end, baseline_missing=False,
)
allocated = ShiftMaterialSummary(config.machine_id, start, end, 0, (item,))
allocator = K7FiberAllocationService(SimpleNamespace(get_fiber_bookings=lambda order: []))
first = row(15, 0, day=13, workplace="K7", order="12026001032")
second = row(20, 0, day=13, workplace="K7", order="12026001037")
order_service = ProductionOrderService(
FakeGateway(shift_rows=[first, second]), MACHINES,
material_allocators={"K7": allocator},
)
kpis = order_service.for_shift(
machine_name="K7", start=start, end=end,
orders=(first.production_order, second.production_order),
allocated_shift_materials=allocated,
)
assert kpis[first.production_order].material_consumption_kg == 0
assert kpis[second.production_order].material_consumption_kg is None
def test_no_active_speed_is_unavailable_and_material_zero_is_not():
speed, material = Speed(count=0), Material(0)
shift = service([b1(7)], [b1(7)], speed=speed, materials=material).detail(A).shifts[0]
assert shift.average_speed_m_min is None
assert shift.material_consumption_kg == 0
html = render_detail(detail=service([b1(7)], [b1(7)], speed=speed,
materials=material).detail(A))
assert "Ø Geschwindigkeit" in html and "Materialverbrauch" in html
assert "<td>—</td>" in html and "<td>0,00 kg</td>" in html
def test_order_html_formats_per_shift_kpis_in_german():
detail = service([b1(7)], [b1(7)]).detail(A)
enriched = replace(detail, shifts=(replace(detail.shifts[0],
average_speed_m_min=4.77,
material_consumption_kg=1234),))
html = render_detail(detail=enriched)
assert "<td>4,77 m/min</td>" in html
assert "<td>1.234,00 kg</td>" in html
def test_optional_source_failure_degrades_only_that_kpi():
speed = Speed(error=ExplorationError("unavailable"))
material = Material(2)
shift = service([b1(7)], [b1(7)], speed=speed, materials=material).detail(A).shifts[0]
assert shift.average_speed_m_min is None and shift.material_consumption_kg == 2
speed = Speed()
material = Material(error=ShiftMaterialReadError("unavailable"))
shift = service([b1(7)], [b1(7)], speed=speed, materials=material).detail(A).shifts[0]
assert shift.average_speed_m_min == 7 and shift.material_consumption_kg is None
def test_unexpected_programming_error_still_propagates():
with pytest.raises(ValueError, match="invalid configuration"):
service([b1(7)], [b1(7)], speed=Speed(error=ValueError("invalid configuration"))).detail(A)
def test_cumulative_material_segments_use_snapshot_deltas_without_double_counting():
a, b = b1(7, order=A), b1(12, order=B)
config = MACHINES["B1"]
stamps = [(6, 0), (8, 20), (10, 40), (13, 70)]
snapshots = [ShiftMaterialSnapshot(datetime(2026, 10, 19, hour, tzinfo=BERLIN),
config.material.calculation_ids[0], config.machine_id,
A, "run", value) for hour, value in stamps]
class Repository:
def get_snapshots(self, *, machine_id, calculation_ids, start, end):
earlier = [sample for sample in snapshots if sample.timestamp <= start]
inside = [sample for sample in snapshots if start < sample.timestamp < end]
return earlier[-1:] + inside
material = ShiftMaterialService(Repository())
first = service([a], [a, b], materials=material).detail(A).shifts[0]
second = service([b], [a, b], materials=material).detail(B).shifts[0]
whole = material.summarize(machine_id=config.machine_id,
calculation_ids=config.material.calculation_ids,
start=first.shift_start, end=first.shift_end)
assert first.segments[0].end == second.segments[0].start
assert (first.material_consumption_kg, second.material_consumption_kg) == (20, 50)
assert first.material_consumption_kg + second.material_consumption_kg == (
whole.total_consumption_kg)
@@ -119,4 +119,5 @@ def test_bento_runtime_wiring(tmp_path, monkeypatch):
assert service._gate_variable_id == 'fef41976-1103-4090-b780-eaeecc02fdfa' assert service._gate_variable_id == 'fef41976-1103-4090-b780-eaeecc02fdfa'
assert service._config == MaterialIntegratorConfig(0.3, 20) assert service._config == MaterialIntegratorConfig(0.3, 20)
assert service._nominal_width_provider.workplace == 'Bento 1' assert service._nominal_width_provider.workplace == 'Bento 1'
assert service._nominal_width_provider.fallback_nominal_width_m == 5.0
erp_settings.from_secret_file.assert_called_once_with(tmp_path / 'erp.env') erp_settings.from_secret_file.assert_called_once_with(tmp_path / 'erp.env')
+465
View File
@@ -0,0 +1,465 @@
import sqlite3
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_raw_closed_event_without_attribution():
source = event(start=START + timedelta(hours=1), end=START + timedelta(hours=2))
summary = summarize([source])
assert source.attributed_start is source.attributed_end is None
assert summary.events[0].start == source.source_start
assert summary.events[0].end == source.source_end
assert summary.total_downtime_seconds == 3600
def test_attributed_end_closes_raw_open_event():
attributed_end = START + timedelta(hours=2)
source = event(end=None, attributed_end=attributed_end)
summary = summarize([source])
assert summary.events[0].start == START
assert summary.events[0].end is attributed_end
assert summary.events[0].source.source_end is None
assert summary.total_downtime_seconds == 2 * 3600
def test_attributed_start_with_no_end_remains_open():
summary = summarize([event(end=None, attributed_start=START + timedelta(hours=7))])
assert summary.total_downtime_seconds == 3600
assert summary.events[0].end is END
def test_attribution_overrides_conflicting_raw_interval():
attributed_start = START + timedelta(hours=1)
attributed_end = START + timedelta(hours=2)
source = event(
start=END,
end=END + timedelta(hours=2),
attributed_start=attributed_start,
attributed_end=attributed_end,
)
summary = summarize([source])
assert summary.events[0].start is attributed_start
assert summary.events[0].end is attributed_end
assert summary.total_downtime_seconds == 3600
assert source.source_start == END
assert source.source_end == END + timedelta(hours=2)
def test_attributed_interval_clips_both_shift_boundaries():
source = event(
start=END,
end=END,
attributed_start=START - timedelta(hours=1),
attributed_end=END + timedelta(hours=1),
)
summary = summarize([source])
assert summary.events[0].start is START
assert summary.events[0].end is END
assert summary.total_downtime_seconds == 8 * 3600
def test_production_reconciled_no_data_event_does_not_overlap_later_shift():
source_start = datetime(2026, 10, 12, 8, 56, 30, tzinfo=UTC)
source = event(
start=source_start,
end=None,
attributed_start=source_start,
attributed_end=datetime(2026, 10, 12, 12, 36, 2, tzinfo=UTC),
)
summary = summarize(
[source],
start=datetime(2026, 10, 13, 12, tzinfo=UTC),
end=datetime(2026, 10, 13, 20, tzinfo=UTC),
)
assert summary.events == summary.reasons == ()
assert summary.total_downtime_seconds == 0
assert summary.non_downtime_seconds == 8 * 3600
def test_attributed_intervals_preserve_union_and_reason_aggregation():
sources = [
event(
identifier,
end=None,
reason=reason,
attributed_start=START + timedelta(hours=lower),
attributed_end=START + timedelta(hours=upper),
)
for identifier, reason, lower, upper in [
("a", "A", 0, 2),
("b", "A", 1, 3),
("c", "B", 2, 4),
]
]
summary = summarize(sources)
assert summary.total_downtime_seconds == 4 * 3600
assert summary.non_downtime_seconds == 4 * 3600
assert [
(reason.reason_name, reason.duration_seconds, reason.event_count)
for reason in summary.reasons
] == [("A", 3 * 3600, 2), ("B", 2 * 3600, 1)]
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,
START.astimezone(UTC),
END.astimezone(UTC),
)
]
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 COALESCE(attributed_start, source_start) < %s" in sql
assert "COALESCE(attributed_end, source_end) IS NULL" in sql
assert "OR COALESCE(attributed_end, source_end) > %s" in sql
assert "ORDER BY COALESCE(attributed_start, source_start), external_id" in sql
assert "category, comment, attributed_start, attributed_end" in sql
assert "production_order" not in sql
assert values[0].attributed_start == START.astimezone(UTC)
assert values[0].attributed_end == END.astimezone(UTC)
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
def test_repository_excludes_production_reconciled_event_from_later_shift(db):
repository, _, connection = db
# Execute the repository's overlap predicate, translating only driver placeholders.
with sqlite3.connect(":memory:") as database:
database.execute(
"""CREATE TABLE production_downtime_events (
external_id, machine_id, source_start, source_end,
reason_id, reason_name, reason_description, reason_group,
category, comment, attributed_start, attributed_end)"""
)
database.execute(
"""INSERT INTO production_downtime_events
(external_id, machine_id, source_start, attributed_start, attributed_end)
VALUES (?, ?, ?, ?, ?)""",
(
"reconciled-no-data",
"machine",
"2026-10-12T08:56:30+00:00",
"2026-10-12T08:56:30+00:00",
"2026-10-12T12:36:02+00:00",
),
)
def execute(sql, params):
return database.execute(
sql.replace("%s", "?"),
tuple(
value.isoformat() if isinstance(value, datetime) else value
for value in params
),
)
connection.execute.side_effect = execute
assert repository.get_events(
machine_id="machine",
start=datetime(2026, 10, 13, 12, tzinfo=UTC),
end=datetime(2026, 10, 13, 20, tzinfo=UTC),
) == []
@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)},
{"attributed_start": START.replace(tzinfo=None)},
{"attributed_end": END.replace(tzinfo=None)},
{"attributed_start": "invalid"},
{"attributed_end": "invalid"},
{"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)
+674
View File
@@ -0,0 +1,674 @@
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", 45),
(None, 10),
("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 summary.total_consumption_kg == pytest.approx(24_886.805)
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_allowed(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)
summary = aggregate([
sample(0, 100), sample(10, 110), sample(20, 500, run="r2"),
sample(30, 520, run="r2"), sample(40, 200), sample(50, 230),
], channel=channel)
assert summary.total_consumption_kg == 60
assert [(item.run_id, item.consumption_kg) for item in summary.items] == [
("r1", 10), ("r2", 20), ("r1", 30),
]
assert summary.items[2].baseline_missing
summary = aggregate([sample(0, 100), sample(10, 110, order="different")], channel=channel)
assert [(i.production_order, i.consumption_kg) for i in summary.items] == [("different", 10)]
@pytest.mark.parametrize("channel", [False, True])
def test_reappearing_run_keeps_order_attribution_within_each_segment(channel):
sample = channel_sample if channel else machine_sample
rows = [
sample(0, 100, run="A", order="first"),
sample(1, 110, run="A", order="second"),
sample(2, 500, run="B", order="second"),
sample(3, 520, run="B", order="third"),
sample(4, 200, run="A", order="third"),
sample(5, 230, run="A", order="fourth"),
]
summary = aggregate(rows, channel=channel)
assert [(i.run_id, i.production_order, i.consumption_kg) for i in summary.items] == [
("A", "second", 10), ("B", "third", 20), ("A", "fourth", 30),
]
def test_channel_identity_gap_does_not_bridge_across_reappearing_run_segment():
rows = [
channel_sample(0, 100, run="A", name="Known"),
channel_sample(1, 110, run="A", name=None),
channel_sample(2, 500, run="B", name="Other"),
channel_sample(3, 520, run="B", name="Other"),
channel_sample(4, 200, run="A", name=None),
channel_sample(5, 230, run="A", name="Known"),
]
summary = aggregate(rows, channel=True)
assert summary.total_consumption_kg == 60
assert [(item.run_id, item.material_name, item.consumption_kg) for item in summary.items] == [
("A", None, 10), ("B", "Other", 20), ("A", "Known", 30),
]
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
summary = aggregate(
[sample(0, 100), sample(10, None, run="r2"), sample(20, 120)], channel=channel
)
assert summary.total_consumption_kg == 0
@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
@pytest.mark.parametrize("middle", [None, "Material B"])
@pytest.mark.parametrize("missing", [False, True])
def test_repeated_channel_identity_consolidates_after_interval_attribution(middle, missing):
offset = 1 if missing else 0
rows = [
channel_sample(offset, 100, name="Material A"),
channel_sample(10, 110, name="Material A"),
channel_sample(20, 115, name=middle),
channel_sample(30, 135, name="Material A", quality=False),
]
summary = aggregate(rows, channel=True)
assert len(summary.items) == 2
a, other = summary.items
assert (a.material_name, a.consumption_kg) == ("Material A", 30)
assert (other.material_name, other.consumption_kg) == (middle, 5)
assert a.baseline_timestamp == rows[0].timestamp
assert a.end_timestamp == rows[-1].timestamp
assert not a.percentage_sum_valid
assert other.percentage_sum_valid
assert all(item.baseline_missing == missing for item in summary.items)
if middle is None:
assert other.material_mapping_status == "UNAVAILABLE"
assert summary.total_consumption_kg == 35
assert summary == aggregate(reversed(rows), channel=True)
def test_hundreds_of_alternating_channel_identities_consolidate():
rows = [channel_sample(0, 100)] + [
channel_sample(index, 100 + index, name="Material A" if index % 2 else None)
for index in range(1, 401)
]
summary = aggregate(rows, channel=True)
assert [(item.material_name, item.consumption_kg) for item in summary.items] == [
("Material A", 399),
(None, 1),
]
assert summary.total_consumption_kg == 400
assert summary == aggregate(reversed(rows), channel=True)
@pytest.mark.parametrize("context", ["channel", "extruder", "run", "order", "calculation"])
def test_channel_consolidation_keeps_unrelated_streams_and_runs_separate(context):
rows = [channel_sample(0, 100), channel_sample(10, 110)]
changes = {
"channel": {"doser_channel": "C2"},
"extruder": {"extruder": "Ex2"},
"run": {"run_id": "r2"},
"order": {"run_id": "r2", "production_order": "other"},
"calculation": {"calculation_id": "calc2"},
}[context]
rows += [
replace(channel_sample(20, 500), **changes),
replace(channel_sample(30, 520), **changes),
]
summary = aggregate(rows, channel=True, calculation_ids=("calc", "calc2"))
assert len(summary.items) == 2
assert sorted(item.consumption_kg for item in summary.items) == [10, 20]
assert summary.total_consumption_kg == 30
@pytest.mark.parametrize(
"field,value", [("material_number", "123"), ("material_mapping_status", "OTHER")]
)
def test_channel_consolidation_preserves_distinct_identity_metadata(field, value):
rows = [
channel_sample(0, 100),
channel_sample(10, 110),
replace(channel_sample(20, 120), **{field: value}),
channel_sample(30, 130),
]
summary = aggregate(rows, channel=True)
assert len(summary.items) == 2
assert sorted(item.consumption_kg for item in summary.items) == [10, 20]
assert summary.total_consumption_kg == 30
@pytest.mark.parametrize("include_zero", [False, True])
def test_consolidated_channel_zero_handling(include_zero):
rows = [
channel_sample(0, 100),
channel_sample(10, 100),
channel_sample(20, 105, name=None),
channel_sample(30, 105),
]
summary = aggregate(rows, channel=True, include_zero=include_zero)
assert summary.total_consumption_kg == 5
assert len(summary.items) == (2 if include_zero else 1)
if include_zero:
assert summary.items[0].consumption_kg == 0
assert summary.items[0].baseline_timestamp == rows[0].timestamp
assert summary.items[0].end_timestamp == rows[-1].timestamp
@pytest.mark.parametrize("minutes", [(0, 1, 2), (0, 0.5, 1, 1.5), (0, 5, 10)])
def test_short_bounded_unknown_gap_bridges_all_deltas(minutes):
rows = [
channel_sample(
minute,
100 + index * 10,
name=" Material A " if index in (0, len(minutes) - 1) else None,
quality=index != 1,
)
for index, minute in enumerate(minutes)
]
summary = aggregate(rows, channel=True)
assert len(summary.items) == 1
item = summary.items[0]
assert item.material_name == "Material A"
assert item.consumption_kg == (len(minutes) - 1) * 10
assert summary.total_consumption_kg == rows[-1].cumulative_consumption_kg - 100
assert item.baseline_timestamp == rows[0].timestamp
assert item.end_timestamp == rows[-1].timestamp
assert not item.percentage_sum_valid
assert not item.baseline_missing
assert summary == aggregate(reversed(rows), channel=True)
@pytest.mark.parametrize(
"names,minutes",
[
(("Material A", None, "Material B"), (0, 1, 2)),
(("Material A", None, None), (0, 1, 2)),
((None, None, "Material A"), (0, 1, 2)),
(("Material A", None, "Material A"), (0, 1, 25)),
(("Material A", None, "Material A"), (0, 5, 10.01)),
],
)
def test_ambiguous_unbounded_or_long_identity_gaps_stay_unknown(names, minutes):
rows = [
channel_sample(minute, 100 + index * 10, name=name)
for index, (minute, name) in enumerate(zip(minutes, names))
]
summary = aggregate(rows, channel=True)
unknown = next(item for item in summary.items if item.material_name is None)
assert unknown.consumption_kg == (20 if names[-1] is None else 10)
assert unknown.material_mapping_status == "UNAVAILABLE"
assert summary.total_consumption_kg == 20
@pytest.mark.parametrize(
"field,value", [("material_number", "M2"), ("material_mapping_status", "OTHER")]
)
def test_bridging_requires_exact_normalized_identity(field, value):
rows = [
channel_sample(0, 100, number="M1"),
channel_sample(0.5, 105, number="M1"),
channel_sample(1, 115, name=None),
replace(channel_sample(2, 120, number="M1"), **{field: value}),
]
summary = aggregate(rows, channel=True)
assert len(summary.items) == 3
assert summary.items[1].material_name is None
assert summary.items[1].consumption_kg == 10
assert summary.total_consumption_kg == 20
@pytest.mark.parametrize("boundary", ["run", "order", "channel", "extruder"])
def test_bridging_never_crosses_context_boundaries(boundary):
changes = {
"run": {"run": "r2"},
"order": {"run": "r2", "order": "new-order"},
"channel": {"channel": "C2"},
"extruder": {"extruder": "Ex2"},
}[boundary]
rows = [
channel_sample(0, 100),
channel_sample(1, 110, name=None),
channel_sample(2, 500, **changes),
channel_sample(3, 520, **changes),
]
summary = aggregate(rows, channel=True)
unknown = next(item for item in summary.items if item.material_name is None)
assert unknown.consumption_kg == 10
assert summary.total_consumption_kg == 30
def test_short_bridge_preserves_missing_baseline_and_zero_filter():
rows = [channel_sample(1, 100), channel_sample(2, 100, name=None), channel_sample(3, 100)]
summary = aggregate(rows, channel=True)
assert len(summary.items) == 1
assert summary.items[0].baseline_missing
assert summary.total_consumption_kg == 0
assert aggregate(rows, channel=True, include_zero=False).items == ()
@pytest.mark.parametrize("channel", [False, True])
def test_orders_within_physical_run_conserve_counter_and_use_end_order(channel):
sample = channel_sample if channel else machine_sample
rows = [sample(i, value, order=order) for i, value, order in
[(0, 1000, "1032"), (1, 1010, "1032"),
(2, 1025, "1037"), (3, 1040, "1037")]]
summary = aggregate(rows, channel=channel)
assert [(i.production_order, i.consumption_kg) for i in summary.items] == [
("1032", 10), ("1037", 30)]
assert {i.run_id for i in summary.items} == {"r1"}
assert summary.total_consumption_kg == 40
assert aggregate([replace(r, production_order="OLD") for r in rows],
channel=channel).total_consumption_kg == 40
rows[2] = sample(2, 1005, order="1037")
with pytest.raises(ValueError, match="decreased/reset"):
aggregate(rows, channel=channel)
@pytest.mark.parametrize("orders", [("X", "Y", "Y"), ("X", "X", "Y"), ("X", "Y", "X")])
def test_channel_unknown_gap_cannot_bridge_order_boundary(orders):
rows = [channel_sample(0, 100, order=orders[0]),
channel_sample(1, 110, name=None, order=orders[1]),
channel_sample(2, 120, order=orders[2])]
summary = aggregate(rows, channel=True)
unknown = [i for i in summary.items if i.material_name is None]
assert len(unknown) == 1
assert unknown[0].production_order == orders[1]
assert unknown[0].consumption_kg == 10
assert summary.total_consumption_kg == 20
+264
View File
@@ -0,0 +1,264 @@
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_service_passes_explicit_site_timezone_to_gateway():
malaysia = ZoneInfo("Asia/Kuala_Lumpur")
gateway = Mock()
gateway.get_confirmations.return_value = []
start = datetime(2026, 10, 19, 6, tzinfo=malaysia)
end = datetime(2026, 10, 19, 14, tzinfo=malaysia)
ShiftProductionService(gateway).summarize(
workplace="Malaysia", start=start, end=end, timezone=malaysia,
)
gateway.get_confirmations.assert_called_once_with(
workplace="Malaysia", start=start, end=end, timezone=malaysia,
)
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
+523
View File
@@ -0,0 +1,523 @@
from copy import deepcopy
from dataclasses import FrozenInstanceError
from datetime import UTC, date, datetime, timedelta
from pathlib import Path
from zoneinfo import ZoneInfo
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 (
most_recent_completed_shift,
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_config,
load_shift_report_machines,
)
CONFIG_PATH = Path(__file__).resolve().parents[1] / "config/shift-report-machines.yaml"
SHIFT_TIMEZONE = ZoneInfo("Europe/Berlin")
START, END = shift_report_window(date(2026, 10, 7), "early", SHIFT_TIMEZONE)
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 is not None and config.material.mode == "channel"
item = ShiftMaterialItem(
source="channel_material_consumption_snapshots" if channel
else "material_consumption_snapshots",
calculation_id=config.material.calculation_ids[0] if config.material else "unused",
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,
"timezone": SHIFT_TIMEZONE}),
("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_order_kpis_enrich_each_production_row_without_changing_shift_totals():
from dataclasses import replace
from production_analytics.service.production_order import ProductionOrderShiftKpi
service, stubs, _, _ = composition("K7")
first = stubs["production"].result.items[0]
second = replace(first, production_order="other", produced_m2=24)
stubs["production"].result = replace(
stubs["production"].result,
items=(first, second), total_produced_m2=147, total_roll_count=2,
)
class OrderKpis:
def __init__(self):
self.calls = []
def for_shift(self, **kwargs):
self.calls.append(kwargs)
return {
"order": ProductionOrderShiftKpi((), 10.24, 3317.58),
"other": ProductionOrderShiftKpi((), 8.5, 1863.36),
}
order_kpis = OrderKpis()
service.order_kpis = order_kpis
report = service.build(machine_name="K7", start=START, end=END)
assert order_kpis.calls == [{"machine_name": "K7", "start": START, "end": END,
"orders": ("order", "other"),
"allocated_shift_materials": None}]
assert [(item.average_speed_m_min, item.material_consumption_kg)
for item in report.production.items] == [(10.24, 3317.58), (8.5, 1863.36)]
assert report.production.total_produced_m2 == 147
assert report.materials is stubs["materials"].result
assert report.speed is stubs["speed"].result
@pytest.mark.parametrize("name", ["Gitter 1", "Gitter 2", "Gitter 3", "Gitter 4", "K5"])
def test_boolean_speed_machines_appear_in_report_without_material(name):
service, stubs, calls, config = composition(name)
report = service.build(machine_name=name, start=START, end=END)
assert [stage for stage, _ in calls] == ["production", "downtime", "speed"]
assert calls[-1][1]["config"] is config.speed
assert report.speed is stubs["speed"].result
assert report.materials is None
def test_sites_and_existing_machine_capabilities():
config = load_shift_report_config(CONFIG_PATH)
assert {key: site.display_name for key, site in config.sites.items()} == {
"espelkamp": "Espelkamp", "adorf": "Adorf", "malaysia": "Malaysia",
}
assert set(config.machines) == {
"B1", "E1", "K7", "K3/4", "E4", "Gitter 1", "Gitter 2",
"Gitter 3", "Gitter 4", "K5", "Secumat 1/2", "Secumat 3",
"Bento 2", "K1", "K6",
}
assert all(config.machines[name].site == "espelkamp" for name in ("B1", "E1", "K7"))
assert all(vars_for_capabilities(machine) == (True, True, True, True)
for name, machine in config.machines.items() if name in ("B1", "E1", "K7"))
assert config.machines["K7"].material.allocation == "erp_fiber_share"
assert config.machines["B1"].material.allocation == "none"
assert config.sites["espelkamp"].timezone is SHIFT_TIMEZONE
assert config.sites["adorf"].timezone is SHIFT_TIMEZONE
assert config.sites["malaysia"].timezone.key == "Asia/Kuala_Lumpur"
assert all(config.machines[name].timezone is SHIFT_TIMEZONE
for name in ("B1", "E1", "K7"))
with pytest.raises(TypeError):
config.sites["new"] = config.sites["adorf"]
def vars_for_capabilities(machine):
value = machine.capabilities
return value.production, value.downtime, value.material, value.speed
def test_new_production_machines_have_valid_sites_and_capabilities():
machines = load_shift_report_config(CONFIG_PATH).machines
expected = {
"K3/4": ("espelkamp", "K3/4", None),
"E4": ("espelkamp", "1568700", "646ebfa0-e97d-4970-b9f4-da94492aecc3"),
"Gitter 1": ("adorf", "GITTERANL", "35612735-03cc-4496-a72e-3c3e2216c720"),
"Gitter 2": ("adorf", "GITTER II", "5e89db10-ef0e-4224-866c-eee12bc3d27c"),
"Gitter 3": ("adorf", "GITTERIII", "ec3baac3-ccc1-4d1e-9b57-3f5ab2daa567"),
"Gitter 4": ("adorf", "GITTER IV", "ffa5de99-66a2-44bd-b039-9b4275bc5f9e"),
"K5": ("adorf", "K5", "8c094b9d-32d2-4ddf-b56a-2cd11a09eebf"),
"Secumat 1/2": ("adorf", "SECEXTRU", "16c0a111-3049-41d5-9e19-42ee0e047757"),
"Secumat 3": ("adorf", "SEC3", "0c207a7c-7813-4cff-90ba-6a0148919d38"),
"Bento 2": ("malaysia", "BENTO 2", "6201f3de-b940-45d7-930c-1481c5ae9e1d"),
"K1": ("malaysia", "K1", "40f1f58b-21fc-490a-8343-d1888938f11b"),
"K6": ("malaysia", "K6", "5e778f87-2d0f-47ac-a3ce-0c0dd9957918"),
}
assert len(machines) == 15
assert set(machines) - {"B1", "E1", "K7"} == set(expected)
downtime_enabled = {
"E4", "Gitter 1", "Gitter 2", "Gitter 3", "Gitter 4",
"K5", "Secumat 1/2", "Secumat 3",
}
for name, (site, workplace, machine_id) in expected.items():
machine = machines[name]
assert (machine.display_name, machine.site, machine.erp_workplace,
machine.machine_id) == (name, site, workplace, machine_id)
speed_enabled = name in {"Gitter 1", "Gitter 2", "Gitter 3", "Gitter 4", "K5"}
assert vars_for_capabilities(machine) == (True, name in downtime_enabled, False,
speed_enabled)
assert machine.material is None
assert (machine.speed is not None) == speed_enabled
assert machine.timezone.key == ("Asia/Kuala_Lumpur" if site == "malaysia"
else "Europe/Berlin")
ids = [machine.machine_id for machine in machines.values() if machine.machine_id]
assert len(ids) == len(set(ids)) == 14
@pytest.mark.parametrize("downtime", [False, True])
def test_partial_capabilities_skip_disabled_sources_and_render_unavailable(
downtime,
):
from dataclasses import replace
from production_analytics.presentation.shift_report import TextBlock, present_report
from production_analytics.service.shift_report_config import ShiftReportCapabilities
service, stubs, calls, config = composition()
partial = replace(config,
capabilities=ShiftReportCapabilities(True, downtime, False, False),
material=None, speed=None)
service.machines = {"Synthetic": partial}
report = service.build(machine_name="Synthetic", start=START, end=END)
expected = ["production", "downtime"] if downtime else ["production"]
assert [name for name, _ in calls] == expected
assert report.production is stubs["production"].result
assert report.downtime is (stubs["downtime"].result if downtime else None)
assert report.materials is None and report.speed is None
assert report.downtime_event_count == (1 if downtime else 0)
blocks = present_report(report)
unavailable = [b for b in blocks if isinstance(b, TextBlock)
and b.text == "Für diese Maschine nicht verfügbar."]
assert len(unavailable) == (1 if downtime else 2)
def test_downtime_only_machine_does_not_query_production():
from dataclasses import replace
from production_analytics.service.shift_report_config import ShiftReportCapabilities
service, stubs, calls, config = composition()
service.machines = {"DowntimeOnly": replace(
config, capabilities=ShiftReportCapabilities(False, True, False, False),
material=None, speed=None,
)}
report = service.build(machine_name="DowntimeOnly", start=START, end=END)
assert [name for name, _ in calls] == ["downtime"]
assert report.production is None and report.downtime is stubs["downtime"].result
@pytest.mark.parametrize("explicit_null", [False, True])
def test_production_only_machine_without_enlyze_id_loads_and_builds(tmp_path, explicit_null):
document = deepcopy(yaml.safe_load(CONFIG_PATH.read_text()))
document["machines"] = {"K3/4": {
"display_name": "K3/4", "site": "espelkamp", "erp_workplace": "K3/4",
"capabilities": {"production": True, "downtime": False,
"material": False, "speed": False},
}}
if explicit_null:
document["machines"]["K3/4"]["machine_id"] = None
path = tmp_path / "machines.yaml"
path.write_text(yaml.safe_dump(document))
machine = load_shift_report_config(path).machines["K3/4"]
assert machine.machine_id is None and machine.timezone is SHIFT_TIMEZONE
service, stubs, calls, _ = composition()
service.machines = {"K3/4": machine}
report = service.build(machine_name="K3/4", start=START, end=END)
assert report.machine_id is None and report.timezone is SHIFT_TIMEZONE
assert report.production is stubs["production"].result
assert report.downtime is report.materials is report.speed is None
assert [name for name, _ in calls] == ["production"]
def test_malaysia_report_carries_site_timezone_to_production_and_presentation():
from dataclasses import replace
from production_analytics.presentation.shift_report import TextBlock, present_report
from production_analytics.service.shift_report_config import ShiftReportCapabilities
malaysia = ZoneInfo("Asia/Kuala_Lumpur")
service, _, calls, config = composition()
service.machines = {"Synthetic": replace(
config, site="malaysia", timezone=malaysia, machine_id=None,
capabilities=ShiftReportCapabilities(True, False, False, False),
material=None, speed=None,
)}
start, end = shift_report_window(date(2026, 10, 19), "late", malaysia)
report = service.build(machine_name="Synthetic", start=start.astimezone(UTC),
end=end.astimezone(UTC))
assert report.timezone is malaysia
assert report.start == start and report.end == end
assert calls == [("production", {"workplace": config.erp_workplace,
"start": start, "end": end, "timezone": malaysia})]
texts = [block.text for block in present_report(report) if isinstance(block, TextBlock)]
assert "Zeitzone: Asia/Kuala_Lumpur" in texts
assert any("Schichtbeginn: 19.10.2026 14:00:00" in value for value in texts)
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, SHIFT_TIMEZONE)
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", SHIFT_TIMEZONE)
assert (end.astimezone(UTC) - start.astimezone(UTC)).total_seconds() == hours * 3600
@pytest.mark.parametrize("shift,start_hour,end_hour", [
("early", 6, 14), ("late", 14, 22), ("night", 22, 6),
])
def test_malaysia_shift_windows_use_local_wall_clock(shift, start_hour, end_hour):
malaysia = ZoneInfo("Asia/Kuala_Lumpur")
start, end = shift_report_window(date(2026, 10, 19), shift, malaysia)
assert start.tzinfo is end.tzinfo is malaysia
assert (start.hour, end.hour) == (start_hour, end_hour)
assert (end.astimezone(UTC) - start.astimezone(UTC)).total_seconds() == 28800
def test_same_instant_has_different_site_completed_shifts():
now = datetime(2026, 10, 19, 11, tzinfo=UTC)
assert most_recent_completed_shift(now, SHIFT_TIMEZONE) == (date(2026, 10, 18), "night")
assert most_recent_completed_shift(now, ZoneInfo("Asia/Kuala_Lumpur")) == (
date(2026, 10, 19), "early")
@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),
lambda d: d["machines"]["B1"].update(site="unknown"),
lambda d: d["machines"]["B1"].update(site=[]),
lambda d: d["machines"]["B1"].pop("capabilities"),
lambda d: d["machines"]["B1"]["capabilities"].update(material=False),
lambda d: d["machines"]["B1"].pop("material"),
lambda d: d["machines"]["B1"]["capabilities"].update(speed=False),
lambda d: d["machines"]["B1"].pop("speed"),
lambda d: d["machines"]["B1"]["capabilities"].update(production="true"),
lambda d: d["machines"]["B1"].update(display_name=" "),
lambda d: d["sites"]["espelkamp"].update(display_name=""),
lambda d: d["sites"]["espelkamp"].update(extra=True),
lambda d: d["machines"]["B1"]["material"].update(allocation="unknown"),
lambda d: d["sites"]["malaysia"].update(timezone="Mars/Base"),
lambda d: d["sites"]["malaysia"].update(timezone=""),
lambda d: d["sites"]["malaysia"].pop("timezone"),
lambda d: d["machines"]["B1"].pop("machine_id"),
lambda d: d["machines"]["B1"].update(machine_id=None),
lambda d: d["machines"]["B1"]["capabilities"].update(
production=False, downtime=False, material=False, speed=False),
])
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)
def test_duplicate_site_key_rejected(tmp_path):
document = CONFIG_PATH.read_text().replace(
" adorf:\n display_name: Adorf", " espelkamp:\n display_name: Adorf"
)
path = tmp_path / "machines.yaml"
path.write_text(document)
with pytest.raises(ValueError, match="unique"):
load_shift_report_config(path)
def test_duplicate_machine_key_rejected(tmp_path):
document = CONFIG_PATH.read_text().replace(" E1:\n", " B1:\n")
path = tmp_path / "machines.yaml"
path.write_text(document)
with pytest.raises(ValueError, match="unique"):
load_shift_report_config(path)
@pytest.mark.parametrize("capability", ["downtime", "material", "speed"])
def test_machine_id_required_for_nonproduction_capabilities(tmp_path, capability):
document = deepcopy(yaml.safe_load(CONFIG_PATH.read_text()))
machine = document["machines"]["B1"]
machine["capabilities"] = {name: name == capability
for name in ("production", "downtime", "material", "speed")}
machine.pop("machine_id")
if capability != "material":
machine.pop("material")
if capability != "speed":
machine.pop("speed")
path = tmp_path / "machines.yaml"
path.write_text(yaml.safe_dump(document))
with pytest.raises(ValueError):
load_shift_report_config(path)
+135
View File
@@ -0,0 +1,135 @@
from dataclasses import replace
from pathlib import Path
from types import SimpleNamespace
import pytest
from test_shift_report import END, START, composition
from production_analytics.cli import __main__ as cli
from production_analytics.presentation import shift_report as presenter
from production_analytics.service import shift_report_runtime as runtime
def arguments(*extra):
return [
"report",
"shift",
"--machine",
"E1",
"--start",
START.isoformat(),
"--end",
END.isoformat(),
"--output",
"/tmp/shift.pdf",
*extra,
]
@pytest.mark.parametrize(
"extra,message",
[
(["--machine", "UNKNOWN"], "Unknown shift-report machine"),
(["--start", "2026-10-07T06:00:00"], "timezone"),
(["--start", "invalid"], "Invalid isoformat"),
(["--end", START.isoformat()], "end must follow start"),
(["--end", "2026-10-06T06:00:00+02:00"], "end must follow start"),
],
)
def test_validation_before_settings_or_source_access(monkeypatch, capsys, extra, message):
def unexpected(*args, **kwargs):
pytest.fail("Invalid arguments reached runtime setup")
monkeypatch.setattr(cli, "_runtime_environment", unexpected)
assert cli.main(arguments(*extra)) == 2
assert message in capsys.readouterr().err
def test_start_end_and_output_are_required():
with pytest.raises(SystemExit) as caught:
cli.main(["report", "shift", "--machine", "E1"])
assert caught.value.code == 2
def test_cli_builds_one_report_and_passes_output(monkeypatch, capsys):
service, _, _, _ = composition("E1")
value = service.build(machine_name="E1", start=START, end=END)
calls = []
def environment(*paths):
calls.append(paths)
return {"settings": "supplied"}
def build(machines, env):
assert set(machines) == {
"B1", "E1", "K7", "K3/4", "E4", "Gitter 1", "Gitter 2",
"Gitter 3", "Gitter 4", "K5", "Secumat 1/2", "Secumat 3",
"Bento 2", "K1", "K6",
}
assert env == {"settings": "supplied"}
def report(**kwargs):
calls.append(kwargs)
return value
return SimpleNamespace(build=report)
monkeypatch.setattr(cli, "_runtime_environment", environment)
monkeypatch.setattr(runtime, "build_shift_report_service", build)
monkeypatch.setattr(
presenter, "write_pdf", lambda report, output: calls.append((report, output))
)
assert cli.main(arguments()) == 0
assert calls == [
(Path("secrets/enlyze.env"), Path("secrets/erp.env"), Path("secrets/postgres.env")),
{"machine_name": "E1", "start": START, "end": END},
(value, Path("/tmp/shift.pdf")),
]
assert capsys.readouterr().out.strip() == "/tmp/shift.pdf"
def test_runtime_wires_existing_readers_without_connecting(monkeypatch):
machines = composition("E1")[0].machines
tokens = {"postgres": object(), "erp": object(), "enlyze": object()}
for settings, token in (
(runtime.PostgresSettings, tokens["postgres"]),
(runtime.ErpSettings, tokens["erp"]),
(runtime.ExplorationSettings, tokens["enlyze"]),
):
monkeypatch.setattr(settings, "from_environment", lambda env, token=token: token)
service = runtime.build_shift_report_service(machines, {})
assert service.production.gateway._settings is tokens["erp"]
assert service.downtime.repository.settings is tokens["postgres"]
assert service.materials.repository.settings is tokens["postgres"]
assert service.channel_materials.repository.settings is tokens["postgres"]
assert isinstance(service.speed.gateway, runtime.EnlyzeApiGateway)
assert set(service.material_allocators) == {"K7"}
def test_allocator_selection_uses_strategy_for_any_machine_name(monkeypatch):
machines = dict(composition("K7")[0].machines)
k7 = machines.pop("K7")
machines["OtherMachine"] = replace(k7, machine_id="other-id", speed=None,
capabilities=replace(k7.capabilities, speed=False))
machines["B1"] = replace(machines["B1"], material=replace(
machines["B1"].material, allocation="none"))
for settings in (runtime.PostgresSettings, runtime.ErpSettings,
runtime.ExplorationSettings):
monkeypatch.setattr(settings, "from_environment", lambda env: object())
service = runtime.build_shift_report_service(machines, {})
assert set(service.material_allocators) == {"OtherMachine"}
assert isinstance(service.material_allocators["OtherMachine"],
runtime.K7FiberAllocationService)
def test_source_failure_is_safe_and_does_not_render(monkeypatch, capsys):
def fail(**kwargs):
raise RuntimeError("secret source details")
monkeypatch.setattr(cli, "_runtime_environment", lambda *args: {})
monkeypatch.setattr(
runtime, "build_shift_report_service", lambda *args: SimpleNamespace(build=fail)
)
monkeypatch.setattr(presenter, "write_pdf", lambda *args: pytest.fail("Rendered failed read"))
assert cli.main(arguments()) == 1
assert capsys.readouterr().err == "Report failed: RuntimeError\n"
Loaded 100 of 104 files, more files were not shown because too many files have changed in this diff. Show more