Compare commits

..
16 Commits
121 changed files with 13886 additions and 143 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).
+7
View File
@@ -0,0 +1,7 @@
machine_id: 5f42a4f6-9ca0-4f6f-9786-40d50a35b230
erp_workplace: Bento 1
production_order_format: "Bento 1-{production_order}"
poll_interval_seconds: 300
lookback_hours: 48
full_reconciliation_hours: 24
completion_tolerance_m2: 0.001
+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
+9
View File
@@ -0,0 +1,9 @@
# Generic ENLYZE downtime reconciliation configuration; one runner per machine.
machine_id: machine-uuid
erp_workplace: WORKPLACE
production_order_format: "Machine-{production_order}"
poll_interval_seconds: 300
lookback_hours: 48
# Full source scan keeps very old open/UNKNOWN events eligible for delayed edits.
full_reconciliation_hours: 24
completion_tolerance_m2: 0.001
@@ -0,0 +1,86 @@
# Process signals use unique PLC origins. Direct material names use explicit
# ENLYZE variable UUIDs (uuid:<UUID>); null current values remain unavailable.
calculations:
- id: e1-channel-material-consumption
type: channel_material_consumption
version: "1"
machine_ref: 8302e3d1-b1e5-42f1-8540-615eb6c73e08
max_sample_gap_seconds: 20.0
percentage_tolerance: 1.0
extruders:
- id: Ex1
total_rate_signal_ref: DB107:18
channels:
- id: C1
status_signal_ref: DB107:122.0
percentage_signal_ref: DB107:126
screw_speed_signal_ref: DB107:170
material_name_signal_ref: "uuid:d3129cf5-3b6e-486c-99e3-8ee6b6fbd7aa"
- id: C2
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
total_rate_signal_ref: DB207:18
channels:
- id: C1
status_signal_ref: DB207:122.0
percentage_signal_ref: DB207:126
screw_speed_signal_ref: DB207:170
material_name_signal_ref: "uuid:7e0b7ea0-1564-467b-aa74-d6ea48ee4a1c"
- id: C2
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);
+73
View File
@@ -12,6 +12,23 @@ CREATE TABLE IF NOT EXISTS material_consumption_snapshots (
CREATE INDEX IF NOT EXISTS material_consumption_snapshots_machine_time_idx CREATE INDEX IF NOT EXISTS material_consumption_snapshots_machine_time_idx
ON material_consumption_snapshots (calculation_id, machine_id, timestamp); ON material_consumption_snapshots (calculation_id, machine_id, timestamp);
-- Channel identities are intentionally independent of material assignment.
CREATE TABLE IF NOT EXISTS channel_material_consumption_snapshots (
timestamp timestamptz NOT NULL,
calculation_id text NOT NULL,
machine_id text NOT NULL,
extruder text NOT NULL,
doser_channel text NOT NULL,
production_order text NOT NULL,
run_id text NOT NULL,
cumulative_consumption_kg double precision NOT NULL,
material_number text NULL,
material_name text NULL,
material_mapping_status text NOT NULL CHECK (material_mapping_status IN ('ASSIGNED', 'UNAVAILABLE', 'AMBIGUOUS', 'UNMAPPED')),
percentage_sum_valid boolean NOT NULL,
PRIMARY KEY (calculation_id, machine_id, extruder, doser_channel, production_order, timestamp)
);
CREATE TABLE IF NOT EXISTS material_efficiency_snapshots ( CREATE TABLE IF NOT EXISTS material_efficiency_snapshots (
erp_feedback_timestamp timestamptz NOT NULL, erp_feedback_timestamp timestamptz NOT NULL,
material_snapshot_timestamp timestamptz NOT NULL, material_snapshot_timestamp timestamptz NOT NULL,
@@ -70,3 +87,59 @@ CREATE TABLE IF NOT EXISTS power_meter_monthly_reports (
generated_at timestamptz NOT NULL DEFAULT now(), generated_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (meter, month) PRIMARY KEY (meter, month)
); );
-- Mutable ENLYZE downtime source records. external_id is the stable ENLYZE UUID.
CREATE TABLE IF NOT EXISTS production_downtime_events (
external_id text PRIMARY KEY,
machine_id text NOT NULL,
production_order text NULL,
source_type text NOT NULL,
source_start timestamptz NOT NULL,
source_end timestamptz NULL,
attributed_start timestamptz NULL,
attributed_end timestamptz NULL,
attributed_duration_seconds double precision NULL,
reason_id text NULL,
reason_name text NULL,
reason_description text NULL,
reason_group text NULL,
category text NOT NULL CHECK (category IN ('PLANNED', 'UNPLANNED', 'UNKNOWN')),
comment text NULL,
source_updated_at timestamptz NULL,
last_reconciled_at timestamptz NOT NULL
);
CREATE INDEX IF NOT EXISTS production_downtime_events_machine_attributed_time_idx
ON production_downtime_events (machine_id, attributed_start);
CREATE INDEX IF NOT EXISTS production_downtime_events_production_order_idx
ON production_downtime_events (production_order);
CREATE INDEX IF NOT EXISTS production_downtime_events_category_idx
ON production_downtime_events (category);
CREATE INDEX IF NOT EXISTS production_downtime_events_unresolved_idx
ON production_downtime_events (machine_id, source_start)
WHERE source_end IS NULL OR category = 'UNKNOWN';
-- One observed ERP order boundary per machine, used to clip open ENLYZE downtimes.
CREATE TABLE IF NOT EXISTS production_order_attribution_state (
machine_id text PRIMARY KEY,
production_order text NOT NULL,
started_at timestamptz NOT 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
+36
View File
@@ -0,0 +1,36 @@
# ENLYZE downtime architecture
`GET /v2/downtimes` is the source of downtime events. Its UUID is the durable external
identity. `end: null` means the source event is currently open. `reason: null` is valid
and is persisted as `UNKNOWN`; it is never treated as `UNPLANNED`. ENLYZE's
`updated.timestamp` describes source metadata/reason editing, not finalization.
The reconciliation runner polls each configured machine with a configurable source-start
lookback (48 hours by default), follows pagination, and upserts by UUID. Every 24 hours by
default it also scans the full machine source so an old open or UNKNOWN event remains eligible
for a delayed classification update. It always replaces
the end time, comment, reason metadata, category, source update timestamp, and attributed
timing. This is intentionally not append-only because supervisors can classify an event much
later. Operators can enlarge `lookback_hours` where delayed classification exceeds the normal
window.
`production_downtime_events` retains ENLYZE source timing separately from FA-attributed
timing. An event only receives an order while the persisted ERP order boundary is active.
When ERP reports a new production order, the preceding boundary ends at the new feedback
timestamp. A boundary also ends when `remaining_quantity_m2 <= completion_tolerance_m2`, or
when `good_quantity_m2 + tolerance >= order_quantity_m2`. These are the exact fields from
`CurrentWorkplaceStatus`; `feedback_timestamp` supplies the boundary instant. No equality on
floating values is required. If neither signal proves completion, attribution stays open.
This protects a completed FA from time in an ENLYZE downtime that remains open after work has
finished. It does not infer completion from downtime. The durable
`production_order_attribution_state` makes this clipping survive runner restarts.
There is no machine-readable schedule today. No clock-time, shift, overnight, weekend, or Excel
planning inference occurs. ENLYZE `reason.category` is the only planned/unplanned source;
anything absent or unsupported remains `UNKNOWN`. A future SPA schedule provider can refine
classification or boundaries as a separate input without changing stored source facts.
The resulting fields support totals per order, category and reason, individual source events,
and open events. Source duration is ENLYZE's `source_start/source_end`; attributed duration is
only the interval inside the proven FA boundary.
+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"]
@@ -0,0 +1,144 @@
"""Configuration for reusable channel-level extruder consumption."""
from dataclasses import dataclass
from pathlib import Path
from uuid import UUID
import yaml
from production_analytics.calculations.config import CalculationConfigError, finite_number
from production_analytics.service.channel_material import ChannelDefinition
@dataclass(frozen=True, slots=True)
class ChannelMaterialCalculationConfig:
id: str
machine_ref: str
max_sample_gap_seconds: float
percentage_tolerance: float
channels: tuple[ChannelDefinition, ...]
material_names: dict[str, str]
def load_channel_material_calculation(path: str | Path) -> ChannelMaterialCalculationConfig:
try:
document = yaml.safe_load(Path(path).read_text(encoding="utf-8"))
except (OSError, UnicodeError, yaml.YAMLError) as exc:
raise CalculationConfigError("Cannot read channel material configuration") from exc
if (
not isinstance(document, dict)
or set(document) != {"calculations"}
or not isinstance(document["calculations"], list)
):
raise CalculationConfigError("Configuration must contain only calculations")
if len(document["calculations"]) != 1:
raise CalculationConfigError("Channel configuration requires one calculation")
entry = document["calculations"][0]
required = {
"id",
"type",
"version",
"machine_ref",
"max_sample_gap_seconds",
"percentage_tolerance",
"extruders",
}
if (
not isinstance(entry, dict)
or set(entry) - (required | {"material_names"})
or required - set(entry)
):
raise CalculationConfigError("Invalid channel calculation fields")
if entry["type"] != "channel_material_consumption" or entry["version"] != "1":
raise CalculationConfigError("Unsupported channel calculation type or version")
if not all(isinstance(entry[x], str) and entry[x].strip() for x in ("id", "machine_ref")):
raise CalculationConfigError("id and machine_ref must be non-empty strings")
channels = []
extruders = entry["extruders"]
if not isinstance(extruders, list) or not extruders:
raise CalculationConfigError("extruders must be a non-empty list")
for extruder in extruders:
if not isinstance(extruder, dict) or set(extruder) != {
"id",
"total_rate_signal_ref",
"channels",
}:
raise CalculationConfigError("Invalid extruder fields")
if not all(
isinstance(extruder[x], str) and extruder[x].strip()
for x in ("id", "total_rate_signal_ref")
):
raise CalculationConfigError("Extruder id and total signal must be strings")
rows = extruder["channels"]
if not isinstance(rows, list) or len(rows) != 7:
raise CalculationConfigError("Each extruder requires exactly seven channels")
for row in rows:
allowed = {
"id",
"status_signal_ref",
"percentage_signal_ref",
"screw_speed_signal_ref",
"material_number_signal_ref",
"material_name_signal_ref",
}
if (
not isinstance(row, dict)
or set(row) - allowed
or {"id", "status_signal_ref", "percentage_signal_ref", "screw_speed_signal_ref"}
- set(row)
):
raise CalculationConfigError("Invalid dosing channel fields")
if not all(
isinstance(row[x], str) and row[x].strip()
for x in (
"id",
"status_signal_ref",
"percentage_signal_ref",
"screw_speed_signal_ref",
)
):
raise CalculationConfigError("Dosing signal references must be non-empty strings")
material = row.get("material_number_signal_ref")
if material is not None and (not isinstance(material, str) or not material.strip()):
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(
ChannelDefinition(
extruder["id"],
row["id"],
extruder["total_rate_signal_ref"],
row["status_signal_ref"],
row["percentage_signal_ref"],
row["screw_speed_signal_ref"],
material,
material_name,
)
)
if len({(c.extruder, c.channel) for c in channels}) != len(channels):
raise CalculationConfigError("Extruder/channel identities must be unique")
names = entry.get("material_names", {})
if not isinstance(names, dict) or any(
not isinstance(k, str) or not isinstance(v, str) for k, v in names.items()
):
raise CalculationConfigError("material_names must map strings to strings")
return ChannelMaterialCalculationConfig(
entry["id"],
entry["machine_ref"],
finite_number(entry["max_sample_gap_seconds"], "max_sample_gap_seconds", positive=True),
finite_number(entry["percentage_tolerance"], "percentage_tolerance"),
tuple(channels),
names,
)
@@ -0,0 +1,103 @@
"""Pure channel-level dosing calculations, shared by extruder implementations."""
from collections.abc import Iterable
from dataclasses import dataclass
from datetime import datetime
from math import isfinite
from production_analytics.calculations.material_consumption import MaterialSample
MATERIAL_ASSIGNED = "ASSIGNED"
MATERIAL_UNAVAILABLE = "UNAVAILABLE"
MATERIAL_AMBIGUOUS = "AMBIGUOUS"
MATERIAL_UNMAPPED = "UNMAPPED"
@dataclass(frozen=True, slots=True)
class DosingChannelSample:
timestamp: datetime
total_rate_kg_per_hour: float
channel_status: bool
dosing_percentage: float
screw_speed: float
material_number: str | None = None
material_name: str | None = None
@dataclass(frozen=True, slots=True)
class ChannelRate:
sample: MaterialSample
material_number: str | None
material_name: str | None
material_mapping_status: str
def validate_active_percentage_sum(
samples: Iterable[DosingChannelSample], *, tolerance: float
) -> bool:
"""Return whether active channel percentages close to 100; never normalize them."""
values = tuple(samples)
if not isfinite(tolerance) or tolerance < 0:
raise ValueError("percentage tolerance must be finite and non-negative")
total = 0.0
for value in values:
if not isfinite(value.dosing_percentage):
raise ValueError("dosing percentage must be finite")
if value.channel_status:
total += value.dosing_percentage
return abs(total - 100.0) <= tolerance
def channel_rates(
samples: Iterable[DosingChannelSample],
*,
material_names: dict[str, str] | None = None,
percentage_tolerance: float = 1.0,
) -> tuple[ChannelRate, ...]:
"""Derive rates and conservative material identity for one aligned timestamp.
A material number which occurs on more than one channel is deliberately not
attributed to either channel: PLC assignments are not reliable enough to
resolve that ambiguity from a previous sample. Direct per-channel names are
already assigned and may be shared by multiple channels.
"""
values = tuple(samples)
validate_active_percentage_sum(values, tolerance=percentage_tolerance)
counts = {
material_number: sum(sample.material_number == material_number for sample in values)
for material_number in (sample.material_number for sample in values)
if material_number is not None
}
names = material_names or {}
result = []
for value in values:
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")
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
elif counts[value.material_number] > 1:
number, name, status = None, None, MATERIAL_AMBIGUOUS
elif value.material_number not in names and names:
number, name, status = value.material_number, None, MATERIAL_UNMAPPED
else:
number, name, status = (
value.material_number,
names.get(value.material_number),
MATERIAL_ASSIGNED,
)
rate = (
value.total_rate_kg_per_hour * value.dosing_percentage / 100
if value.channel_status
else 0.0
)
result.append(
ChannelRate(
sample=MaterialSample(value.timestamp, rate, 1.0 if value.channel_status else 0.0),
material_number=number,
material_name=name,
material_mapping_status=status,
)
)
return tuple(result)
@@ -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)
+137 -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")
@@ -128,10 +142,35 @@ def _parser() -> argparse.ArgumentParser:
monthly.add_argument("--meter") monthly.add_argument("--meter")
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-poll", help="Continuously poll channel-level material consumption"
)
channel_material.add_argument("--config", type=Path, required=True)
channel_material.add_argument("--poll-interval-seconds", type=float, default=10.0)
channel_material.add_argument(
"--state-directory", type=Path, default=Path("data/state/channel-material")
)
channel_material.add_argument("--secrets-file", type=Path, default=Path("secrets/enlyze.env"))
channel_material.add_argument("--once", action="store_true", help="Run one poll cycle and exit")
efficiency = runners.add_parser("material-efficiency", help="Persist ERP feedback KPI points") efficiency = runners.add_parser("material-efficiency", help="Persist ERP feedback KPI points")
efficiency.add_argument("--config", type=Path, required=True) efficiency.add_argument("--config", type=Path, required=True)
efficiency.add_argument("--secrets-file", type=Path, default=Path("secrets/enlyze.env")) efficiency.add_argument("--secrets-file", type=Path, default=Path("secrets/enlyze.env"))
efficiency.add_argument("--erp-secrets-file", type=Path, default=Path("secrets/erp.env")) efficiency.add_argument("--erp-secrets-file", type=Path, default=Path("secrets/erp.env"))
downtime = runners.add_parser("downtime-reconcile", help="Reconcile ENLYZE downtime events")
downtime.add_argument("--config", type=Path, required=True)
downtime.add_argument("--secrets-file", type=Path, default=Path("secrets/enlyze.env"))
downtime.add_argument("--erp-secrets-file", type=Path, default=Path("secrets/erp.env"))
return parser return parser
@@ -174,6 +213,35 @@ def _run_material(args: argparse.Namespace) -> int:
return 0 return 0
def _run_channel_material(args: argparse.Namespace) -> int:
from production_analytics.calculations.channel_config import load_channel_material_calculation
from production_analytics.calculations.config import CalculationConfigError
from production_analytics.enlyze.exploration import ConfigurationError
from production_analytics.service.channel_material_runtime import build_channel_material_runner
try:
calculation = load_channel_material_calculation(args.config)
runner = build_channel_material_runner(
calculation,
poll_interval_seconds=args.poll_interval_seconds,
state_directory=args.state_directory,
secrets_file=args.secrets_file,
)
if args.once:
runner.run_once()
else:
runner.run()
except (CalculationConfigError, ConfigurationError) as exc:
print(f"Config/startup error: {exc}", file=sys.stderr)
return 2
except KeyboardInterrupt:
return 0
except Exception as exc:
print(f"Startup/runtime error: {type(exc).__name__}", file=sys.stderr)
return 1
return 0
def _run_material_efficiency(args: argparse.Namespace) -> int: def _run_material_efficiency(args: argparse.Namespace) -> int:
from production_analytics.calculations.config import CalculationConfigError from production_analytics.calculations.config import CalculationConfigError
from production_analytics.enlyze.exploration import ConfigurationError from production_analytics.enlyze.exploration import ConfigurationError
@@ -214,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
@@ -247,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
@@ -255,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:
@@ -263,15 +335,77 @@ 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:
from production_analytics.service.downtime_runtime import build_downtime_runner
try:
build_downtime_runner(
args.config,
secrets_file=args.secrets_file,
erp_secrets_file=args.erp_secrets_file,
).run()
except Exception as exc:
print(f"Config/startup/runtime error: {type(exc).__name__}", file=sys.stderr)
return 1
return 0
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":
return _run_channel_material(args)
if args.command == "material-efficiency": if args.command == "material-efficiency":
return _run_material_efficiency(args) return _run_material_efficiency(args)
if args.command == "power-meter": if args.command == "power-meter":
return _run_power_meter(args) return _run_power_meter(args)
if args.command == "downtime-reconcile":
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
+486 -12
View File
@@ -3,14 +3,21 @@
from dataclasses import dataclass 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 uuid import UUID
from production_analytics.calculations.channel_material import DosingChannelSample
from production_analytics.calculations.material_consumption import ( from production_analytics.calculations.material_consumption import (
MaterialSample, MaterialSample,
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:
from production_analytics.service.channel_material import ChannelDefinition
@dataclass(frozen=True, slots=True) @dataclass(frozen=True, slots=True)
class EnlyzeProductionRun: class EnlyzeProductionRun:
@@ -22,6 +29,24 @@ class EnlyzeProductionRun:
end: datetime | None end: datetime | None
@dataclass(frozen=True, slots=True)
class EnlyzeDowntime:
"""ENLYZE downtime source record. ``end`` and ``reason`` are deliberately nullable."""
uuid: str
machine_id: str
source_type: str
start: datetime
end: datetime | None
comment: str | None
reason_id: str | None
reason_name: str | None
reason_description: str | None
reason_group: str | None
reason_category: str | None
source_updated_at: datetime | None
class EnlyzeApiGateway: class EnlyzeApiGateway:
def __init__(self, client: ExplorationClient) -> None: def __init__(self, client: ExplorationClient) -> None:
self._client = client self._client = client
@@ -60,11 +85,16 @@ class EnlyzeApiGateway:
end = _parse_timestamp(item["end"]) if item["end"] is not None else None end = _parse_timestamp(item["end"]) if item["end"] is not None else None
if end is not None and end < start: if end is not None and end < start:
raise ValueError("run end must not precede start") raise ValueError("run end must not precede start")
runs.append(EnlyzeProductionRun( runs.append(
uuid=item["uuid"], machine_id=item["machine"], EnlyzeProductionRun(
product_id=item.get("product"), production_order=item["production_order"], uuid=item["uuid"],
start=start, end=end, machine_id=item["machine"],
)) product_id=item.get("product"),
production_order=item["production_order"],
start=start,
end=end,
)
)
next_cursor = None next_cursor = None
if "metadata" in response.body: if "metadata" in response.body:
metadata = response.body["metadata"] metadata = response.body["metadata"]
@@ -85,6 +115,130 @@ class EnlyzeApiGateway:
except (KeyError, TypeError, ValueError) as exc: except (KeyError, TypeError, ValueError) as exc:
raise ValueError(f"Invalid production-run response on page {page}: {exc}") from exc raise ValueError(f"Invalid production-run response on page {page}: {exc}") from exc
def get_downtimes(
self,
machine_id: str,
*,
start: datetime | None = None,
) -> list[EnlyzeDowntime]:
"""Retrieve machine downtimes and follow ENLYZE cursor pagination.
``start`` is an inclusive source-time lookback; callers use it for reconciliation,
not as a claim that records before it cannot subsequently be edited.
"""
if start is not None and (start.tzinfo is None or start.utcoffset() is None):
raise ValueError("start must be timezone-aware")
params = {"machine": machine_id}
if start is not None:
params["start"] = start.astimezone(UTC).isoformat()
result: list[EnlyzeDowntime] = []
cursors: set[str] = set()
page = 1
while True:
response = self._client.get("/v2/downtimes", params)
try:
if not isinstance(response.body, dict) or not isinstance(
response.body["data"], list
):
raise ValueError("body data must be a list")
for item in response.body["data"]:
result.append(_parse_downtime(item, machine_id))
cursor = _next_cursor(response.body)
if cursor is None:
return result
if cursor in cursors:
raise ValueError("next_cursor has already been followed")
cursors.add(cursor)
params = {**params, "cursor": cursor}
page += 1
except (KeyError, TypeError, ValueError) as 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,
*, *,
@@ -98,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:
@@ -108,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,)
) )
@@ -152,7 +309,19 @@ class EnlyzeApiGateway:
if nominal_width_m is None or specific_discharge_kg_per_rev_m is None: if nominal_width_m is None or specific_discharge_kg_per_rev_m is None:
raise ValueError("rotational discharge requires width and factor") raise ValueError("rotational discharge requires width and factor")
rate = rotational_discharge_rate_kg_per_hour( rate = rotational_discharge_rate_kg_per_hour(
sources, nominal_width_m, specific_discharge_kg_per_rev_m, sources,
nominal_width_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:
@@ -162,20 +331,38 @@ 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, specific_discharge_kg_per_rev_m, gate, sources,
specific_discharge_kg_per_rev_m,
gate,
process_application_gate_threshold, process_application_gate_threshold,
) )
samples.append(MaterialSample( samples.append(
MaterialSample(
timestamp=_parse_timestamp(record[time_index]), timestamp=_parse_timestamp(record[time_index]),
material_rate_kg_per_hour=float(rate), gate_value=float(gate), material_rate_kg_per_hour=float(rate),
gate_value=float(gate),
application_g_m2=application, application_g_m2=application,
)) )
)
except (TypeError, ValueError) as exc: except (TypeError, ValueError) as exc:
raise ValueError(f"malformed record {index}: {exc}") from exc raise ValueError(f"malformed record {index}: {exc}") from exc
next_cursor = None next_cursor = None
@@ -198,6 +385,229 @@ class EnlyzeApiGateway:
except (KeyError, TypeError, ValueError) as exc: except (KeyError, TypeError, ValueError) as exc:
raise ValueError(f"Invalid timeseries response on page {page}: {exc}") from exc raise ValueError(f"Invalid timeseries response on page {page}: {exc}") from exc
def get_dosing_channel_samples(
self,
*,
machine_id: str,
channels: tuple["ChannelDefinition", ...],
start: datetime,
end: datetime,
) -> dict[str, list[DosingChannelSample]]:
"""Read configured dosing channels through the gateway only.
Process and material-number refs name stable PLC origins resolved uniquely
at poll time. Direct material-name refs explicitly name machine variable UUIDs.
"""
if (
start.tzinfo is None
or start.utcoffset() is None
or end.tzinfo is None
or end.utcoffset() is None
):
raise ValueError("dosing channel window must be timezone-aware")
if end < start:
raise ValueError("end must not precede start")
resolved = self.resolve_dosing_channel_signal_refs(
machine_id=machine_id,
channels=channels,
)
variable_ids = list(
dict.fromkeys(
variable_id
for references in resolved.values()
for variable_id in references
if variable_id is not None
)
)
body = {
"machine": machine_id,
"start": start.astimezone(UTC).isoformat(),
"end": end.astimezone(UTC).isoformat(),
"variables": [{"uuid": x} for x in variable_ids],
}
result = {key: [] for key in resolved}
cursors: set[str] = set()
while True:
response = self._client.post_json("/v2/timeseries", body)
try:
data = response.body["data"]
columns = data["columns"]
if not isinstance(columns, list) or any(
columns.count(x) != 1 for x in ("time", *variable_ids)
):
raise ValueError("required columns must occur exactly once")
if not isinstance(data["records"], list):
raise ValueError("records must be a list")
for row in data["records"]:
if not isinstance(row, list) or len(row) != len(columns):
raise ValueError("record must match columns")
timestamp = _parse_timestamp(row[columns.index("time")])
for key, (total, status, percentage, screw, material, name) in resolved.items():
sample = self._dosing_sample(
row,
columns,
timestamp,
total,
status,
percentage,
screw,
material,
name,
)
if sample is not None:
result[key].append(sample)
cursor = _next_cursor(response.body)
if cursor is None:
return result
if cursor in cursors:
raise ValueError("next_cursor has already been followed")
cursors.add(cursor)
body = {**body, "cursor": cursor}
except (KeyError, TypeError, ValueError) as exc:
raise ValueError(f"Invalid dosing timeseries response: {exc}") from exc
def resolve_dosing_channel_signal_refs(
self,
*,
machine_id: str,
channels: tuple["ChannelDefinition", ...],
) -> dict[str, tuple[str, str, str, str, str | None, str | None]]:
"""Resolve unique PLC origins and explicit machine variable UUID references."""
variable_ids: set[str] = set()
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:
refs = (
channel.total_rate_signal_ref,
channel.status_signal_ref,
channel.percentage_signal_ref,
channel.screw_speed_signal_ref,
)
ids = tuple(self._unique_origin(origins, ref) for ref in refs)
material = (
self._unique_origin(origins, channel.material_number_signal_ref)
if channel.material_number_signal_ref
else None
)
key = channel.channel + "\0" + channel.extruder
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
@staticmethod
def _dosing_sample(
row: list[object],
columns: list[object],
timestamp: datetime,
total: str,
status: str,
percentage: str,
screw: str,
material: str | None,
name: str | None = None,
) -> DosingChannelSample | None:
def numeric(variable: str) -> float:
value = row[columns.index(variable)]
if (
isinstance(value, bool)
or not isinstance(value, (int, float))
or not isfinite(value)
):
raise ValueError("dosing values must be finite numeric")
return float(value)
for variable in (total, percentage, screw):
if row[columns.index(variable)] is None:
return None
status_value = row[columns.index(status)]
if status_value is None:
enabled = False
elif isinstance(status_value, bool):
enabled = status_value
elif (
isinstance(status_value, (int, float))
and not isinstance(status_value, bool)
and isfinite(status_value)
):
enabled = status_value != 0
else:
raise ValueError("dosing status must be boolean or numeric")
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)):
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(
timestamp,
numeric(total),
enabled,
numeric(percentage),
numeric(screw),
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, *, variable_ids: set[str] | None = None
) -> dict[str, list[str]]:
params = {"machine": machine_id}
result: dict[str, list[str]] = {}
cursors: set[str] = set()
while True:
response = self._client.get("/v2/variables", params)
try:
items = response.body["data"]
if not isinstance(items, list):
raise ValueError("data must be a list")
for item in items:
uuid = item["uuid"]
if not isinstance(uuid, str):
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")
if not isinstance(details, dict):
raise ValueError("variable details must be an object")
origin_identifier = details.get("origin_identifier")
if origin_identifier is None:
# Derived ENLYZE variables do not have a PLC origin.
continue
if not isinstance(origin_identifier, dict):
raise ValueError("variable origin_identifier must be an object")
code = origin_identifier.get("code")
if not isinstance(code, str):
raise ValueError("variable origin must be a string")
result.setdefault(code, []).append(uuid)
cursor = _next_cursor(response.body)
if cursor is None:
return result
if cursor in cursors:
raise ValueError("next_cursor has already been followed")
cursors.add(cursor)
params = {**params, "cursor": cursor}
except (KeyError, TypeError, ValueError) as exc:
raise ValueError(f"Invalid variable response: {exc}") from exc
@staticmethod
def _unique_origin(origins: dict[str, list[str]], origin: str) -> str:
matches = origins.get(origin, [])
if len(matches) != 1:
raise ValueError(f"Configured PLC origin {origin!r} is unavailable or ambiguous")
return matches[0]
def _parse_timestamp(value: str) -> datetime: def _parse_timestamp(value: str) -> datetime:
if not isinstance(value, str): if not isinstance(value, str):
@@ -206,3 +616,67 @@ def _parse_timestamp(value: str) -> datetime:
if timestamp.tzinfo is None or timestamp.utcoffset() is None: if timestamp.tzinfo is None or timestamp.utcoffset() is None:
raise ValueError("timestamp must be timezone-aware") raise ValueError("timestamp must be timezone-aware")
return timestamp.astimezone(UTC) return timestamp.astimezone(UTC)
def _next_cursor(body: dict[object, object]) -> str | None:
if "metadata" not in body:
return None
metadata = body["metadata"]
if not isinstance(metadata, dict) or "next_cursor" not in metadata:
raise ValueError("metadata must be an object with a next_cursor field")
cursor = metadata["next_cursor"]
if cursor is not None and (not isinstance(cursor, str) or not cursor):
raise ValueError("next_cursor must be null or a non-empty string")
return cursor
def _nullable_text(value: object, name: str) -> str | None:
if value is not None and not isinstance(value, str):
raise ValueError(f"{name} must be a string or null")
return value
def _parse_downtime(item: object, machine_id: str) -> EnlyzeDowntime:
if not isinstance(item, dict):
raise ValueError("downtime must be an object")
for key in ("uuid", "machine", "type", "start"):
if not isinstance(item.get(key), str) or not item[key]:
raise ValueError(f"{key} must be a non-empty string")
if item["machine"] != machine_id:
raise ValueError("downtime machine does not match requested machine")
start = _parse_timestamp(item["start"])
end_value = item.get("end")
end = _parse_timestamp(end_value) if end_value is not None else None
if end is not None and end < start:
raise ValueError("downtime end must not precede start")
reason = item.get("reason")
if reason is not None and not isinstance(reason, dict):
raise ValueError("reason must be an object or null")
if reason is not None:
for key in ("uuid", "name", "category"):
if not isinstance(reason.get(key), str) or not reason[key]:
raise ValueError(f"reason {key} must be a non-empty string")
updated = item.get("updated")
if updated is not None and not isinstance(updated, dict):
raise ValueError("updated must be an object or null")
updated_at = None
if updated is not None:
updated_at = _parse_timestamp(updated.get("timestamp"))
return EnlyzeDowntime(
uuid=item["uuid"],
machine_id=machine_id,
source_type=item["type"],
start=start,
end=end,
comment=_nullable_text(item.get("comment"), "comment"),
reason_id=None if reason is None else reason["uuid"],
reason_name=None if reason is None else reason["name"],
reason_description=None
if reason is None
else _nullable_text(reason.get("description"), "reason description"),
reason_group=None
if reason is None
else _nullable_text(reason.get("group"), "reason group"),
reason_category=None if reason is None else reason["category"],
source_updated_at=updated_at,
)
+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>'''
@@ -0,0 +1,247 @@
"""Stateful polling for configured extruder dosing channels."""
from collections import defaultdict
from dataclasses import dataclass
from datetime import datetime
from typing import Protocol
from production_analytics.calculations.channel_material import (
ChannelRate,
DosingChannelSample,
channel_rates,
validate_active_percentage_sum,
)
from production_analytics.calculations.material_consumption import (
MaterialConsumptionIntegrator,
MaterialIntegrationState,
MaterialIntegratorConfig,
)
from production_analytics.enlyze.gateway import EnlyzeProductionRun
@dataclass(frozen=True, slots=True)
class ChannelDefinition:
extruder: str
channel: str
total_rate_signal_ref: str
status_signal_ref: str
percentage_signal_ref: str
screw_speed_signal_ref: str
material_number_signal_ref: str | None = None
material_name_signal_ref: str | None = None
@dataclass(frozen=True, slots=True)
class ChannelPollingState:
run_id: str
integration_state: MaterialIntegrationState
class ChannelStateStore(Protocol):
def load(
self, machine_id: str, extruder: str, channel: str, production_order: str
) -> ChannelPollingState | None: ...
def save(
self,
machine_id: str,
extruder: str,
channel: str,
production_order: str,
state: ChannelPollingState,
) -> None: ...
class ChannelGateway(Protocol):
def get_open_production_run(self, machine_id: str) -> EnlyzeProductionRun | None: ...
def get_production_runs(self, machine_id: str) -> list[EnlyzeProductionRun]: ...
def get_dosing_channel_samples(
self,
*,
machine_id: str,
channels: tuple[ChannelDefinition, ...],
start: datetime,
end: datetime,
) -> dict[str, list[DosingChannelSample]]: ...
@dataclass(frozen=True, slots=True)
class ChannelPollResult:
run: EnlyzeProductionRun
extruder: str
channel: str
state: MaterialIntegrationState
material_number: str | None
material_name: str | None
material_mapping_status: str
percentage_sum_valid: bool
class ChannelMaterialPollingService:
def __init__(
self,
*,
gateway: ChannelGateway,
state_store: ChannelStateStore,
machine_id: str,
channels: tuple[ChannelDefinition, ...],
max_sample_gap_seconds: float,
percentage_tolerance: float = 1.0,
material_names: dict[str, str] | None = None,
) -> None:
if not channels or len({(c.extruder, c.channel) for c in channels}) != len(channels):
raise ValueError("channels must be non-empty and uniquely identified")
self.gateway, self.state_store, self.machine_id, self.channels = (
gateway,
state_store,
machine_id,
channels,
)
self.config = MaterialIntegratorConfig(0.5, max_sample_gap_seconds)
self.percentage_tolerance, self.material_names = percentage_tolerance, material_names or {}
def poll_once(self, *, now: datetime) -> tuple[ChannelPollResult, ...] | None:
if now.tzinfo is None or now.utcoffset() is None:
raise ValueError("now must be timezone-aware")
run = self.gateway.get_open_production_run(self.machine_id)
if run is None or now < run.start:
return None
# Each channel is separately checkpointed so an E4-style extra extruder
# can be introduced without changing state identity.
states: dict[str, ChannelPollingState | None] = {
c.channel + "\0" + c.extruder: self.state_store.load(
self.machine_id, c.extruder, c.channel, run.production_order
)
for c in self.channels
}
# A missing checkpoint is bootstrapped over each closed run separately.
# Resetting the temporal baseline at every run boundary is essential:
# a short wall-clock gap between ENLYZE runs must not become material.
if all(state is None for state in states.values()):
totals = {key: MaterialIntegrationState() for key in states}
previous_runs = sorted(
(
candidate
for candidate in self.gateway.get_production_runs(self.machine_id)
if candidate.production_order == run.production_order
and candidate.uuid != run.uuid
and candidate.end is not None
and candidate.end <= run.start
),
key=lambda candidate: candidate.start,
)
for previous in previous_runs:
historical = self._derive(
self.gateway.get_dosing_channel_samples(
machine_id=self.machine_id,
channels=self.channels,
start=previous.start,
end=previous.end,
)
)
for key, samples in historical.items():
integrator = MaterialConsumptionIntegrator(self.config, totals[key])
integrator.process_many(rate.sample for rate, _ in samples)
state = integrator.state
totals[key] = MaterialIntegrationState(
cumulative_consumption_kg=state.cumulative_consumption_kg,
integrated_running_seconds=state.integrated_running_seconds,
)
states = {key: ChannelPollingState("bootstrap", state) for key, state in totals.items()}
start = min(
(
s.integration_state.last_processed_timestamp
for s in states.values()
if s is not None
and s.run_id == run.uuid
and s.integration_state.last_processed_timestamp is not None
),
default=run.start,
)
if now < start:
return None
raw = self.gateway.get_dosing_channel_samples(
machine_id=self.machine_id, channels=self.channels, start=start, end=now
)
derived = self._derive(raw)
results = []
for definition in self.channels:
key = definition.channel + "\0" + definition.extruder
saved = states[key]
initial = (
saved.integration_state
if saved is not None and saved.run_id == run.uuid
else MaterialIntegrationState(
cumulative_consumption_kg=0.0
if saved is None
else saved.integration_state.cumulative_consumption_kg,
integrated_running_seconds=0.0
if saved is None
else saved.integration_state.integrated_running_seconds,
)
)
integrator = MaterialConsumptionIntegrator(self.config, initial)
samples = derived[key]
latest: ChannelRate | None = None
quality = True
for rate, sample_quality in samples:
if (
initial.last_processed_timestamp is not None
and rate.sample.timestamp < initial.last_processed_timestamp
):
continue
integrator.process(rate.sample)
latest = rate
quality = quality and sample_quality
state = integrator.state
self.state_store.save(
self.machine_id,
definition.extruder,
definition.channel,
run.production_order,
ChannelPollingState(run.uuid, state),
)
results.append(
ChannelPollResult(
run,
definition.extruder,
definition.channel,
state,
None if latest is None else latest.material_number,
None if latest is None else latest.material_name,
"UNAVAILABLE" if latest is None else latest.material_mapping_status,
quality,
)
)
return tuple(results)
def _derive(
self, raw: dict[str, list[DosingChannelSample]]
) -> dict[str, list[tuple[ChannelRate, bool]]]:
"""Evaluate aligned channel records with extruder-scoped quality rules."""
by_timestamp: dict[datetime, dict[str, DosingChannelSample]] = defaultdict(dict)
for definition in self.channels:
key = definition.channel + "\0" + definition.extruder
for sample in raw[key]:
by_timestamp[sample.timestamp][key] = sample
derived: dict[str, list[tuple[ChannelRate, bool]]] = defaultdict(list)
for timestamp, values in sorted(by_timestamp.items()):
if set(values) != set(raw):
raise ValueError(f"unaligned channel samples at {timestamp.isoformat()}")
grouped: dict[str, list[tuple[str, DosingChannelSample]]] = defaultdict(list)
for key, sample in values.items():
grouped[key.split("\0", 1)[1]].append((key, sample))
for siblings in grouped.values():
quality = validate_active_percentage_sum(
(sample for _, sample in siblings),
tolerance=self.percentage_tolerance,
)
for (key, _), rate in zip(
siblings,
channel_rates(
(sample for _, sample in siblings),
material_names=self.material_names,
percentage_tolerance=self.percentage_tolerance,
),
):
derived[key].append((rate, quality))
return derived
@@ -0,0 +1,98 @@
"""Sequential foreground runner for channel-level material consumption."""
import sys
import time
from collections.abc import Callable
from datetime import UTC, datetime
from typing import TextIO
from production_analytics.calculations.config import finite_number
from production_analytics.enlyze.exploration import ConfigurationError, ExplorationError
from production_analytics.service.channel_material import ChannelMaterialPollingService
from production_analytics.service.postgres_channel_material import (
PostgresChannelMaterialSnapshotWriter,
)
def utc_now() -> datetime:
return datetime.now(UTC)
class ChannelMaterialPollingRunner:
def __init__(
self,
service: ChannelMaterialPollingService,
*,
machine_id: str,
calculation_id: str,
snapshot_writer: PostgresChannelMaterialSnapshotWriter,
poll_interval_seconds: float,
clock: Callable[[], datetime] = utc_now,
sleep: Callable[[float], None] = time.sleep,
stdout: TextIO | None = None,
stderr: TextIO | None = None,
) -> None:
self.service = service
self.machine_id = machine_id
self.calculation_id = calculation_id
self.snapshot_writer = snapshot_writer
self.interval = finite_number(poll_interval_seconds, "poll interval", positive=True)
self.clock = clock
self.sleep = sleep
self.stdout = stdout if stdout is not None else sys.stdout
self.stderr = stderr if stderr is not None else sys.stderr
def run_once(self) -> bool:
"""Run and report one cycle; return whether channel snapshots were written."""
now = self.clock()
if now.tzinfo is None or now.utcoffset() is None:
raise ConfigurationError("Runner clock must return timezone-aware timestamps")
now = now.astimezone(UTC)
prefix = f"{now.isoformat()} machine={self.machine_id!r}"
results = self.service.poll_once(now=now)
if results is None:
print(
f"{prefix} no open Production Run / no eligible polling window; snapshots=0",
file=self.stdout,
flush=True,
)
return False
for result in results:
self.snapshot_writer.write(
timestamp=now,
calculation_id=self.calculation_id,
machine_id=self.machine_id,
extruder=result.extruder,
channel=result.channel,
production_order=result.run.production_order,
run_id=result.run.uuid,
cumulative_consumption_kg=result.state.cumulative_consumption_kg,
material_number=result.material_number,
material_name=result.material_name,
material_mapping_status=result.material_mapping_status,
percentage_sum_valid=result.percentage_sum_valid,
)
print(
f"{prefix} production_order={results[0].run.production_order!r} "
f"channel snapshots={len(results)} written",
file=self.stdout,
flush=True,
)
return True
def run(self) -> None:
try:
while True:
try:
self.run_once()
except ConfigurationError:
raise
except Exception as exc:
if isinstance(exc, ExplorationError):
detail = f"ENLYZE/gateway: {type(exc).__name__}"
else:
detail = f"poll cycle: {type(exc).__name__}"
print(f"channel material error {detail}", file=self.stderr, flush=True)
self.sleep(self.interval)
except KeyboardInterrupt:
print("Channel material polling stopped", file=self.stdout, flush=True)
@@ -0,0 +1,69 @@
"""Compose the live channel-level material polling application."""
import math
import os
import tempfile
from pathlib import Path
from urllib.parse import urlsplit
from production_analytics.calculations.channel_config import ChannelMaterialCalculationConfig
from production_analytics.calculations.config import finite_number
from production_analytics.enlyze.exploration import (
ConfigurationError,
ExplorationClient,
ExplorationSettings,
load_secret_file,
)
from production_analytics.enlyze.gateway import EnlyzeApiGateway
from production_analytics.service.channel_material import ChannelMaterialPollingService
from production_analytics.service.channel_material_runner import ChannelMaterialPollingRunner
from production_analytics.service.channel_material_state_store import JsonChannelMaterialStateStore
from production_analytics.service.postgres_channel_material import (
PostgresChannelMaterialSnapshotWriter,
)
from production_analytics.service.postgres_material import PostgresSettings
def build_channel_material_runner(
calculation: ChannelMaterialCalculationConfig,
*,
poll_interval_seconds: float,
state_directory: Path,
secrets_file: Path,
) -> ChannelMaterialPollingRunner:
finite_number(poll_interval_seconds, "poll interval", positive=True)
environment = dict(os.environ)
environment.update(load_secret_file(secrets_file))
settings = ExplorationSettings.from_environment(environment)
parsed = urlsplit(settings.base_url)
if parsed.scheme not in {"http", "https"} or not parsed.hostname or parsed.username:
raise ConfigurationError(
"ENLYZE_BASE_URL must be an HTTP(S) server URL without credentials"
)
if not math.isfinite(settings.timeout_seconds):
raise ConfigurationError("ENLYZE_HTTP_TIMEOUT_SECONDS must be finite")
try:
state_directory.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryFile(dir=state_directory):
pass
except OSError as exc:
raise ConfigurationError(
f"State directory startup check failed: {type(exc).__name__}"
) from exc
postgres_settings = PostgresSettings.from_environment(environment)
service = ChannelMaterialPollingService(
gateway=EnlyzeApiGateway(ExplorationClient(settings)),
state_store=JsonChannelMaterialStateStore(state_directory),
machine_id=calculation.machine_ref,
channels=calculation.channels,
max_sample_gap_seconds=calculation.max_sample_gap_seconds,
percentage_tolerance=calculation.percentage_tolerance,
material_names=calculation.material_names,
)
return ChannelMaterialPollingRunner(
service,
machine_id=calculation.machine_ref,
calculation_id=calculation.id,
snapshot_writer=PostgresChannelMaterialSnapshotWriter(postgres_settings),
poll_interval_seconds=poll_interval_seconds,
)
@@ -0,0 +1,59 @@
"""Restart-safe JSON state storage keyed by channel identity."""
import hashlib
import json
import os
import tempfile
from pathlib import Path
from production_analytics.calculations.material_state import (
material_state_from_dict,
material_state_to_dict,
)
from production_analytics.service.channel_material import ChannelPollingState
class JsonChannelMaterialStateStore:
def __init__(self, directory: str | Path) -> None:
self.directory = Path(directory)
def _path(self, *identity: str) -> Path:
digest = hashlib.sha256(json.dumps(identity).encode()).hexdigest()
return self.directory / f"channel-material-{digest}.json"
def load(
self, machine_id: str, extruder: str, channel: str, production_order: str
) -> ChannelPollingState | None:
path = self._path(machine_id, extruder, channel, production_order)
if not path.exists():
return None
data = json.loads(path.read_text(encoding="utf-8"))
if not isinstance(data, dict) or not isinstance(data.get("run_id"), str):
raise ValueError("Invalid channel material state")
return ChannelPollingState(
data["run_id"], material_state_from_dict(data["integration_state"])
)
def save(
self,
machine_id: str,
extruder: str,
channel: str,
production_order: str,
state: ChannelPollingState,
) -> None:
self.directory.mkdir(parents=True, exist_ok=True)
payload = {
"run_id": state.run_id,
"integration_state": material_state_to_dict(state.integration_state),
}
material_state_from_dict(payload["integration_state"])
destination = self._path(machine_id, extruder, channel, production_order)
with tempfile.NamedTemporaryFile(
mode="w", encoding="utf-8", dir=self.directory, delete=False
) as handle:
temporary = Path(handle.name)
json.dump(payload, handle, allow_nan=False)
handle.flush()
os.fsync(handle.fileno())
os.replace(temporary, destination)
@@ -0,0 +1,214 @@
"""Generic ENLYZE downtime reconciliation and ERP order attribution."""
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
from enum import StrEnum
from math import isfinite
from typing import Protocol
from production_analytics.context import build_enlyze_production_order
from production_analytics.enlyze.gateway import EnlyzeDowntime
from production_analytics.erp import CurrentWorkplaceStatus
class DowntimeCategory(StrEnum):
PLANNED = "PLANNED"
UNPLANNED = "UNPLANNED"
UNKNOWN = "UNKNOWN"
@dataclass(frozen=True, slots=True)
class ProductionOrderBoundary:
machine_id: str
production_order: str
started_at: datetime
ended_at: datetime | None
@dataclass(frozen=True, slots=True)
class ProductionDowntimeEvent:
external_id: str
machine_id: str
production_order: str | None
source_type: str
source_start: datetime
source_end: datetime | None
attributed_start: datetime | None
attributed_end: datetime | None
attributed_duration_seconds: float | None
reason_id: str | None
reason_name: str | None
reason_description: str | None
reason_group: str | None
category: DowntimeCategory
comment: str | None
source_updated_at: datetime | None
last_reconciled_at: datetime
class DowntimeGateway(Protocol):
def get_downtimes(
self, machine_id: str, *, start: datetime | None = None
) -> list[EnlyzeDowntime]: ...
class WorkplaceStatusReader(Protocol):
def get_current_workplace_status(self, workplace: str) -> CurrentWorkplaceStatus | None: ...
class DowntimeRepository(Protocol):
def current_boundary(self, machine_id: str) -> ProductionOrderBoundary | None: ...
def save_boundary(self, boundary: ProductionOrderBoundary) -> None: ...
def close_order_attribution(
self, machine_id: str, production_order: str, ended_at: datetime
) -> None: ...
def upsert(self, event: ProductionDowntimeEvent) -> None: ...
class DowntimeReconciliationService:
"""Reconciles mutable source events without deriving a shift schedule."""
def __init__(
self,
gateway: DowntimeGateway,
erp: WorkplaceStatusReader,
repository: DowntimeRepository,
*,
machine_id: str,
workplace: str,
production_order_format: str,
lookback_hours: float = 48,
full_reconciliation_hours: float = 24,
completion_tolerance_m2: float = 0.001,
) -> None:
if not isfinite(lookback_hours) or lookback_hours <= 0:
raise ValueError("lookback_hours must be positive")
if not isfinite(full_reconciliation_hours) or full_reconciliation_hours <= 0:
raise ValueError("full_reconciliation_hours must be positive")
if not isfinite(completion_tolerance_m2) or completion_tolerance_m2 < 0:
raise ValueError("completion_tolerance_m2 must be non-negative")
self.gateway, self.erp, self.repository = gateway, erp, repository
self.machine_id, self.workplace = machine_id, workplace
self.production_order_format = production_order_format
self.lookback = timedelta(hours=lookback_hours)
self.full_reconciliation_interval = timedelta(hours=full_reconciliation_hours)
self._last_full_reconciliation: datetime | None = None
self.tolerance = completion_tolerance_m2
def reconcile_once(self, now: datetime) -> int:
if now.tzinfo is None or now.utcoffset() is None:
raise ValueError("now must be timezone-aware")
now = now.astimezone(UTC)
boundary = self._refresh_boundary(now)
events = self.gateway.get_downtimes(self.machine_id, start=now - self.lookback)
if (
self._last_full_reconciliation is None
or now - self._last_full_reconciliation >= self.full_reconciliation_interval
):
# ENLYZE does not guarantee that a delayed reason edit remains in a source-start
# lookback window. A periodic full scan makes old open/UNKNOWN UUIDs mutable too.
events = list(
{
event.uuid: event
for event in [
*events,
*self.gateway.get_downtimes(self.machine_id),
]
}.values()
)
self._last_full_reconciliation = now
for source in events:
self.repository.upsert(self._event(source, boundary, now))
return len(events)
def _refresh_boundary(self, now: datetime) -> ProductionOrderBoundary | None:
status = self.erp.get_current_workplace_status(self.workplace)
old = self.repository.current_boundary(self.machine_id)
if status is None:
return old
order = build_enlyze_production_order(status.production_order, self.production_order_format)
feedback_at = _aware_feedback(status.feedback_timestamp)
if old is not None and old.production_order != order and old.ended_at is None:
self.repository.close_order_attribution(
self.machine_id, old.production_order, feedback_at
)
if old is None or old.production_order != order:
current = ProductionOrderBoundary(self.machine_id, order, feedback_at, None)
else:
current = old
if _is_complete(status, self.tolerance) and current.ended_at is None:
current = ProductionOrderBoundary(
current.machine_id,
current.production_order,
current.started_at,
feedback_at,
)
self.repository.close_order_attribution(
self.machine_id, current.production_order, feedback_at
)
self.repository.save_boundary(current)
return current
def _event(
self,
source: EnlyzeDowntime,
boundary: ProductionOrderBoundary | None,
now: datetime,
) -> ProductionDowntimeEvent:
category = (
DowntimeCategory(source.reason_category)
if source.reason_category
in {
"PLANNED",
"UNPLANNED",
}
else DowntimeCategory.UNKNOWN
)
attributed_start = attributed_end = None
order = None
if boundary is not None:
lower = max(source.start, boundary.started_at)
upper = source.end
if boundary.ended_at is not None:
upper = boundary.ended_at if upper is None else min(upper, boundary.ended_at)
if upper is None or lower < upper:
order, attributed_start, attributed_end = boundary.production_order, lower, upper
duration = (
None
if attributed_start is None or attributed_end is None
else (attributed_end - attributed_start).total_seconds()
)
return ProductionDowntimeEvent(
source.uuid,
source.machine_id,
order,
source.source_type,
source.start,
source.end,
attributed_start,
attributed_end,
duration,
source.reason_id,
source.reason_name,
source.reason_description,
source.reason_group,
category,
source.comment,
source.source_updated_at,
now,
)
def _aware_feedback(value: datetime) -> datetime:
if value.tzinfo is None or value.utcoffset() is None:
raise ValueError("ERP feedback timestamp must be timezone-aware for downtime attribution")
return value.astimezone(UTC)
def _is_complete(status: CurrentWorkplaceStatus, tolerance: float) -> bool:
remaining = status.remaining_quantity_m2
if remaining is not None and remaining <= tolerance:
return True
if status.order_quantity_m2 is None or status.good_quantity_m2 is None:
return False
return status.good_quantity_m2 + tolerance >= status.order_quantity_m2
@@ -0,0 +1,50 @@
"""Foreground reconciliation runner suitable for a systemd service."""
import sys
import time
from collections.abc import Callable
from datetime import UTC, datetime
from typing import TextIO
from production_analytics.calculations.config import finite_number
from production_analytics.service.downtime import DowntimeReconciliationService
class DowntimeReconciliationRunner:
def __init__(
self,
service: DowntimeReconciliationService,
*,
machine_id: str,
poll_interval_seconds: float = 300,
clock: Callable[[], datetime] | None = None,
sleep: Callable[[float], None] = time.sleep,
stdout: TextIO | None = None,
stderr: TextIO | None = None,
) -> None:
self.service, self.machine_id = service, machine_id
self.interval = finite_number(poll_interval_seconds, "poll interval", positive=True)
self.clock, self.sleep = clock or (lambda: datetime.now(UTC)), sleep
self.stdout, self.stderr = stdout or sys.stdout, stderr or sys.stderr
def run(self) -> None:
try:
while True:
now = self.clock()
try:
count = self.service.reconcile_once(now)
print(
f"{now.isoformat()} machine={self.machine_id!r} reconciled={count}",
file=self.stdout,
flush=True,
)
except Exception as exc:
print(
f"{now.isoformat()} machine={self.machine_id!r} reconciliation failed: "
f"{type(exc).__name__}",
file=self.stderr,
flush=True,
)
self.sleep(self.interval)
except KeyboardInterrupt:
return
@@ -0,0 +1,67 @@
"""Build the generic downtime runner from a small, explicit YAML configuration."""
import os
from dataclasses import dataclass
from pathlib import Path
import yaml
from production_analytics.enlyze.exploration import (
ExplorationClient,
ExplorationSettings,
load_secret_file,
)
from production_analytics.enlyze.gateway import EnlyzeApiGateway
from production_analytics.erp import ErpSettings, ErpWorkplaceStatusGateway
from production_analytics.service.downtime import DowntimeReconciliationService
from production_analytics.service.downtime_runner import DowntimeReconciliationRunner
from production_analytics.service.postgres_downtime import PostgresDowntimeRepository
from production_analytics.service.postgres_material import PostgresSettings
@dataclass(frozen=True, slots=True)
class DowntimeConfig:
machine_id: str
erp_workplace: str
production_order_format: str
poll_interval_seconds: float = 300
lookback_hours: float = 48
full_reconciliation_hours: float = 24
completion_tolerance_m2: float = 0.001
def load_downtime_config(path: Path) -> DowntimeConfig:
raw = yaml.safe_load(path.read_text(encoding="utf-8"))
if not isinstance(raw, dict):
raise ValueError("Downtime config must be a mapping")
allowed = {field.name for field in DowntimeConfig.__dataclass_fields__.values()}
if set(raw) - allowed or not {"machine_id", "erp_workplace", "production_order_format"} <= set(
raw
):
raise ValueError("Downtime config has unknown or missing fields")
for name in ("machine_id", "erp_workplace", "production_order_format"):
if not isinstance(raw[name], str) or not raw[name].strip():
raise ValueError(f"{name} must be a non-empty string")
return DowntimeConfig(**raw)
def build_downtime_runner(
config_path: Path, *, secrets_file: Path, erp_secrets_file: Path
) -> DowntimeReconciliationRunner:
config = load_downtime_config(config_path)
environment = {**os.environ, **load_secret_file(secrets_file)}
erp_environment = {**os.environ, **load_secret_file(erp_secrets_file)}
service = DowntimeReconciliationService(
EnlyzeApiGateway(ExplorationClient(ExplorationSettings.from_environment(environment))),
ErpWorkplaceStatusGateway(ErpSettings.from_environment(erp_environment)),
PostgresDowntimeRepository(PostgresSettings.from_environment(os.environ)),
machine_id=config.machine_id,
workplace=config.erp_workplace,
production_order_format=config.production_order_format,
lookback_hours=config.lookback_hours,
full_reconciliation_hours=config.full_reconciliation_hours,
completion_tolerance_m2=config.completion_tolerance_m2,
)
return DowntimeReconciliationRunner(
service, machine_id=config.machine_id, poll_interval_seconds=config.poll_interval_seconds
)
@@ -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(
@@ -0,0 +1,63 @@
"""PostgreSQL writer for channel-level cumulative consumption snapshots."""
from datetime import datetime
from production_analytics.service.postgres_material import PostgresSettings
class PostgresChannelMaterialSnapshotWriter:
def __init__(self, settings: PostgresSettings) -> None:
self.settings = settings
def write(
self,
*,
timestamp: datetime,
calculation_id: str,
machine_id: str,
extruder: str,
channel: str,
production_order: str,
run_id: str,
cumulative_consumption_kg: float,
material_number: str | None,
material_name: str | None,
material_mapping_status: str,
percentage_sum_valid: bool,
) -> None:
import psycopg
with psycopg.connect(
host=self.settings.host,
port=self.settings.port,
dbname=self.settings.dbname,
user=self.settings.user,
password=self.settings.password,
connect_timeout=10,
options="-c statement_timeout=10000",
) as connection:
connection.execute(
"""INSERT INTO channel_material_consumption_snapshots
(timestamp, calculation_id, machine_id, extruder, doser_channel,
production_order, run_id, cumulative_consumption_kg,
material_number, material_name, material_mapping_status,
percentage_sum_valid)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
ON CONFLICT (calculation_id, machine_id, extruder, doser_channel,
production_order, timestamp)
DO NOTHING""",
(
timestamp,
calculation_id,
machine_id,
extruder,
channel,
production_order,
run_id,
cumulative_consumption_kg,
material_number,
material_name,
material_mapping_status,
percentage_sum_valid,
),
)
@@ -0,0 +1,147 @@
"""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.postgres_material import PostgresSettings
class DowntimeReadError(RuntimeError):
"""Safe operator-facing error for persisted downtime reads."""
class PostgresDowntimeRepository:
def __init__(self, settings: PostgresSettings) -> None:
self.settings = settings
def _connect(self):
import psycopg
return psycopg.connect(
host=self.settings.host,
port=self.settings.port,
dbname=self.settings.dbname,
user=self.settings.user,
password=self.settings.password,
connect_timeout=10,
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:
with self._connect() as connection:
row = connection.execute(
"""SELECT machine_id, production_order, started_at, ended_at
FROM production_order_attribution_state WHERE machine_id = %s""",
(machine_id,),
).fetchone()
return None if row is None else ProductionOrderBoundary(*row)
def save_boundary(self, boundary: ProductionOrderBoundary) -> None:
with self._connect() as connection:
connection.execute(
"""INSERT INTO production_order_attribution_state
(machine_id, production_order, started_at, ended_at)
VALUES (%s, %s, %s, %s)
ON CONFLICT (machine_id) DO UPDATE SET
production_order = EXCLUDED.production_order,
started_at = EXCLUDED.started_at, ended_at = EXCLUDED.ended_at""",
(
boundary.machine_id,
boundary.production_order,
boundary.started_at,
boundary.ended_at,
),
)
def close_order_attribution(self, machine_id: str, production_order: str, ended_at) -> None:
with self._connect() as connection:
connection.execute(
"""UPDATE production_downtime_events
SET attributed_end = CASE WHEN source_end IS NULL OR source_end > %s THEN %s
ELSE source_end END,
attributed_duration_seconds = EXTRACT(EPOCH FROM
(CASE WHEN source_end IS NULL OR source_end > %s
THEN %s ELSE source_end END
- attributed_start))
WHERE machine_id = %s AND production_order = %s
AND attributed_start IS NOT NULL AND attributed_end IS NULL""",
(ended_at, ended_at, ended_at, ended_at, machine_id, production_order),
)
def upsert(self, event: ProductionDowntimeEvent) -> None:
with self._connect() as connection:
connection.execute(
"""INSERT INTO production_downtime_events
(external_id, machine_id, production_order, source_type, source_start,
source_end, attributed_start, attributed_end, attributed_duration_seconds,
reason_id, reason_name, reason_description, reason_group, category, comment,
source_updated_at, last_reconciled_at)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
ON CONFLICT (external_id) DO UPDATE SET
machine_id = EXCLUDED.machine_id,
production_order = COALESCE(
EXCLUDED.production_order, production_downtime_events.production_order),
source_type = EXCLUDED.source_type, source_start = EXCLUDED.source_start,
source_end = EXCLUDED.source_end,
attributed_start = COALESCE(
EXCLUDED.attributed_start, production_downtime_events.attributed_start),
attributed_end = COALESCE(
EXCLUDED.attributed_end, production_downtime_events.attributed_end),
attributed_duration_seconds = COALESCE(
EXCLUDED.attributed_duration_seconds,
production_downtime_events.attributed_duration_seconds),
reason_id = EXCLUDED.reason_id, reason_name = EXCLUDED.reason_name,
reason_description = EXCLUDED.reason_description,
reason_group = EXCLUDED.reason_group,
category = EXCLUDED.category, comment = EXCLUDED.comment,
source_updated_at = EXCLUDED.source_updated_at,
last_reconciled_at = EXCLUDED.last_reconciled_at""",
(
event.external_id,
event.machine_id,
event.production_order,
event.source_type,
event.source_start,
event.source_end,
event.attributed_start,
event.attributed_end,
event.attributed_duration_seconds,
event.reason_id,
event.reason_name,
event.reason_description,
event.reason_group,
event.category.value,
event.comment,
event.source_updated_at,
event.last_reconciled_at,
),
)
@@ -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()
+21
View File
@@ -0,0 +1,21 @@
"""Shared test adaptations for the production PostgreSQL schema."""
import re
from pathlib import Path
import pytest
@pytest.fixture(scope="session")
def sqlite_schema() -> str:
"""Keep PostgreSQL DDL authoritative; adapt JSON storage and clock for SQLite.
SQLite stores serialized JSON as text. These tests exercise schema and INSERT
semantics, not PostgreSQL JSONB operators or TimescaleDB behavior.
"""
schema = (Path(__file__).resolve().parents[1] / "db" / "schema.sql").read_text(
encoding="utf-8"
)
schema = re.sub(r"::jsonb\b", "", schema)
schema = re.sub(r"\bjsonb\b", "text", schema)
return schema.replace("DEFAULT now()", "DEFAULT CURRENT_TIMESTAMP")
+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
+360
View File
@@ -0,0 +1,360 @@
from datetime import UTC, datetime, timedelta
from pathlib import Path
from unittest.mock import Mock
import pytest
from production_analytics.calculations.channel_config import load_channel_material_calculation
from production_analytics.calculations.channel_material import (
MATERIAL_AMBIGUOUS,
MATERIAL_UNAVAILABLE,
DosingChannelSample,
channel_rates,
validate_active_percentage_sum,
)
from production_analytics.enlyze.gateway import EnlyzeApiGateway, EnlyzeProductionRun
from production_analytics.service.channel_material import (
ChannelDefinition,
ChannelMaterialPollingService,
)
from production_analytics.service.channel_material_state_store import JsonChannelMaterialStateStore
NOW = datetime(2026, 9, 1, tzinfo=UTC)
E1_CONFIG = (
Path(__file__).resolve().parents[1] / "config/e1-channel-material-consumption.example.yaml"
)
def sample(*, on=True, percent=100, material=None, timestamp=NOW):
return DosingChannelSample(timestamp, 120, on, percent, 10, material)
def test_off_channel_with_nonzero_displayed_percentage_contributes_zero():
assert channel_rates((sample(on=False, percent=40),))[0].sample.material_rate_kg_per_hour == 0
def test_e1_config_dry_run_resolves_every_signal_through_gateway_without_sampling():
config = load_channel_material_calculation(E1_CONFIG)
origins = {
reference
for channel in config.channels
for reference in (
channel.total_rate_signal_ref,
channel.status_signal_ref,
channel.percentage_signal_ref,
channel.screw_speed_signal_ref,
)
}
client = Mock()
client.get.return_value.body = {
"data": [
{
"uuid": f"variable-{index}",
"details": {"origin_identifier": {"code": origin}},
}
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(
machine_id=config.machine_ref,
channels=config.channels,
)
assert config.machine_ref == "8302e3d1-b1e5-42f1-8540-615eb6c73e08"
assert len(config.channels) == 14
assert len(origins) == 44
assert len(resolved) == 14
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.post_json.assert_not_called()
def test_active_percentages_sum_to_100_and_deviation_is_reported_not_normalized():
active = (sample(percent=40), sample(percent=60))
assert validate_active_percentage_sum(active, tolerance=0.1)
assert not validate_active_percentage_sum(
(sample(percent=40), sample(percent=50)), tolerance=0.1
)
assert [x.sample.material_rate_kg_per_hour for x in channel_rates(active)] == [48, 72]
def test_null_and_duplicate_material_assignments_are_not_inferred():
assert (
channel_rates((sample(material=None),))[0].material_mapping_status == MATERIAL_UNAVAILABLE
)
rates = channel_rates((sample(material="123"), sample(material="123")))
assert all(rate.material_mapping_status == MATERIAL_AMBIGUOUS for rate in rates)
assert all(rate.material_number is None and rate.material_name is None for rate in rates)
def test_run_change_and_json_restart_preserve_channel_total(tmp_path):
channels = (ChannelDefinition("Ex1", "C1", "rate", "on", "pct", "rpm"),)
store, gateway = JsonChannelMaterialStateStore(tmp_path), Mock()
gateway.get_production_runs.return_value = []
gateway.get_open_production_run.return_value = EnlyzeProductionRun(
"r1", "m", None, "order", NOW, None
)
key = "C1\0Ex1"
gateway.get_dosing_channel_samples.return_value = {
key: [sample(timestamp=NOW), sample(timestamp=NOW + timedelta(seconds=10))]
}
first = ChannelMaterialPollingService(
gateway=gateway,
state_store=store,
machine_id="m",
channels=channels,
max_sample_gap_seconds=20,
)
assert first.poll_once(now=NOW + timedelta(seconds=10))[
0
].state.cumulative_consumption_kg == pytest.approx(10 / 30)
gateway.get_open_production_run.return_value = EnlyzeProductionRun(
"r2", "m", None, "order", NOW + timedelta(seconds=20), None
)
gateway.get_dosing_channel_samples.return_value = {
key: [
sample(timestamp=NOW + timedelta(seconds=20)),
sample(timestamp=NOW + timedelta(seconds=30)),
]
}
restarted = ChannelMaterialPollingService(
gateway=gateway,
state_store=store,
machine_id="m",
channels=channels,
max_sample_gap_seconds=20,
)
assert restarted.poll_once(now=NOW + timedelta(seconds=30))[
0
].state.cumulative_consumption_kg == pytest.approx(20 / 30)
def test_bootstrap_replays_closed_runs_without_integrating_the_inter_run_gap(tmp_path):
channels = (ChannelDefinition("Ex1", "C1", "rate", "on", "pct", "rpm"),)
closed = EnlyzeProductionRun("r1", "m", None, "order", NOW, NOW + timedelta(seconds=10))
current = EnlyzeProductionRun("r2", "m", None, "order", NOW + timedelta(seconds=20), None)
gateway = Mock()
gateway.get_open_production_run.return_value = current
gateway.get_production_runs.return_value = [closed, current]
key = "C1\0Ex1"
gateway.get_dosing_channel_samples.side_effect = [
{key: [sample(timestamp=NOW), sample(timestamp=NOW + timedelta(seconds=10))]},
{
key: [
sample(timestamp=NOW + timedelta(seconds=20)),
sample(timestamp=NOW + timedelta(seconds=30)),
]
},
]
result = ChannelMaterialPollingService(
gateway=gateway,
state_store=JsonChannelMaterialStateStore(tmp_path),
machine_id="m",
channels=channels,
max_sample_gap_seconds=20,
).poll_once(now=NOW + timedelta(seconds=30))
assert result is not None
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)
]
+141
View File
@@ -0,0 +1,141 @@
import io
from datetime import UTC, datetime
from pathlib import Path
from unittest.mock import Mock, patch
from production_analytics.calculations.channel_config import load_channel_material_calculation
from production_analytics.calculations.material_consumption import MaterialIntegrationState
from production_analytics.cli.__main__ import _parser, main
from production_analytics.enlyze.gateway import EnlyzeProductionRun
from production_analytics.service.channel_material import ChannelPollResult
from production_analytics.service.channel_material_runner import ChannelMaterialPollingRunner
from production_analytics.service.channel_material_runtime import build_channel_material_runner
EXAMPLE = (
Path(__file__).resolve().parents[1] / "config/e1-channel-material-consumption.example.yaml"
)
NOW = datetime(2026, 9, 1, tzinfo=UTC)
def test_cli_channel_material_arguments():
args = _parser().parse_args(
[
"run",
"channel-material-poll",
"--config",
str(EXAMPLE),
"--poll-interval-seconds",
"15",
"--state-directory",
"state",
"--secrets-file",
"secrets.env",
"--once",
]
)
assert args.command == "channel-material-poll"
assert args.config == EXAMPLE
assert args.poll_interval_seconds == 15
assert args.state_directory == Path("state")
assert args.secrets_file == Path("secrets.env")
assert args.once
def test_runtime_constructs_channel_service(tmp_path, monkeypatch):
monkeypatch.setenv("ENLYZE_BASE_URL", "https://example.invalid/api/")
for key, value in {
"HOST": "localhost",
"PORT": "5432",
"DB": "analytics",
"USER": "user",
"PASSWORD": "environment-password",
}.items():
monkeypatch.setenv(f"POSTGRES_{key}", value)
secrets = tmp_path / "secrets.env"
secrets.write_text("ENLYZE_API_KEY=secret-from-file\nPOSTGRES_PASSWORD=file-password\n")
calculation = load_channel_material_calculation(EXAMPLE)
with patch(
"production_analytics.service.channel_material_runtime.ChannelMaterialPollingService"
) as service:
runner = build_channel_material_runner(
calculation,
poll_interval_seconds=7,
state_directory=tmp_path / "state",
secrets_file=secrets,
)
kwargs = service.call_args.kwargs
assert kwargs["machine_id"] == calculation.machine_ref
assert kwargs["channels"] == calculation.channels
assert kwargs["max_sample_gap_seconds"] == calculation.max_sample_gap_seconds
assert kwargs["percentage_tolerance"] == calculation.percentage_tolerance
assert kwargs["material_names"] == calculation.material_names
assert kwargs["gateway"]._client._settings.api_key == "secret-from-file"
assert kwargs["state_store"].directory == tmp_path / "state"
assert runner.service is service.return_value
assert runner.interval == 7
assert runner.snapshot_writer.settings.password == "file-password"
def test_once_executes_one_cycle_and_exits(capsys):
with patch(
"production_analytics.service.channel_material_runtime.build_channel_material_runner"
) as build:
assert main(["run", "channel-material-poll", "--config", str(EXAMPLE), "--once"]) == 0
build.return_value.run_once.assert_called_once_with()
build.return_value.run.assert_not_called()
assert capsys.readouterr().err == ""
def test_no_snapshots_are_written_without_eligible_production_run():
writer = Mock()
output = io.StringIO()
runner = ChannelMaterialPollingRunner(
Mock(poll_once=Mock(return_value=None)),
machine_id="machine",
calculation_id="calculation",
snapshot_writer=writer,
poll_interval_seconds=10,
clock=lambda: NOW,
stdout=output,
)
assert not runner.run_once()
writer.write.assert_not_called()
assert "snapshots=0" in output.getvalue()
def test_one_cycle_writes_each_channel_snapshot():
run = EnlyzeProductionRun("run", "machine", None, "order", NOW, None)
first = ChannelPollResult(
run, "Ex1", "C1", MaterialIntegrationState(1.5, 10), "42", "Material", "MAPPED", True
)
second = ChannelPollResult(
run, "Ex1", "C2", MaterialIntegrationState(2.5, 10), None, None, "AMBIGUOUS", False
)
writer = Mock()
output = io.StringIO()
runner = ChannelMaterialPollingRunner(
Mock(poll_once=Mock(return_value=(first, second))),
machine_id="machine",
calculation_id="calculation",
snapshot_writer=writer,
poll_interval_seconds=10,
clock=lambda: NOW,
stdout=output,
)
assert runner.run_once()
assert writer.write.call_count == 2
assert writer.write.call_args_list[0].kwargs == {
"timestamp": NOW,
"calculation_id": "calculation",
"machine_id": "machine",
"extruder": "Ex1",
"channel": "C1",
"production_order": "order",
"run_id": "run",
"cumulative_consumption_kg": 1.5,
"material_number": "42",
"material_name": "Material",
"material_mapping_status": "MAPPED",
"percentage_sum_valid": True,
}
assert "channel snapshots=2 written" in output.getvalue()
+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:
+140
View File
@@ -0,0 +1,140 @@
from datetime import UTC, datetime
from production_analytics.enlyze.gateway import EnlyzeDowntime
from production_analytics.erp import CurrentWorkplaceStatus
from production_analytics.service.downtime import (
DowntimeCategory,
DowntimeReconciliationService,
ProductionOrderBoundary,
)
NOW = datetime(2026, 9, 16, 12, tzinfo=UTC)
def source(*, identifier="d", end=NOW, category=None):
return EnlyzeDowntime(
identifier,
"machine",
"THRESHOLD",
datetime(2026, 9, 16, 10, tzinfo=UTC),
end,
None,
"reason" if category else None,
"reason" if category else None,
None,
None,
category,
None,
)
def status(order="1", *, remaining=3, good=7, target=10, feedback=NOW):
return CurrentWorkplaceStatus(
"WP", order, None, None, feedback, target, good, remaining, None, None
)
class Gateway:
def __init__(self, events):
self.events = events
def get_downtimes(self, machine_id, *, start=None):
return self.events
class Erp:
def __init__(self, current):
self.current = current
def get_current_workplace_status(self, workplace):
return self.current
class Repo:
def __init__(self):
self.boundary = None
self.events = {}
self.closures = []
def current_boundary(self, machine_id):
return self.boundary
def save_boundary(self, boundary):
self.boundary = boundary
def close_order_attribution(self, machine_id, production_order, ended_at):
self.closures.append((production_order, ended_at))
for event in self.events.values():
if event.production_order == production_order and event.attributed_end is None:
event # database-specific clipping is covered by SQL contract
def upsert(self, event):
self.events[event.external_id] = event
def service(repo, events, current):
return DowntimeReconciliationService(
Gateway(events),
Erp(current),
repo,
machine_id="machine",
workplace="WP",
production_order_format="FA-{production_order}",
)
def test_categories_open_and_reconciliation_upsert() -> None:
repo = Repo()
runner = service(
repo,
[
source(identifier="p", category="PLANNED"),
source(identifier="u", category="UNPLANNED"),
source(identifier="x", end=None),
],
status(),
)
assert runner.reconcile_once(NOW) == 3
assert {key: event.category for key, event in repo.events.items()} == {
"p": DowntimeCategory.PLANNED,
"u": DowntimeCategory.UNPLANNED,
"x": DowntimeCategory.UNKNOWN,
}
assert repo.events["x"].source_end is None
# Same UUID is overwritten, never duplicated; delayed classification is accepted.
runner.gateway.events = [source(identifier="x", end=NOW, category="PLANNED")]
runner.reconcile_once(NOW)
assert len(repo.events) == 3
assert repo.events["x"].category is DowntimeCategory.PLANNED
assert repo.events["x"].source_end == NOW
def test_completion_clips_attribution_and_new_order_closes_previous() -> None:
repo = Repo()
repo.boundary = ProductionOrderBoundary(
"machine",
"FA-1",
datetime(2026, 9, 16, 9, tzinfo=UTC),
None,
)
event = source(identifier="open", end=None)
first = service(repo, [event], status(remaining=0, feedback=NOW))
first.reconcile_once(NOW)
assert repo.boundary is not None and repo.boundary.ended_at == NOW
assert repo.events["open"].production_order == "FA-1"
assert repo.events["open"].attributed_end == NOW
repo.boundary = ProductionOrderBoundary(
"machine",
"FA-1",
datetime(2026, 9, 16, 8, tzinfo=UTC),
None,
)
service(repo, [], status(order="2", feedback=NOW)).reconcile_once(NOW)
assert repo.closures == [("FA-1", NOW), ("FA-1", NOW)]
assert repo.boundary.production_order == "FA-2"
def test_unknown_is_not_unplanned_and_no_schedule_is_used() -> None:
repo = Repo()
service(repo, [source(end=datetime(2026, 9, 20, tzinfo=UTC))], status()).reconcile_once(NOW)
assert repo.events["d"].category is DowntimeCategory.UNKNOWN
+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),
}
+198 -51
View File
@@ -6,6 +6,52 @@ import pytest
from production_analytics.enlyze.gateway import EnlyzeApiGateway from production_analytics.enlyze.gateway import EnlyzeApiGateway
def test_downtime_pagination_and_nullable_reason() -> None:
client = Mock()
base = {
"machine": "machine-1",
"type": "THRESHOLD",
"comment": None,
"start": "2026-09-03T04:00:00Z",
"end": None,
"reason": None,
"updated": None,
}
client.get.side_effect = [
Mock(body={"data": [{**base, "uuid": "d1"}], "metadata": {"next_cursor": "next"}}),
Mock(
body={
"data": [
{
**base,
"uuid": "d2",
"end": "2026-09-03T05:00:00Z",
"reason": {
"uuid": "r",
"name": "Break",
"description": None,
"group": "General",
"category": "PLANNED",
},
}
],
"metadata": {"next_cursor": None},
}
),
]
result = EnlyzeApiGateway(client).get_downtimes(
"machine-1",
start=datetime(2026, 9, 3, tzinfo=UTC),
)
assert [item.uuid for item in result] == ["d1", "d2"]
assert result[0].end is None and result[0].reason_category is None
assert result[1].reason_category == "PLANNED"
assert client.get.call_args_list[1].args == (
"/v2/downtimes",
{"machine": "machine-1", "start": "2026-09-03T00:00:00+00:00", "cursor": "next"},
)
def test_get_open_production_run_returns_current_run() -> None: def test_get_open_production_run_returns_current_run() -> None:
client = Mock() client = Mock()
client.get.return_value.body = { client.get.return_value.body = {
@@ -138,11 +184,19 @@ def test_get_material_samples_uses_column_names_not_fixed_positions() -> None:
@pytest.fixture @pytest.fixture
def timeseries(): def timeseries():
client = Mock() client = Mock()
client.post_json.return_value.body = {"data": { client.post_json.return_value.body = {
"columns": ["time", "rate", "gate"], "records": [], "data": {
}} "columns": ["time", "rate", "gate"],
args = dict(machine_id="m", rate_variable_id="rate", gate_variable_id="gate", "records": [],
start=datetime(2026, 9, 3, tzinfo=UTC), end=datetime(2026, 9, 4, tzinfo=UTC)) }
}
args = dict(
machine_id="m",
rate_variable_id="rate",
gate_variable_id="gate",
start=datetime(2026, 9, 3, tzinfo=UTC),
end=datetime(2026, 9, 4, tzinfo=UTC),
)
return EnlyzeApiGateway(client), client, args return EnlyzeApiGateway(client), client, args
@@ -176,9 +230,19 @@ def test_missing_required_column(timeseries, column) -> None:
gateway.get_material_samples(**args) gateway.get_material_samples(**args)
@pytest.mark.parametrize("record", [[], {}, ["bad", 1, 1], [None, 1, 1], @pytest.mark.parametrize(
["2026-09-03T00:00:00", 1, 1], ["2026-09-03T00:00:00Z", None, 1], "record",
["2026-09-03T00:00:00Z", 1, float("inf")], ["2026-09-03T00:00:00Z", True, 1]]) [
[],
{},
["bad", 1, 1],
[None, 1, 1],
["2026-09-03T00:00:00", 1, 1],
["2026-09-03T00:00:00Z", None, 1],
["2026-09-03T00:00:00Z", 1, float("inf")],
["2026-09-03T00:00:00Z", True, 1],
],
)
def test_malformed_records_fail_clearly(timeseries, record) -> None: def test_malformed_records_fail_clearly(timeseries, record) -> None:
gateway, client, args = timeseries gateway, client, args = timeseries
client.post_json.return_value.body["data"]["records"] = [record] client.post_json.return_value.body["data"]["records"] = [record]
@@ -188,15 +252,21 @@ def test_malformed_records_fail_clearly(timeseries, record) -> None:
def test_multiple_open_runs_rejected() -> None: def test_multiple_open_runs_rejected() -> None:
client = Mock() client = Mock()
run = dict(uuid="r", machine="m", production_order="o", start="2026-09-03T00:00:00Z", run = dict(uuid="r", machine="m", production_order="o", start="2026-09-03T00:00:00Z", end=None)
end=None)
client.get.return_value.body = {"data": [run, {**run, "uuid": "r2"}]} client.get.return_value.body = {"data": [run, {**run, "uuid": "r2"}]}
with pytest.raises(ValueError, match="multiple open Production Runs"): with pytest.raises(ValueError, match="multiple open Production Runs"):
EnlyzeApiGateway(client).get_open_production_run("m") EnlyzeApiGateway(client).get_open_production_run("m")
@pytest.mark.parametrize("item", [{}, None, {"end": None}, @pytest.mark.parametrize(
dict(uuid="r", machine="m", production_order="o", start="bad", end=None)]) "item",
[
{},
None,
{"end": None},
dict(uuid="r", machine="m", production_order="o", start="bad", end=None),
],
)
def test_malformed_run_fails_clearly(item) -> None: def test_malformed_run_fails_clearly(item) -> None:
client = Mock() client = Mock()
client.get.return_value.body = {"data": [item]} client.get.return_value.body = {"data": [item]}
@@ -219,16 +289,24 @@ def test_timeseries_with_null_cursor(timeseries) -> None:
def test_timeseries_pagination_resolves_columns_per_page(timeseries) -> None: def test_timeseries_pagination_resolves_columns_per_page(timeseries) -> None:
gateway, client, args = timeseries gateway, client, args = timeseries
client.post_json.side_effect = [ client.post_json.side_effect = [
Mock(body={ Mock(
"data": {"columns": ["time", "rate", "gate"], body={
"records": [["2026-09-03T00:00:00Z", 10, 2]]}, "data": {
"columns": ["time", "rate", "gate"],
"records": [["2026-09-03T00:00:00Z", 10, 2]],
},
"metadata": {"next_cursor": "continuation"}, "metadata": {"next_cursor": "continuation"},
}), }
Mock(body={ ),
"data": {"columns": ["gate", "time", "rate"], Mock(
"records": [[3, "2026-09-03T01:00:00Z", 20]]}, body={
"data": {
"columns": ["gate", "time", "rate"],
"records": [[3, "2026-09-03T01:00:00Z", 20]],
},
"metadata": {"next_cursor": None}, "metadata": {"next_cursor": None},
}), }
),
] ]
samples = gateway.get_material_samples(**args) samples = gateway.get_material_samples(**args)
assert [(s.timestamp, s.material_rate_kg_per_hour, s.gate_value) for s in samples] == [ assert [(s.timestamp, s.material_rate_kg_per_hour, s.gate_value) for s in samples] == [
@@ -237,16 +315,32 @@ def test_timeseries_pagination_resolves_columns_per_page(timeseries) -> None:
] ]
assert client.post_json.call_count == 2 assert client.post_json.call_count == 2
first, second = client.post_json.call_args_list first, second = client.post_json.call_args_list
assert first.args == ("/v2/timeseries", { assert first.args == (
"machine": "m", "start": args["start"].isoformat(), "end": args["end"].isoformat(), "/v2/timeseries",
{
"machine": "m",
"start": args["start"].isoformat(),
"end": args["end"].isoformat(),
"variables": [{"uuid": "rate"}, {"uuid": "gate"}], "variables": [{"uuid": "rate"}, {"uuid": "gate"}],
}) },
)
assert second.args == ("/v2/timeseries", {**first.args[1], "cursor": "continuation"}) assert second.args == ("/v2/timeseries", {**first.args[1], "cursor": "continuation"})
@pytest.mark.parametrize("metadata", [None, [], "bad", {}, @pytest.mark.parametrize(
{"next_cursor": ""}, {"next_cursor": 1}, {"next_cursor": False}, "metadata",
{"next_cursor": []}, {"next_cursor": {}}]) [
None,
[],
"bad",
{},
{"next_cursor": ""},
{"next_cursor": 1},
{"next_cursor": False},
{"next_cursor": []},
{"next_cursor": {}},
],
)
def test_invalid_pagination_metadata(timeseries, metadata) -> None: def test_invalid_pagination_metadata(timeseries, metadata) -> None:
gateway, client, args = timeseries gateway, client, args = timeseries
client.post_json.return_value.body["metadata"] = metadata client.post_json.return_value.body["metadata"] = metadata
@@ -267,25 +361,38 @@ def test_repeated_pagination_cursor(timeseries, cursors) -> None:
assert client.post_json.call_count == len(cursors) assert client.post_json.call_count == len(cursors)
@pytest.mark.parametrize("data, error", [ @pytest.mark.parametrize(
"data, error",
[
({"columns": ["time", "rate", "gate"], "records": [[]]}, "malformed record 0"), ({"columns": ["time", "rate", "gate"], "records": [[]]}, "malformed record 0"),
({"columns": ["time", "rate", "rate", "gate"], "records": []}, "required column"), ({"columns": ["time", "rate", "rate", "gate"], "records": []}, "required column"),
({"columns": ["time", "rate"], "records": []}, "required column"), ({"columns": ["time", "rate"], "records": []}, "required column"),
({"columns": None, "records": []}, "columns must be a list"), ({"columns": None, "records": []}, "columns must be a list"),
({"columns": ["time", "rate", "gate"], "records": None}, "records must be a list"), ({"columns": ["time", "rate", "gate"], "records": None}, "records must be a list"),
({"columns": ["time", "rate", "gate"], (
"records": [["2026-09-03T01:00:00", 10, 2]]}, "timezone-aware"), {"columns": ["time", "rate", "gate"], "records": [["2026-09-03T01:00:00", 10, 2]]},
({"columns": ["time", "rate", "gate"], "timezone-aware",
"records": [["2026-09-03T01:00:00Z", float("nan"), 2]]}, "finite"), ),
({"columns": ["time", "rate", "gate"], (
"records": [["2026-09-03T01:00:00Z", 10, True]]}, "numeric"), {
]) "columns": ["time", "rate", "gate"],
"records": [["2026-09-03T01:00:00Z", float("nan"), 2]],
},
"finite",
),
(
{"columns": ["time", "rate", "gate"], "records": [["2026-09-03T01:00:00Z", 10, True]]},
"numeric",
),
],
)
def test_malformed_later_page(timeseries, data, error) -> None: def test_malformed_later_page(timeseries, data, error) -> None:
gateway, client, args = timeseries gateway, client, args = timeseries
first_body = client.post_json.return_value.body first_body = client.post_json.return_value.body
first_body["metadata"] = {"next_cursor": "continuation"} first_body["metadata"] = {"next_cursor": "continuation"}
client.post_json.side_effect = [ client.post_json.side_effect = [
Mock(body=first_body), Mock(body={"data": data, "metadata": {"next_cursor": None}}), Mock(body=first_body),
Mock(body={"data": data, "metadata": {"next_cursor": None}}),
] ]
with pytest.raises(ValueError, match=f"Invalid timeseries response on page 2:.*{error}"): with pytest.raises(ValueError, match=f"Invalid timeseries response on page 2:.*{error}"):
gateway.get_material_samples(**args) gateway.get_material_samples(**args)
@@ -294,8 +401,13 @@ def test_malformed_later_page(timeseries, data, error) -> None:
def test_production_runs_follow_pages_and_find_open_run() -> None: def test_production_runs_follow_pages_and_find_open_run() -> None:
client = Mock() client = Mock()
closed = dict(uuid="closed", machine="m", production_order="opaque-order", closed = dict(
start="2026-09-01T00:00:00Z", end="2026-09-01T01:00:00Z") uuid="closed",
machine="m",
production_order="opaque-order",
start="2026-09-01T00:00:00Z",
end="2026-09-01T01:00:00Z",
)
opened = {**closed, "uuid": "open", "end": None} opened = {**closed, "uuid": "open", "end": None}
pages = [ pages = [
Mock(body={"data": [closed], "metadata": {"next_cursor": "a"}}), Mock(body={"data": [closed], "metadata": {"next_cursor": "a"}}),
@@ -314,10 +426,20 @@ def test_production_runs_follow_pages_and_find_open_run() -> None:
assert gateway.get_open_production_run("m") == runs[1] assert gateway.get_open_production_run("m") == runs[1]
@pytest.mark.parametrize("metadata", [ @pytest.mark.parametrize(
None, [], "bad", {}, {"next_cursor": ""}, {"next_cursor": 1}, "metadata",
{"next_cursor": False}, {"next_cursor": []}, {"next_cursor": {}}, [
]) None,
[],
"bad",
{},
{"next_cursor": ""},
{"next_cursor": 1},
{"next_cursor": False},
{"next_cursor": []},
{"next_cursor": {}},
],
)
def test_production_run_invalid_pagination(metadata) -> None: def test_production_run_invalid_pagination(metadata) -> None:
client = Mock() client = Mock()
client.get.return_value.body = {"data": [], "metadata": metadata} client.get.return_value.body = {"data": [], "metadata": metadata}
@@ -329,25 +451,50 @@ def test_production_run_invalid_pagination(metadata) -> None:
def test_production_run_cyclic_pagination(cursors) -> None: def test_production_run_cyclic_pagination(cursors) -> None:
client = Mock() client = Mock()
client.get.side_effect = [ client.get.side_effect = [
Mock(body={"data": [], "metadata": {"next_cursor": cursor}}) Mock(body={"data": [], "metadata": {"next_cursor": cursor}}) for cursor in cursors
for cursor in cursors
] ]
with pytest.raises(ValueError, match="next_cursor has already been followed"): with pytest.raises(ValueError, match="next_cursor has already been followed"):
EnlyzeApiGateway(client).get_production_runs("m") EnlyzeApiGateway(client).get_production_runs("m")
assert client.get.call_count == len(cursors) assert client.get.call_count == len(cursors)
@pytest.mark.parametrize("body", [ @pytest.mark.parametrize(
None, [], {}, {"data": {}}, {"data": [None]}, "body",
{"data": [dict(uuid="r", machine="wrong", production_order="o", [
start="2026-09-03T00:00:00Z", end=None)]}, None,
{"data": [dict(uuid="r", machine="m", production_order="o", [],
start="2026-09-03T00:00:00Z", end="2026-09-02T00:00:00Z")]}, {},
]) {"data": {}},
{"data": [None]},
{
"data": [
dict(
uuid="r",
machine="wrong",
production_order="o",
start="2026-09-03T00:00:00Z",
end=None,
)
]
},
{
"data": [
dict(
uuid="r",
machine="m",
production_order="o",
start="2026-09-03T00:00:00Z",
end="2026-09-02T00:00:00Z",
)
]
},
],
)
def test_production_run_malformed_later_page(body) -> None: def test_production_run_malformed_later_page(body) -> None:
client = Mock() client = Mock()
client.get.side_effect = [ client.get.side_effect = [
Mock(body={"data": [], "metadata": {"next_cursor": "a"}}), Mock(body=body), Mock(body={"data": [], "metadata": {"next_cursor": "a"}}),
Mock(body=body),
] ]
with pytest.raises(ValueError, match="Invalid production-run response on page 2"): with pytest.raises(ValueError, match="Invalid production-run response on page 2"):
EnlyzeApiGateway(client).get_production_runs("m") EnlyzeApiGateway(client).get_production_runs("m")
+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)
Loaded 100 of 121 files, more files were not shown because too many files have changed in this diff. Show more