Compare commits

..
7 Commits
93 changed files with 10798 additions and 56 deletions

No files matched your search

+2
View File
@@ -32,3 +32,5 @@ activate.sh
# Live polling checkpoints
data/state/
data/backup-spreader3/
+4
View File
@@ -560,3 +560,7 @@ changes. Daily 24h reports and final order summary tables remain future work.
No dashboard, aggregation or lag correction is added here.
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).
+1
View File
@@ -16,6 +16,7 @@ calculations:
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
@@ -14,6 +14,7 @@ calculations:
max_sample_gap_seconds: 20.0
erp_workplace: Bento 1
production_order_format: "Bento 1-{production_order}"
fallback_nominal_width_m: 5.0
output_metric: material_consumption
output_unit: kg
group_by: production_order
@@ -1,5 +1,5 @@
# Supply E1's ENLYZE machine UUID before operating. Signal references are PLC
# origins, resolved uniquely by the ENLYZE gateway at poll time.
# 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
@@ -11,20 +11,76 @@ calculations:
- 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}
- {id: C2, status_signal_ref: DB107:222.0, percentage_signal_ref: DB107:226, screw_speed_signal_ref: DB107:270}
- {id: C3, status_signal_ref: DB107:322.0, percentage_signal_ref: DB107:326, screw_speed_signal_ref: DB107:370}
- {id: C4, status_signal_ref: DB107:422.0, percentage_signal_ref: DB107:426, screw_speed_signal_ref: DB107:470}
- {id: C5, status_signal_ref: DB107:522.0, percentage_signal_ref: DB107:526, screw_speed_signal_ref: DB107:570}
- {id: C6, status_signal_ref: DB107:622.0, percentage_signal_ref: DB107:626, screw_speed_signal_ref: DB107:670}
- {id: C7, status_signal_ref: DB107:722.0, percentage_signal_ref: DB107:726, screw_speed_signal_ref: DB107:770}
- 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}
- {id: C2, status_signal_ref: DB207:222.0, percentage_signal_ref: DB207:226, screw_speed_signal_ref: DB207:270}
- {id: C3, status_signal_ref: DB207:322.0, percentage_signal_ref: DB207:326, screw_speed_signal_ref: DB207:370}
- {id: C4, status_signal_ref: DB207:422.0, percentage_signal_ref: DB207:426, screw_speed_signal_ref: DB207:470}
- {id: C5, status_signal_ref: DB207:522.0, percentage_signal_ref: DB207:526, screw_speed_signal_ref: DB207:570}
- {id: C6, status_signal_ref: DB207:622.0, percentage_signal_ref: DB207:626, screw_speed_signal_ref: DB207:670}
- {id: C7, status_signal_ref: DB207:722.0, percentage_signal_ref: DB207:726, screw_speed_signal_ref: DB207:770}
- 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
+7
View File
@@ -0,0 +1,7 @@
machine_id: 16c0a111-3049-41d5-9e19-42ee0e047757
erp_workplace: SECEXTRU
production_order_format: "Sec 1/2-{production_order}"
poll_interval_seconds: 300
lookback_hours: 48
full_reconciliation_hours: 24
completion_tolerance_m2: 0.001
+7
View File
@@ -0,0 +1,7 @@
machine_id: 0c207a7c-7813-4cff-90ba-6a0148919d38
erp_workplace: SEC3
production_order_format: "Sec 3-{production_order}"
poll_interval_seconds: 300
lookback_hours: 48
full_reconciliation_hours: 24
completion_tolerance_m2: 0.001
+232
View File
@@ -0,0 +1,232 @@
sites:
espelkamp:
display_name: Espelkamp
timezone: Europe/Berlin
adorf:
display_name: Adorf
timezone: Europe/Berlin
malaysia:
display_name: Malaysia
timezone: Asia/Kuala_Lumpur
machines:
B1:
display_name: B1
site: espelkamp
machine_id: 5f42a4f6-9ca0-4f6f-9786-40d50a35b230
erp_workplace: BENTO 1
capabilities:
production: true
downtime: true
material: true
speed: true
material:
mode: cumulative
calculation_ids:
- bento1-fresh-bentonite-consumption
- bento1-spreader3-consumption
speed:
signal_ref: fef41976-1103-4090-b780-eaeecc02fdfa
signal: Transport Auszug Geschwindigkeit Istwert
unit: m/min
production_gate_m_min: 0.3
E1:
display_name: E1
site: espelkamp
machine_id: 8302e3d1-b1e5-42f1-8540-615eb6c73e08
erp_workplace: '1568705'
capabilities:
production: true
downtime: true
material: true
speed: true
material:
mode: channel
calculation_ids:
- e1-channel-material-consumption
speed:
signal_ref: 488e28a9-79a6-44c4-9cc2-c021bb2108ec
signal: Geschwindigkeit Gesamtanlage
unit: m/min
production_gate_m_min: 0.5
K7:
display_name: K7
site: espelkamp
machine_id: c220f95c-a65e-4cb7-99b7-0626d6c7508c
erp_workplace: K7
capabilities:
production: true
downtime: true
material: true
speed: true
material:
mode: cumulative
calculation_ids:
- k7-fiber-consumption
allocation: erp_fiber_share
speed:
signal_ref: 823867bb-f5d2-40eb-b875-657155addfd0
signal: Geschwindigkeit Gesamtanlage
unit: m/min
production_gate_m_min: 0.5
K3/4:
display_name: K3/4
site: espelkamp
machine_id: null
erp_workplace: K3/4
capabilities:
production: true
downtime: false
material: false
speed: false
E4:
display_name: E4
site: espelkamp
machine_id: 646ebfa0-e97d-4970-b9f4-da94492aecc3
erp_workplace: '1568700'
capabilities:
production: true
downtime: true
material: false
speed: false
Gitter 1:
display_name: Gitter 1
site: adorf
machine_id: 35612735-03cc-4496-a72e-3c3e2216c720
erp_workplace: GITTERANL
capabilities:
production: true
downtime: true
material: false
speed: true
speed:
signal_ref: 33abccf8-8dee-4b40-b0ce-63c3c0fd2cd9
signal: Produktionsgeschwindigkeit Automatikbetrieb
unit: m/min
numeric_dwell_gate:
signal_ref: 620511e3-a46b-47c4-8514-f2d4bde29e2b # Querspeicher Geschwindigkeit Abzug Quer (m/min)
threshold: 50.0
comparison: below
minimum_duration_seconds: 150
Gitter 2:
display_name: Gitter 2
site: adorf
machine_id: 5e89db10-ef0e-4224-866c-eee12bc3d27c
erp_workplace: GITTER II
capabilities:
production: true
downtime: true
material: false
speed: true
speed:
signal_ref: d3acefd8-1013-4b59-a235-fa265fd85fae
signal: Produktionsgeschwindigkeit Automatikbetrieb
unit: m/min
numeric_dwell_gate:
signal_ref: 1ae8fb5d-1d25-414a-9181-d35b6cdde507 # Quer Transportwagen Position re. Absolutwertgeber (Position; DB21:224.0)
threshold: 27000
comparison: below
minimum_duration_seconds: 150
Gitter 3:
display_name: Gitter 3
site: adorf
machine_id: ec3baac3-ccc1-4d1e-9b57-3f5ab2daa567
erp_workplace: GITTERIII
capabilities:
production: true
downtime: true
material: false
speed: true
speed:
signal_ref: 88641764-6fd1-4733-a054-80fa43a62470
signal: Produktionsgeschwindigkeit Automatikbetrieb
unit: m/min
numeric_dwell_gate:
signal_ref: f78bd11f-b2a8-4454-86a0-c8de576799c2 # Transportwagen Position re. Absolutwertgeber (Position; DB21:224.0)
threshold: 31000
comparison: below
minimum_duration_seconds: 150
Gitter 4:
display_name: Gitter 4
site: adorf
machine_id: ffa5de99-66a2-44bd-b039-9b4275bc5f9e
erp_workplace: GITTER IV
capabilities:
production: true
downtime: true
material: false
speed: true
speed:
signal_ref: 1d7660d4-10f4-4466-b1fd-076f9fd504fe
signal: Produktionsgeschwindigkeit Automatikbetrieb
unit: m/min
numeric_dwell_gate:
signal_ref: 5685fb13-861d-4e95-8a98-e39d4fc3e059 # Querspeicher Geschwindigkeit Abzug Quer (m/min; DB21:482.0)
threshold: 2
comparison: below
minimum_duration_seconds: 150
K5:
display_name: K5
site: adorf
machine_id: 8c094b9d-32d2-4ddf-b56a-2cd11a09eebf
erp_workplace: K5
capabilities:
production: true
downtime: true
material: false
speed: true
speed:
signal_ref: c3ae3002-b75c-4d7c-bb33-f10265fcf428
signal: Nadelmaschine 3 Auszug
unit: m/min
running_signal_ref: 507b1225-2992-4dd1-8412-34969466722f # Stillstand Nadelmaschine 3 (technical origin: Stillstand Anlage)
running_when: false
Secumat 1/2:
display_name: Secumat 1/2
site: adorf
machine_id: 16c0a111-3049-41d5-9e19-42ee0e047757
erp_workplace: SECEXTRU
capabilities:
production: true
downtime: true
material: false
speed: false
Secumat 3:
display_name: Secumat 3
site: adorf
machine_id: 0c207a7c-7813-4cff-90ba-6a0148919d38
erp_workplace: SEC3
capabilities:
production: true
downtime: true
material: false
speed: false
Bento 2:
display_name: Bento 2
site: malaysia
machine_id: 6201f3de-b940-45d7-930c-1481c5ae9e1d
erp_workplace: BENTO 2
capabilities:
production: true
downtime: false
material: false
speed: false
K1:
display_name: K1
site: malaysia
machine_id: 40f1f58b-21fc-490a-8343-d1888938f11b
erp_workplace: K1
capabilities:
production: true
downtime: false
material: false
speed: false
K6:
display_name: K6
site: malaysia
machine_id: 5e778f87-2d0f-47ac-a3ce-0c0dd9957918
erp_workplace: K6
capabilities:
production: true
downtime: false
material: false
speed: false
+21
View File
@@ -0,0 +1,21 @@
-- Apply once before enabling the reconciliation service (also safe to reapply).
CREATE TABLE IF NOT EXISTS historical_assignment_audit (
id bigserial PRIMARY KEY,
machine_id text NOT NULL,
source_table text NOT NULL,
record_identity jsonb NOT NULL,
previous_order text NOT NULL,
new_order text NOT NULL,
run_id text NOT NULL,
reason text NOT NULL,
action text NOT NULL DEFAULT 'updated',
retained_run_id text,
reconciled_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP,
CHECK (previous_order <> new_order)
);
ALTER TABLE historical_assignment_audit
ADD COLUMN IF NOT EXISTS action text NOT NULL DEFAULT 'updated';
ALTER TABLE historical_assignment_audit
ADD COLUMN IF NOT EXISTS retained_run_id text;
CREATE INDEX IF NOT EXISTS historical_assignment_audit_machine_time_idx
ON historical_assignment_audit (machine_id, reconciled_at);
+17
View File
@@ -126,3 +126,20 @@ CREATE TABLE IF NOT EXISTS production_order_attribution_state (
started_at timestamptz NOT NULL,
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
+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.
+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"
license = { text = "Proprietary" }
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]
dev = [
@@ -20,6 +20,7 @@ dev = [
[project.scripts]
production-analytics = "production_analytics.cli.__main__:main"
production-analytics-web = "production_analytics.web:main"
[tool.hatch.build.targets.wheel]
packages = ["src/production_analytics"]
@@ -2,6 +2,7 @@
from dataclasses import dataclass
from pathlib import Path
from uuid import UUID
import yaml
@@ -78,6 +79,7 @@ def load_channel_material_calculation(path: str | Path) -> ChannelMaterialCalcul
"percentage_signal_ref",
"screw_speed_signal_ref",
"material_number_signal_ref",
"material_name_signal_ref",
}
if (
not isinstance(row, dict)
@@ -99,6 +101,20 @@ def load_channel_material_calculation(path: str | Path) -> ChannelMaterialCalcul
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"],
@@ -108,6 +124,7 @@ def load_channel_material_calculation(path: str | Path) -> ChannelMaterialCalcul
row["percentage_signal_ref"],
row["screw_speed_signal_ref"],
material,
material_name,
)
)
if len({(c.extruder, c.channel) for c in channels}) != len(channels):
@@ -21,6 +21,7 @@ class DosingChannelSample:
dosing_percentage: float
screw_speed: float
material_number: str | None = None
material_name: str | None = None
@dataclass(frozen=True, slots=True)
@@ -55,9 +56,10 @@ def channel_rates(
) -> tuple[ChannelRate, ...]:
"""Derive rates and conservative material identity for one aligned timestamp.
A material value which occurs on more than one channel is deliberately not
A material number which occurs on more than one channel is deliberately not
attributed to either channel: PLC assignments are not reliable enough to
resolve that ambiguity from a previous sample.
resolve that ambiguity from a previous sample. Direct per-channel names are
already assigned and may be shared by multiple channels.
"""
values = tuple(samples)
validate_active_percentage_sum(values, tolerance=percentage_tolerance)
@@ -71,7 +73,9 @@ def channel_rates(
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_number is None:
if value.material_name is not None and value.material_name.strip():
number, name, status = None, value.material_name, MATERIAL_ASSIGNED
elif value.material_number is None:
number, name, status = None, None, MATERIAL_UNAVAILABLE
elif counts[value.material_number] > 1:
number, name, status = None, None, MATERIAL_AMBIGUOUS
@@ -62,6 +62,7 @@ class MaterialCalculationConfig:
specific_discharge_kg_per_signal_unit_m: float | None = None
erp_workplace: str = ""
production_order_format: str = ""
fallback_nominal_width_m: float | None = None
process_application_calculation_id: str | None = None
@@ -149,9 +150,14 @@ def load_material_calculation(
except ValueError as exc:
raise CalculationConfigError("Invalid production_order_format") from exc
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 (
"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")
if "calibration_ref" in entry:
@@ -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
)
@@ -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)
+73 -3
View File
@@ -104,6 +104,18 @@ def _parser() -> argparse.ArgumentParser:
default=Path("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")
runners = run.add_subparsers(dest="command", required=True)
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("--secrets-file", type=Path, default=Path("secrets/enlyze.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("--meter")
power.add_argument("--start", help="ISO timestamp; defaults to one polling window ago")
@@ -129,6 +143,16 @@ def _parser() -> argparse.ArgumentParser:
monthly.add_argument("--month", required=True, help="YYYY-MM")
monthly.add_argument("--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"
)
@@ -258,8 +282,9 @@ def _parse_cli_timestamp(value: str) -> object:
def _run_power_meter(args: argparse.Namespace) -> int:
from datetime import UTC, datetime, timedelta
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.power_meter.config import load_power_meter_config
@@ -292,6 +317,7 @@ def _run_power_meter(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.power_meter.config import load_power_meter_config
from production_analytics.power_meter.repository import PostgresPowerMeterRepository
@@ -300,7 +326,8 @@ def _run_monthly_report(args: argparse.Namespace) -> int:
config = load_power_meter_config(args.config, args.meter)
environment = _runtime_environment(args.db_secrets_file)
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)
return 0
except (CalculationConfigError, ConfigurationError, ValueError, RuntimeError) as exc:
@@ -308,6 +335,36 @@ def _run_monthly_report(args: argparse.Namespace) -> int:
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
@@ -325,6 +382,17 @@ def _run_downtime(args: argparse.Namespace) -> int:
def main(argv: Sequence[str] | None = None) -> int:
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.command == "channel-material-poll":
return _run_channel_material(args)
@@ -336,6 +404,8 @@ def main(argv: Sequence[str] | None = None) -> int:
return _run_downtime(args)
return _run_material(args)
if args.namespace == "report":
if args.command == "shift":
return _run_shift_report(args)
return _run_monthly_report(args)
if args.namespace != "enlyze" or args.command not in {"raw", "timeseries"}:
return 2
+127 -10
View File
@@ -4,6 +4,7 @@ from dataclasses import dataclass
from datetime import UTC, datetime
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 (
@@ -11,6 +12,7 @@ from production_analytics.calculations.material_consumption import (
area_application_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
if TYPE_CHECKING:
@@ -152,6 +154,91 @@ class EnlyzeApiGateway:
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(
self,
*,
@@ -308,8 +395,8 @@ class EnlyzeApiGateway:
) -> dict[str, list[DosingChannelSample]]:
"""Read configured dosing channels through the gateway only.
Configurations name stable PLC origins; ENLYZE UUIDs are resolved at poll
time and must be unique, preventing a silently stale variable mapping.
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
@@ -355,9 +442,17 @@ class EnlyzeApiGateway:
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) in resolved.items():
for key, (total, status, percentage, screw, material, name) in resolved.items():
sample = self._dosing_sample(
row, columns, timestamp, total, status, percentage, screw, material
row,
columns,
timestamp,
total,
status,
percentage,
screw,
material,
name,
)
if sample is not None:
result[key].append(sample)
@@ -376,10 +471,11 @@ class EnlyzeApiGateway:
*,
machine_id: str,
channels: tuple["ChannelDefinition", ...],
) -> dict[str, tuple[str, str, str, str, str | None]]:
"""Resolve configured PLC origins without reading samples or writing state."""
origins = self._variables_by_origin(machine_id)
resolved: dict[str, tuple[str, str, str, str, str | None]] = {}
) -> 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,
@@ -394,7 +490,17 @@ class EnlyzeApiGateway:
else None
)
key = channel.channel + "\0" + channel.extruder
resolved[key] = (*ids, material)
name = None
if channel.material_name_signal_ref is not None:
if material is not None:
raise ValueError("Material number and name signals are mutually exclusive")
ref = channel.material_name_signal_ref
if not ref.startswith("uuid:"):
raise ValueError("material_name_signal_ref must be uuid:<UUID>")
name = str(UUID(ref[5:]))
if name not in variable_ids:
raise ValueError(f"Configured material-name UUID {name!r} is unavailable")
resolved[key] = (*ids, material, name)
return resolved
@staticmethod
@@ -407,6 +513,7 @@ class EnlyzeApiGateway:
percentage: str,
screw: str,
material: str | None,
name: str | None = None,
) -> DosingChannelSample | None:
def numeric(variable: str) -> float:
value = row[columns.index(variable)]
@@ -438,6 +545,9 @@ class EnlyzeApiGateway:
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),
@@ -445,9 +555,12 @@ class EnlyzeApiGateway:
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) -> dict[str, list[str]]:
def _variables_by_origin(
self, machine_id: str, *, variable_ids: set[str] | None = None
) -> dict[str, list[str]]:
params = {"machine": machine_id}
result: dict[str, list[str]] = {}
cursors: set[str] = set()
@@ -461,6 +574,10 @@ class EnlyzeApiGateway:
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")
+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 (
CurrentWorkplaceStatus,
ErpFiberBookingGateway,
ErpProductionConfirmationGateway,
ErpReadError,
ErpSettings,
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
from collections.abc import Mapping
from dataclasses import dataclass, field
from datetime import datetime
from datetime import UTC, datetime
from decimal import Decimal
from math import isfinite
from zoneinfo import ZoneInfo
import pymssql
from production_analytics.calculations.fiber_allocation import FiberBooking
from production_analytics.enlyze.exploration import ConfigurationError, load_secret_file
@@ -22,7 +24,10 @@ class ErpSettings:
def __post_init__(self) -> None:
for attribute, suffix in (
("host", "HOST"), ("database", "NAME"), ("user", "USER"), ("password", "PASSWORD"),
("host", "HOST"),
("database", "NAME"),
("user", "USER"),
("password", "PASSWORD"),
):
value = getattr(self, attribute)
if not isinstance(value, str) or not value.strip() or "\x00" in value:
@@ -40,7 +45,8 @@ class ErpSettings:
except ValueError:
raise ConfigurationError("ERP_DB_PORT must be an integer from 1 to 65535") from None
return cls(
host=environment.get("ERP_DB_HOST", ""), port=port,
host=environment.get("ERP_DB_HOST", ""),
port=port,
database=environment.get("ERP_DB_NAME", ""),
user=environment.get("ERP_DB_USER", ""),
password=environment.get("ERP_DB_PASSWORD", ""),
@@ -48,8 +54,10 @@ class ErpSettings:
@classmethod
def from_secret_file(
cls, path: str | os.PathLike[str] = "secrets/erp.env",
*, environment: Mapping[str, str] | None = None,
cls,
path: str | os.PathLike[str] = "secrets/erp.env",
*,
environment: Mapping[str, str] | None = None,
) -> "ErpSettings":
"""Load dotenv values over the environment, following the existing convention."""
try:
@@ -62,7 +70,7 @@ class ErpSettings:
@dataclass(frozen=True, slots=True)
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
production_order: str
@@ -97,9 +105,13 @@ class ErpWorkplaceStatusGateway:
raise ValueError("workplace 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,
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(_CURRENT_STATUS_SQL, (workplace,))
@@ -117,12 +129,17 @@ class ErpWorkplaceStatusGateway:
if len(row) != 10 or not isinstance(row[4], datetime):
raise ValueError
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_description=_text(row[3], nullable=True),
feedback_timestamp=row[4],
order_quantity_m2=_number(row[5]), good_quantity_m2=_number(row[6]),
remaining_quantity_m2=_number(row[7]), remaining_time_hours=_number(row[8]),
feedback_timestamp=(
row[4].replace(tzinfo=_PLANT_TIMEZONE) if row[4].utcoffset() is None else row[4]
),
order_quantity_m2=_number(row[5]),
good_quantity_m2=_number(row[6]),
remaining_quantity_m2=_number(row[7]),
remaining_time_hours=_number(row[8]),
remaining_rolls=_number(row[9]),
)
except Exception:
@@ -146,3 +163,270 @@ def _number(value: object) -> float | None:
if not isfinite(result):
raise ValueError
return result
_PLANT_TIMEZONE = ZoneInfo("Europe/Berlin")
@dataclass(frozen=True, slots=True)
class ProductionConfirmation:
"""Historical ERP view row; quantities follow the view's production semantics."""
workplace: str
production_order: str
timestamp: datetime
article_number: str | None
article_description: str | None
roll_number: str | None
production_quantity_m2: float | None
feedback_quantity_m2: float | None
raw_material_number: str | None
raw_material_description: str | None
batch_number: str | None
raw_material_quantity: float | None
tenant: str | None
@property
def is_finished_goods(self) -> bool:
"""Positive feedback identifies finished production, independently of workplace."""
return self.feedback_quantity_m2 is not None and self.feedback_quantity_m2 > 0
_PRODUCTION_CONFIRMATION_SQL = """SELECT
[Mandant], [Fertigungsauftragsnummer], [Zeitstempel], [Arbeitsplatz],
[Artikelnummer], [Artikelbezeichnung], [Rollennummer], [Fertigungsmenge],
[Rohstoffnummer], [Rohstoffbezeichnung], [Chargennummer], [Rückmeldemenge], [Fasermenge]
FROM [dbo].[GRAFANA_PRODUCTION_CONFIRMATION]
WHERE [Arbeitsplatz] = %s AND [Zeitstempel] >= %s AND [Zeitstempel] < %s
ORDER BY [Zeitstempel], [Mandant], [Fertigungsauftragsnummer], [Rollennummer],
[Artikelnummer], [Rohstoffnummer], [Chargennummer], [Fertigungsmenge],
[Rückmeldemenge], [Fasermenge], [Artikelbezeichnung], [Rohstoffbezeichnung]"""
class ErpProductionConfirmationGateway:
"""Read complete view rows for an exact workplace and a plant-local [start, end).
SQL datetime stores no offset or fold. Ambiguous autumn timestamps are attached
with fold=0 (the first occurrence); the source cannot identify their actual fold.
Windows whose local end does not follow their local start cannot be expressed
by this SQL predicate and are rejected. Repeated hours cannot be queried separately.
"""
def __init__(self, settings: ErpSettings) -> None:
self._settings = settings
def get_confirmations(
self, *, workplace: str, start: datetime, end: datetime,
timezone: ZoneInfo | None = None,
) -> list[ProductionConfirmation]:
timezone = _PLANT_TIMEZONE if timezone is None else timezone
if not isinstance(timezone, ZoneInfo):
raise ValueError("timezone must be a ZoneInfo")
if not isinstance(workplace, str) or not workplace.strip() or "\x00" in workplace:
raise ValueError("workplace must be a non-empty string without NUL bytes")
for name, value in (("start", start), ("end", end)):
if not isinstance(value, datetime) or value.tzinfo is None or value.utcoffset() is None:
raise ValueError(f"{name} must be a timezone-aware datetime")
if end.astimezone(UTC) <= start.astimezone(UTC):
raise ValueError("end must follow start")
local_start = start.astimezone(timezone).replace(tzinfo=None)
local_end = end.astimezone(timezone).replace(tzinfo=None)
if local_end <= local_start:
raise ValueError("end must follow start in plant-local SQL time")
try:
with pymssql.connect(
server=self._settings.host,
port=self._settings.port,
database=self._settings.database,
user=self._settings.user,
password=self._settings.password,
login_timeout=10,
timeout=10,
) as connection:
with connection.cursor() as cursor:
cursor.execute(
_PRODUCTION_CONFIRMATION_SQL, (workplace.strip(), local_start, local_end)
)
rows = cursor.fetchall()
except Exception:
raise ErpReadError("ERP production confirmation read failed") from None
try:
return [_production_confirmation(row, timezone) for row in rows]
except Exception:
raise ErpReadError("ERP production confirmation returned an invalid row") from None
def search_orders(self, query: str, *, limit: int = 25) -> list["OrderConfirmationGroup"]:
query = _order_query(query)
if type(limit) is not int or not 1 <= limit <= 100:
raise ValueError("limit must be between 1 and 100")
pattern = "%" + query.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%"
rows = self._read_orders(_ORDER_SEARCH_SQL, (limit, pattern, query, query))
try:
return [_order_group(row) for row in rows]
except Exception:
raise ErpReadError("ERP production-order search returned an invalid row") from None
def get_order_confirmations(self, production_order: str) -> list["OrderConfirmationRow"]:
order = _order_query(production_order)
rows = self._read_orders(_ORDER_DETAIL_SQL, (order,))
try:
return [_order_confirmation(row) for row in rows]
except Exception:
raise ErpReadError("ERP production-order detail returned an invalid row") from None
def _read_orders(self, sql: str, parameters: tuple) -> list[tuple]:
try:
with pymssql.connect(
server=self._settings.host, port=self._settings.port,
database=self._settings.database, user=self._settings.user,
password=self._settings.password, login_timeout=10, timeout=10,
) as connection:
with connection.cursor() as cursor:
cursor.execute(sql, parameters)
return cursor.fetchall()
except Exception:
raise ErpReadError("ERP production-order read failed") from None
@dataclass(frozen=True, slots=True)
class OrderConfirmationGroup:
production_order: str
workplace: str
article_number: str | None
article_description: str | None
first_confirmation_local: datetime
last_confirmation_local: datetime
@dataclass(frozen=True, slots=True)
class OrderConfirmationRow:
production_order: str
workplace: str
article_number: str | None
article_description: str | None
timestamp_local: datetime
feedback_quantity_m2: float
_ORDER_SEARCH_SQL = """WITH matching_orders AS (
SELECT TOP (%s) [Fertigungsauftragsnummer]
FROM [dbo].[GRAFANA_PRODUCTION_CONFIRMATION]
WHERE [Fertigungsauftragsnummer] LIKE %s ESCAPE '\\' AND [Rückmeldemenge] > 0
GROUP BY [Fertigungsauftragsnummer]
ORDER BY CASE WHEN [Fertigungsauftragsnummer] = %s THEN 0 ELSE 1 END,
[Fertigungsauftragsnummer]
)
SELECT c.[Fertigungsauftragsnummer], c.[Arbeitsplatz], c.[Artikelnummer],
c.[Artikelbezeichnung], MIN(c.[Zeitstempel]), MAX(c.[Zeitstempel])
FROM [dbo].[GRAFANA_PRODUCTION_CONFIRMATION] AS c
JOIN matching_orders AS m ON m.[Fertigungsauftragsnummer] = c.[Fertigungsauftragsnummer]
WHERE c.[Rückmeldemenge] > 0
GROUP BY c.[Fertigungsauftragsnummer], c.[Arbeitsplatz], c.[Artikelnummer],
c.[Artikelbezeichnung]
ORDER BY CASE WHEN c.[Fertigungsauftragsnummer] = %s THEN 0 ELSE 1 END,
c.[Fertigungsauftragsnummer], c.[Arbeitsplatz], c.[Artikelnummer], c.[Artikelbezeichnung]"""
_ORDER_DETAIL_SQL = """SELECT [Fertigungsauftragsnummer], [Arbeitsplatz], [Artikelnummer],
[Artikelbezeichnung], [Zeitstempel], [Rückmeldemenge]
FROM [dbo].[GRAFANA_PRODUCTION_CONFIRMATION]
WHERE [Fertigungsauftragsnummer] = %s AND [Rückmeldemenge] > 0
ORDER BY [Zeitstempel], [Arbeitsplatz], [Artikelnummer], [Artikelbezeichnung],
[Rückmeldemenge]"""
def _order_query(value: str) -> str:
if (not isinstance(value, str) or not value.strip() or "\x00" in value
or len(value.strip()) > 80):
raise ValueError("production order query must be 1–80 non-NUL characters")
return value.strip()
def _order_group(row: tuple) -> OrderConfirmationGroup:
if len(row) != 6 or any(not isinstance(row[index], datetime)
or row[index].tzinfo is not None for index in (4, 5)):
raise ValueError
return OrderConfirmationGroup(_text(row[0]), _text(row[1]),
_text(row[2], nullable=True), _text(row[3], nullable=True),
row[4], row[5])
def _order_confirmation(row: tuple) -> OrderConfirmationRow:
if len(row) != 6 or not isinstance(row[4], datetime) or row[4].tzinfo is not None:
raise ValueError
quantity = _number(row[5])
if quantity is None or quantity <= 0:
raise ValueError
return OrderConfirmationRow(_text(row[0]), _text(row[1]),
_text(row[2], nullable=True), _text(row[3], nullable=True),
row[4], quantity)
def _production_confirmation(row: tuple[object, ...], timezone: ZoneInfo) -> ProductionConfirmation:
if len(row) != 13 or not isinstance(row[2], datetime) or row[2].tzinfo is not None:
raise ValueError
return ProductionConfirmation(
workplace=_text(row[3]),
production_order=_text(row[1]),
timestamp=row[2].replace(tzinfo=timezone, fold=0),
article_number=_text(row[4], nullable=True),
article_description=_text(row[5], nullable=True),
roll_number=_text(row[6], nullable=True),
production_quantity_m2=_number(row[7]),
feedback_quantity_m2=_number(row[11]),
raw_material_number=_text(row[8], nullable=True),
raw_material_description=_text(row[9], nullable=True),
batch_number=_text(row[10], nullable=True),
raw_material_quantity=_number(row[12]),
tenant=_text(row[0], nullable=True),
)
_FIBER_BOOKING_SQL = """SELECT [Fertigungsauftragsnummer], [Rohstoffnummer],
[Rohstoffbezeichnung], [Fasermenge]
FROM [dbo].[GRAFANA_PRODUCTION_CONFIRMATION]
WHERE [Fertigungsauftragsnummer] = %s AND [Fasermenge] > 0
AND NULLIF(LTRIM(RTRIM([Rohstoffnummer])), '') IS NOT NULL
ORDER BY [Rohstoffnummer], [Rohstoffbezeichnung], [Fasermenge]"""
class ErpFiberBookingGateway:
"""Order-wide positive raw-material bookings; never a measured shift quantity."""
def __init__(self, settings: ErpSettings) -> None:
self._settings = settings
def get_fiber_bookings(self, production_order: str) -> list[FiberBooking]:
if (
not isinstance(production_order, str)
or not production_order.strip()
or "\x00" in production_order
):
raise ValueError("production_order must be a non-empty string without NUL bytes")
try:
with pymssql.connect(
server=self._settings.host,
port=self._settings.port,
database=self._settings.database,
user=self._settings.user,
password=self._settings.password,
login_timeout=10,
timeout=10,
) as connection:
with connection.cursor() as cursor:
cursor.execute(_FIBER_BOOKING_SQL, (production_order.strip(),))
rows = cursor.fetchall()
except Exception:
raise ErpReadError("ERP fiber booking read failed") from None
try:
return [
FiberBooking(
_text(row[0]),
_text(row[1], nullable=True),
_text(row[2], nullable=True),
_number(row[3]),
)
for row in rows
]
except Exception:
raise ErpReadError("ERP fiber booking returned an invalid row") from None
@@ -0,0 +1 @@
"""Output presenters independent of report composition and source access."""
@@ -0,0 +1,29 @@
"""Shared, server-rendered navigation between the two web workflows."""
from typing import Literal
Mode = Literal["shift", "order"]
MODE_NAV_CSS = """
.mode-nav{display:inline-flex;gap:.25rem;padding:.25rem;margin-bottom:1rem;
background:#e8eef3;border:1px solid #aab9c5;border-radius:.55rem}
.mode-nav a{display:block;padding:.55rem .85rem;border:1px solid transparent;
border-radius:.35rem;color:#182c3b;font-weight:600;text-decoration:none}
.mode-nav a:hover{background:#d4e0e9}
.mode-nav a[aria-current="page"]{background:#294d67;border-color:#294d67;color:white}
.mode-nav a[aria-current="page"]:hover{background:#294d67}
.mode-nav a:focus-visible{outline:3px solid #bf6525;outline-offset:2px}
"""
def render_mode_navigation(active: Mode) -> str:
if active not in ("shift", "order"):
raise ValueError("Unknown web workflow")
links = (("shift", "/", "Schichtbericht"),
("order", "/orders", "Fertigungsauftrag"))
items = "".join(
f'<a href="{href}"' + (' aria-current="page"' if mode == active else "")
+ f">{label}</a>"
for mode, href, label in links
)
return f'<nav class="mode-nav" aria-label="Bereich wählen">{items}</nav>'
@@ -0,0 +1,125 @@
"""Server-rendered, escaped production-order search and detail pages."""
from html import escape
from urllib.parse import urlencode
from production_analytics.presentation.mode_navigation import (
MODE_NAV_CSS,
render_mode_navigation,
)
from production_analytics.presentation.shift_report import _number
from production_analytics.service.production_order import (
ProductionOrderDetail,
ProductionOrderSearchResult,
)
SHIFT_LABELS = {"early": "Frühschicht", "late": "Spätschicht", "night": "Nachtschicht"}
def _page(title: str, body: str) -> str:
return f'''<!doctype html><html lang="de"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{escape(title)}</title><style>
body {{font:16px system-ui,sans-serif;background:#f4f6f8;color:#182c3b;margin:0}}
main {{max-width:1100px;margin:2rem auto;padding:1.5rem;background:white}}
form {{display:flex;flex-wrap:wrap;gap:.7rem;align-items:end;padding:1rem;background:#e8eef3}}
label {{display:grid;gap:.4rem}} input,button {{font:inherit;padding:.55rem}}
table {{width:100%;border-collapse:collapse}} th,td {{text-align:left;padding:.7rem;
border-bottom:1px solid #c9d1d8}} th {{background:#e8eef3}}
.table-scroll {{overflow-x:auto}} .metadata {{color:#526473;font-size:.9rem}}
.error {{padding:1rem;background:#ffe8e5;border-left:4px solid #a32920}}
{MODE_NAV_CSS}</style></head><body><main>{render_mode_navigation("order")}
{body}</main></body></html>'''
def _form(query: str) -> str:
return ('<form method="get" action="/orders"><label>Fertigungsauftrag (FA)'
f'<input type="search" name="q" value="{escape(query, quote=True)}"'
' maxlength="80" required></label><button type="submit">Suchen</button></form>')
def _text(value: str | None) -> str:
return escape(value) if value else "–"
def _period(value, timezone) -> str:
label = value.strftime("%d.%m.%Y %H:%M")
return escape(f"{label} ({timezone.key})" if timezone else f"{label} (ERP-Lokalzeit)")
def render_search(*, query: str = "", results: tuple[ProductionOrderSearchResult, ...] = (),
error: str | None = None, searched: bool = False) -> str:
body = "<h1>Fertigungsauftrag suchen</h1>" + _form(query)
if error:
body += f'<p class="error" role="alert">{escape(error)}</p>'
elif searched:
if not results:
body += "<p>Keine passenden Fertigungsaufträge gefunden.</p>"
else:
body += '<div class="table-scroll"><table><thead><tr><th>FA</th><th>Artikel</th>'
body += '<th>Artikelbezeichnung</th><th>Arbeitsplatz / Maschine</th>'
body += '<th>Erste Rückmeldung</th><th>Letzte Rückmeldung</th></tr></thead><tbody>'
for result in results:
href = "/order?" + urlencode({"production_order": result.production_order})
for placement in result.placements:
machine = placement.machine_name or "nicht zugeordnet"
link = (f'<a href="{escape(href, quote=True)}">'
f'{escape(result.production_order)}</a>')
body += "<tr>" + "".join(f"<td>{cell}</td>" for cell in (
link,
_text(placement.article_number), _text(placement.article_description),
escape(f"{placement.workplace} / {machine}"),
_period(placement.first_confirmation_local, placement.timezone),
_period(placement.last_confirmation_local, placement.timezone),
)) + "</tr>"
body += "</tbody></table></div>"
return _page("Fertigungsauftrag suchen", body)
def render_detail(*, detail: ProductionOrderDetail | None,
error: str | None = None) -> str:
if error:
return _page("Fertigungsauftrag", f'<p class="error" role="alert">{escape(error)}</p>')
if detail is None:
return _page("Fertigungsauftrag", "<p>Fertigungsauftrag nicht gefunden.</p>")
body = f"<h1>Fertigungsauftrag {escape(detail.production_order)}</h1>"
body += '<p class="metadata">Zeiten sind ERP-Rückmeldezeitpunkte, keine durchgehenden '
body += 'Maschinenlaufzeiten. Mengen sind positive Rückmeldemengen in m². '
body += 'Geschwindigkeit und Material beziehen sich auf angenäherte FA-Zeitfenster.</p>'
body += '<h2>Artikel und Arbeitsplätze</h2><div class="table-scroll"><table><thead><tr>'
body += '<th>Artikel</th><th>Artikelbezeichnung</th><th>Arbeitsplatz / Maschine</th>'
body += '<th>Erste Rückmeldung</th><th>Letzte Rückmeldung</th></tr></thead><tbody>'
for placement in detail.placements:
machine = placement.machine_name or f"nicht zugeordnet ({placement.mapping_status})"
body += "<tr>" + "".join(f"<td>{cell}</td>" for cell in (
_text(placement.article_number), _text(placement.article_description),
escape(f"{placement.workplace} / {machine}"),
_period(placement.first_confirmation_local, placement.timezone),
_period(placement.last_confirmation_local, placement.timezone),
)) + "</tr>"
body += '</tbody></table></div><h2>Schichten</h2>'
if not detail.shifts:
body += "<p>Keine Schichtzuordnung für konfigurierte Maschinen verfügbar.</p>"
else:
body += '<div class="table-scroll"><table><thead><tr><th>Standort</th><th>Maschine</th>'
body += '<th>Datum</th><th>Schicht</th><th>Produzierte Menge</th>'
body += '<th>Ø Geschwindigkeit</th><th>Materialverbrauch</th>'
body += '<th>Erste Rückmeldung</th><th>Letzte Rückmeldung</th><th>Bericht</th>'
body += '</tr></thead><tbody>'
for item in detail.shifts:
href = "/?" + urlencode({"date": item.date.isoformat(), "shift": item.shift,
"machine": item.machine_name})
body += "<tr>" + "".join(f"<td>{cell}</td>" for cell in (
escape(item.site.title()), escape(item.machine_name),
item.date.strftime("%d.%m.%Y"),
SHIFT_LABELS[item.shift], f"{item.produced_m2:,.2f} m²",
(f"{_number(item.average_speed_m_min)} m/min"
if item.average_speed_m_min is not None else "—"),
(f"{_number(item.material_consumption_kg)} kg"
if item.material_consumption_kg is not None else "—"),
escape(item.first_confirmation.strftime("%d.%m.%Y %H:%M %Z")),
escape(item.last_confirmation.strftime("%d.%m.%Y %H:%M %Z")),
f'<a href="{escape(href, quote=True)}">Schichtbericht</a>',
)) + "</tr>"
body += "</tbody></table></div>"
return _page(f"Fertigungsauftrag {detail.production_order}", body)
@@ -0,0 +1,309 @@
"""German operational shift slips with deterministic A4 PDF output."""
from collections import defaultdict
from dataclasses import dataclass
from io import BytesIO
from math import fsum
from pathlib import Path
from xml.sax.saxutils import escape
from production_analytics.calculations.shift_report import ShiftReport
def _number(value: float) -> str:
return f"{value:,.2f}".translate(str.maketrans({",": ".", ".": ","}))
def _duration(seconds: float) -> str:
hours, remainder = divmod(round(seconds, 1), 3600)
minutes, seconds = divmod(remainder, 60)
return f"{int(hours)} h {int(minutes):02d} min {seconds:04.1f} s".replace(".", ",")
@dataclass(frozen=True, slots=True)
class TextBlock:
text: str
style: str = "Normal"
@dataclass(frozen=True, slots=True)
class TableBlock:
headers: tuple[str, ...]
rows: tuple[tuple[str, ...], ...]
widths_mm: tuple[float, ...]
@dataclass(frozen=True, slots=True)
class MaterialPieBlock:
labels: tuple[str, ...]
consumption_kg: tuple[float, ...]
def present_report(
report: ShiftReport,
*,
include_single_material_chart: bool = False,
) -> tuple[TextBlock | TableBlock | MaterialPieBlock, ...]:
"""Format supplied values and material totals without source access or a clock."""
story = []
def text(value: str, style: str = "Normal") -> None:
story.append(TextBlock(value, style))
def table(headers: tuple[str, ...], rows: list[tuple], widths: list[float]) -> None:
story.append(TableBlock(headers, tuple(rows), tuple(widths)))
text("Schichtbericht", "Title")
text(f"Maschine: {report.display_name or report.machine_name}", "Heading2")
for label, timestamp in (("Schichtbeginn", report.start), ("Schichtende", report.end)):
text(f"{label}: {timestamp.astimezone(report.timezone):%d.%m.%Y %H:%M:%S %Z (%z)}")
text(f"Zeitzone: {report.timezone.key}")
text("Produktion", "Heading2")
if report.production is None:
text("Für diese Maschine nicht verfügbar.")
elif report.production.items:
table(
("Produktionsauftrag", "Artikelnummer", "Artikelbeschreibung", "Menge", "Rollen",
"Ø Geschwindigkeit", "Materialverbrauch"),
[
(
item.production_order,
item.article_number or "Nicht verfügbar",
item.article_description or "Nicht verfügbar",
f"{_number(item.produced_m2)} m²",
str(item.roll_count),
(f"{_number(item.average_speed_m_min)} m/min"
if item.average_speed_m_min is not None else "—"),
(f"{_number(item.material_consumption_kg)} kg"
if item.material_consumption_kg is not None else "—"),
)
for item in report.production.items
],
[28, 22, 44, 23, 13, 23, 25],
)
elif report.production is not None:
text("Keine Produktionsdaten vorhanden.")
if report.production is not None:
text(
f"Gesamtmenge: {_number(report.production.total_produced_m2)} m² | "
f"Rollen gesamt: {report.production.total_roll_count}"
)
text("Stillstand", "Heading2")
if report.downtime is None:
text("Für diese Maschine nicht verfügbar.")
else:
text(f"Stillstand gesamt: {_duration(report.downtime.total_downtime_seconds)}")
text("Zeit ohne erfassten Stillstand: " + _duration(report.downtime.non_downtime_seconds))
text("Top 3 Stillstandsgründe", "Heading3")
if report.top_downtime_reasons:
table(
("Stillstandsgrund", "Dauer"),
[
(view.display_name, _duration(view.reason.duration_seconds))
for view in report.top_downtime_reasons
],
[125, 53],
)
else:
text("Keine Stillstandsgründe vorhanden.")
if not report.downtime.events:
text("Keine Stillstandsereignisse vorhanden.")
text("Materialverbrauch", "Heading2")
if report.materials is None:
text("Für diese Maschine nicht verfügbar.")
else:
material_totals = defaultdict(list)
for item in report.materials.items:
material_totals[(item.material_number, item.material_name)].append(item.consumption_kg)
materials = [
(number, name, fsum(quantities))
for (number, name), quantities in sorted(
material_totals.items(),
key=lambda entry: (entry[0][1] or "", entry[0][0] or ""),
)
if fsum(quantities) != 0
]
if any(item.erp_booking_share is not None for item in report.materials.items):
allocation_totals = defaultdict(list)
for item in report.materials.items:
allocation_totals[
(
item.production_order,
item.material_number,
item.material_name,
item.erp_booking_share,
)
].append(item.consumption_kg)
rows = []
for (order, number, name, share), quantities in sorted(
allocation_totals.items(),
key=lambda entry: (
entry[0][0],
entry[0][2] or "",
entry[0][1] or "",
-1 if entry[0][3] is None else entry[0][3],
),
):
quantity = fsum(quantities)
if quantity != 0:
rows.append(
(
order,
name or number or "Materialzuordnung fehlt",
number or "–",
f"{_number(quantity)} kg",
f"{share * 100:.0f}%" if share is not None else "–",
)
)
if rows:
table(
("Produktionsauftrag", "Materialname", "Materialnummer", "Verbrauch",
"ERP-Anteil"),
rows,
[32, 66, 28, 30, 22],
)
else:
text("Keine Materialverbrauchsdaten vorhanden.")
text(
"Verbrauchsaufteilung geschätzt nach ERP-Buchungsverhältnis; "
"Gesamtverbrauch aus ENLYZE."
)
elif materials:
table(
("Materialname", "Materialnummer", "Verbrauch"),
[
(
name or number or "Materialzuordnung fehlt",
number or "–",
f"{_number(quantity)} kg",
)
for number, name, quantity in materials
],
[110, 38, 30],
)
else:
text("Keine Materialverbrauchsdaten vorhanden.")
text(f"Materialverbrauch gesamt: {_number(report.materials.total_consumption_kg)} kg")
positive_materials = [
(number, name, quantity) for number, name, quantity in materials if quantity > 0
]
if len(positive_materials) >= (1 if include_single_material_chart else 2):
base_labels = [
name or number or "Materialzuordnung fehlt"
for number, name, _ in positive_materials
]
labels = tuple(
f"{label} ({number or 'ohne Materialnummer'})"
if base_labels.count(label) > 1
else label
for label, (number, _, _) in zip(base_labels, positive_materials)
)
story.append(
MaterialPieBlock(labels, tuple(quantity for _, _, quantity in positive_materials))
)
return tuple(story)
def render_pdf(report: ShiftReport) -> bytes:
"""Repeatable bytes with the same ReportLab version and invariant metadata."""
from reportlab.graphics.charts.piecharts import Pie
from reportlab.graphics.shapes import Drawing, Rect
from reportlab.lib import colors
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.units import mm
from reportlab.pdfgen.canvas import Canvas
from reportlab.platypus import Paragraph, SimpleDocTemplate, Spacer, Table, TableStyle
styles = getSampleStyleSheet()
styles["Normal"].fontSize = 9
styles["Normal"].leading = 12
def paragraph(value: str, style: str = "Normal") -> Paragraph:
return Paragraph(escape(value).replace("\n", "<br/>"), styles[style])
story = []
for block in present_report(report):
if isinstance(block, TextBlock):
story.extend([paragraph(block.text, block.style), Spacer(1, 3 * mm)])
elif isinstance(block, MaterialPieBlock):
palette = tuple(
colors.HexColor(value)
for value in ("#496a81", "#8aa399", "#c4ad7a", "#9a869f", "#8399b0", "#b78e7c")
)
drawing = Drawing(65 * mm, 60 * mm)
pie = Pie()
pie.x, pie.y = 5 * mm, 2 * mm
pie.width = pie.height = 55 * mm
pie.data = list(block.consumption_kg)
pie.labels = []
pie.slices.strokeColor = colors.white
pie.slices.strokeWidth = 0.5
legend_rows = []
for index, label in enumerate(block.labels):
color = palette[index % len(palette)]
pie.slices[index].fillColor = color
swatch = Drawing(4 * mm, 4 * mm)
swatch.add(Rect(0, 0, 4 * mm, 4 * mm, fillColor=color, strokeColor=None))
legend_rows.append([swatch, paragraph(label)])
drawing.add(pie)
legend = Table(legend_rows, colWidths=[8 * mm, 101 * mm])
legend.setStyle(TableStyle([("VALIGN", (0, 0), (-1, -1), "TOP")]))
chart = Table([[drawing, legend]], colWidths=[65 * mm, 113 * mm], splitInRow=1)
chart.setStyle(
TableStyle(
[
("VALIGN", (0, 0), (-1, -1), "TOP"),
("LEFTPADDING", (0, 0), (-1, -1), 0),
("RIGHTPADDING", (0, 0), (-1, -1), 0),
]
)
)
story.extend([chart, Spacer(1, 4 * mm)])
else:
cells = [[paragraph(value) for value in row] for row in [block.headers, *block.rows]]
result = Table(cells, colWidths=[width * mm for width in block.widths_mm], repeatRows=1)
result.setStyle(
TableStyle(
[
("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#e8eef3")),
("VALIGN", (0, 0), (-1, -1), "TOP"),
("LINEBELOW", (0, 0), (-1, -1), 0.3, colors.HexColor("#c9d1d8")),
("TOPPADDING", (0, 0), (-1, -1), 6),
("BOTTOMPADDING", (0, 0), (-1, -1), 6),
]
)
)
story.extend([result, Spacer(1, 4 * mm)])
buffer = BytesIO()
document = SimpleDocTemplate(
buffer,
pagesize=A4,
leftMargin=16 * mm,
rightMargin=16 * mm,
topMargin=16 * mm,
bottomMargin=16 * mm,
title="Schichtbericht",
author="Production Analytics",
pageCompression=0,
)
def canvas(*args, **kwargs):
kwargs["invariant"] = 1
return Canvas(*args, **kwargs)
def footer(canvas, document):
canvas.saveState()
canvas.setFont("Helvetica", 8)
canvas.drawRightString(A4[0] - 16 * mm, 10 * mm, f"Seite {document.page}")
canvas.restoreState()
document.build(story, canvasmaker=canvas, onFirstPage=footer, onLaterPages=footer)
return buffer.getvalue()
def write_pdf(report: ShiftReport, output: Path) -> None:
payload = render_pdf(report)
output.parent.mkdir(parents=True, exist_ok=True)
output.write_bytes(payload)
@@ -0,0 +1,149 @@
"""HTML formatting of the shared report presentation; no data-source access."""
from html import escape
from math import fsum
from urllib.parse import urlencode
from production_analytics.presentation.mode_navigation import (
MODE_NAV_CSS,
render_mode_navigation,
)
from production_analytics.presentation.shift_report import (
MaterialPieBlock,
TableBlock,
TextBlock,
_number,
present_report,
)
def _material_chart(block: MaterialPieBlock) -> str:
"""Draw supplied material slices; percentages are presentation geometry only.
No scripts or external assets: source labels are escaped HTML/SVG text.
The adjacent shared material table remains the textual source of truth.
"""
palette = ("#496a81", "#8aa399", "#c4ad7a", "#9a869f", "#8399b0", "#b78e7c")
total = fsum(block.consumption_kg)
slices, legend = [], []
offset = 0.0
for index, (label, kg) in enumerate(zip(block.labels, block.consumption_kg)):
percent = kg / total * 100
color = palette[index % len(palette)]
description = f"{label}: {_number(kg)} kg ({_number(percent)} %)"
slices.append(
f'<circle cx="60" cy="60" r="44" pathLength="100" fill="none" '
f'stroke="{color}" stroke-width="22" '
f'stroke-dasharray="{percent:.8f} {100 - percent:.8f}" '
f'stroke-dashoffset="{-offset:.8f}" transform="rotate(-90 60 60)">'
f"<title>{escape(description)}</title></circle>"
)
legend.append(
f'<li><span class="material-swatch" style="background:{color}" '
f'aria-hidden="true"></span><span>{escape(description)}</span></li>'
)
offset += percent
return (
'<figure class="material-chart"><figcaption>Verbrauchsanteile nach Material</figcaption>'
'<svg viewBox="0 0 120 120" role="img" aria-label="Materialverbrauch in kg">'
"<title>Verbrauchsanteile nach Material; Werte in der Legende</title>"
+ "".join(slices)
+ '</svg><ul class="material-legend">'
+ "".join(legend)
+ '</ul><p class="metadata">Anteile der positiven Verbrauchsmengen.</p></figure>'
)
def render_page(*, machines, labels, day, shift, machine, report, generated_at, error,
sites=None):
machine_labels = ((key, getattr(config, "display_name", key))
for key, config in machines.items())
def options(values, selected):
return "".join(
f'<option value="{escape(key, quote=True)}"'
+ (" selected" if key == selected else "")
+ f">{escape(label)}</option>"
for key, label in values
)
body = ""
if error:
body = f'<p class="error" role="alert">{escape(error)}</p>'
if report is not None:
body += (
f'<p class="metadata">Datenstand: {generated_at:%d.%m.%Y %H:%M:%S %Z} '
f"({report.timezone.key}). Quellen können nachträglich korrigiert werden.</p>"
)
material_open = False
details_open = False
for block in present_report(report, include_single_material_chart=True):
if isinstance(block, TextBlock):
if material_open and block.style == "Heading2":
body += ("</div>" if details_open else "") + "</div></section>"
material_open = details_open = False
if block.text == "Materialverbrauch" and block.style == "Heading2":
body += (
'<section class="material-section"><h2>Materialverbrauch</h2>'
'<div class="material-layout"><div class="material-details">'
)
material_open = details_open = True
continue
tag = {"Title": "h1", "Heading2": "h2", "Heading3": "h3"}.get(block.style, "p")
body += f"<{tag}>{escape(block.text)}</{tag}>"
elif isinstance(block, TableBlock):
body += '<div class="table-scroll"><table><thead><tr>'
body += "".join(f'<th scope="col">{escape(cell)}</th>' for cell in block.headers)
body += "</tr></thead><tbody>"
production_table = block.headers[:2] == ("Produktionsauftrag", "Artikelnummer")
for row in block.rows:
cells = []
for index, cell in enumerate(row):
if production_table and index == 0:
href = "/order?" + urlencode({"production_order": cell})
cells.append(
f'<td><a class="fa-link" href="{escape(href, quote=True)}">'
f"{escape(cell)}</a></td>"
)
else:
cells.append(f"<td>{escape(cell)}</td>")
body += "<tr>" + "".join(cells) + "</tr>"
body += "</tbody></table></div>"
elif isinstance(block, MaterialPieBlock):
body += "</div>" + _material_chart(block)
details_open = False
if material_open:
body += ("</div>" if details_open else "") + "</div></section>"
return f'''<!doctype html>
<html lang="de"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Live-Schichtberichte</title><style>
body {{font: 16px system-ui,sans-serif; background:#f4f6f8; color:#182c3b; margin:0}}
main {{max-width:1100px; margin:2rem auto; padding:1.5rem; background:white}}
form {{display:flex; flex-wrap:wrap; gap:1rem; align-items:end; padding:1rem;
background:#e8eef3}} label {{display:grid; gap:.4rem}}
input,select,button {{font:inherit; padding:.55rem}} button {{cursor:pointer}}
table {{width:100%; border-collapse:collapse}} th,td {{text-align:left; padding:.7rem;
border-bottom:1px solid #c9d1d8}} th {{background:#e8eef3}}
.table-scroll {{overflow-x:auto}} .metadata {{color:#526473; font-size:.9rem}}
.fa-link {{color:#17547a; font-weight:600; text-decoration:underline;
text-underline-offset:2px}} .fa-link:hover,.fa-link:focus-visible {{color:#0b3653}}
.material-layout {{display:grid; grid-template-columns:minmax(0, 1fr) 300px; gap:1.5rem}}
.material-chart {{margin:0; min-width:0}} .material-chart svg {{display:block;
width:220px; max-width:100%; margin:.75rem auto}}
.material-chart figcaption {{font-weight:600}} .material-legend {{list-style:none; padding:0}}
.material-legend li {{display:flex; gap:.5rem; margin:.6rem 0; overflow-wrap:anywhere}}
.material-swatch {{width:.9rem; height:.9rem; flex-shrink:0; margin-top:.2rem}}
@media(max-width:850px) {{.material-layout {{grid-template-columns:minmax(0, 1fr)}}}}
.error {{padding:1rem; background:#ffe8e5; border-left:4px solid #a32920}}
{MODE_NAV_CSS}</style></head><body><main>{render_mode_navigation("shift")}
<h1>Live-Schichtberichte</h1>
<form method="get" action="/">
<label>Datum (Schichtbeginn)<input type="date" name="date" required
value="{day.isoformat()}"></label>
<label>Schicht<select name="shift">{options(labels.items(), shift)}</select></label>
<label>Maschine<select name="machine">{options(machine_labels, machine)}
</select></label>
<button type="submit">Bericht anzeigen</button>
<button type="submit" name="format" value="pdf">Als PDF exportieren</button>
</form><p class="metadata">Nachtschicht: 22:00 Uhr am gewählten Datum bis 06:00 Uhr
am Folgetag. Jeder Aufruf liest die aktuellen Quelldaten.</p>{body}</main></body></html>'''
@@ -28,6 +28,7 @@ class ChannelDefinition:
percentage_signal_ref: str
screw_speed_signal_ref: str
material_number_signal_ref: str | None = None
material_name_signal_ref: str | None = None
@dataclass(frozen=True, slots=True)
@@ -0,0 +1,46 @@
"""Explicit K7 order adapter; generic measured material calculation stays ERP-free."""
import re
from collections import defaultdict
from dataclasses import replace
from math import fsum
from typing import Protocol
from production_analytics.calculations.fiber_allocation import (
FiberBooking,
allocate_fiber_materials,
)
from production_analytics.calculations.shift_material import ShiftMaterialSummary
class FiberBookingReader(Protocol):
def get_fiber_bookings(self, production_order: str) -> list[FiberBooking]: ...
class K7FiberAllocationService:
def __init__(self, reader: FiberBookingReader) -> None:
self.reader = reader
def allocate(self, measured: ShiftMaterialSummary) -> ShiftMaterialSummary:
bookings = {}
items = []
for item in measured.items:
match = re.fullmatch(r"(?:K 7-)?([0-9]+)", item.production_order.strip())
if match is None:
items.append(item)
continue
order = match[1]
if order not in bookings:
bookings[order] = self.reader.get_fiber_bookings(order)
items.extend(allocate_fiber_materials(item, bookings[order], erp_order=order))
# Keep the measured shift total, rather than replacing it with an ERP total.
return replace(measured, items=tuple(items))
def totals_by_order(self, allocated: ShiftMaterialSummary) -> dict[str, float]:
"""Sum the same allocated items shown in the shift material table by ERP FA."""
quantities = defaultdict(list)
for item in allocated.items:
match = re.fullmatch(r"(?:K 7-)?([0-9]+)", item.production_order.strip())
if match is not None:
quantities[match[1]].append(item.consumption_kg)
return {order: fsum(values) for order, values in quantities.items()}
@@ -0,0 +1,98 @@
"""Conservative historical attribution decisions and orchestration, without SQL."""
from dataclasses import dataclass
from datetime import datetime, time, timedelta
from zoneinfo import ZoneInfo
from production_analytics.context import build_enlyze_production_order
BERLIN = ZoneInfo("Europe/Berlin")
def reconciliation_window(now: datetime, lookback_days: int = 3):
"""Previous N complete Berlin calendar days, as a half-open interval."""
if now.utcoffset() is None or isinstance(lookback_days, bool) or lookback_days < 1:
raise ValueError("An aware clock and positive lookback-days are required")
end = datetime.combine(now.astimezone(BERLIN).date(), time(), BERLIN)
return end - timedelta(days=lookback_days), end
@dataclass(frozen=True)
class HistoricalRecord:
table: str
identity: tuple
machine_id: str
timestamp: datetime
production_order: str
run_id: str
@dataclass(frozen=True)
class Decision:
record: HistoricalRecord
order: str | None
reason: str
desired_run_id: str | None = None
def decide(record, runs, confirmations, workplace, format_template):
"""Keep physical counter/run identities; never infer boundaries from ERP points."""
candidates = [r for r in runs if r.machine_id == record.machine_id
and r.start.timestamp() <= record.timestamp.timestamp()
and (r.end is None or record.timestamp.timestamp() < r.end.timestamp())]
if len(candidates) != 1 or candidates[0].end is None:
return Decision(record, None, "unresolved: missing or overlapping closed ENLYZE runs")
run = candidates[0]
orders = {build_enlyze_production_order(c.production_order, format_template)
for c in confirmations if c.workplace == workplace and c.is_finished_goods
and run.start.timestamp() < c.timestamp.timestamp() < run.end.timestamp()}
if orders != {run.production_order}:
return Decision(record, None, "unresolved: ERP evidence missing or conflicts with ENLYZE")
return Decision(record, run.production_order,
f"closed ENLYZE run {run.uuid} [{run.start.isoformat()}, "
f"{run.end.isoformat()}) corroborated by ERP order {run.production_order}",
run.uuid)
def reconcile_machine(repository, source, erp, config, template, start, end, dry_run=False):
records = repository.read(config.machine_id, start, end)
runs = source.get_production_runs(config.machine_id)
# Query complete overlapping runs so partial-window evidence cannot conceal conflicts.
relevant = [r for r in runs if r.end is not None
and r.start.timestamp() < end.timestamp() and r.end.timestamp() > start.timestamp()]
evidence_start = min([start, *(r.start for r in relevant)], key=datetime.timestamp)
evidence_end = max([end, *(r.end for r in relevant)], key=datetime.timestamp)
confirmations = erp.get_confirmations(
workplace=config.erp_workplace, start=evidence_start, end=evidence_end,
)
decisions = [decide(r, runs, confirmations, config.erp_workplace, template) for r in records]
# Require complete, unambiguous evidence, allowing orders within a physical run.
decisions = repository.guard_runs(decisions)
applied = repository.apply(decisions) if not dry_run else 0
return decisions, applied
def grouped_counts(decisions):
"""Count physical identities and contiguous attribution segments, not snapshot rows."""
groups = {}
for d in decisions:
r = d.record
key = (r.table, r.machine_id, r.identity[0], r.run_id)
groups.setdefault(key, []).append(d)
proposed_runs = unresolved_runs = corrected_segments = unresolved_segments = 0
for peers in groups.values():
proposed_runs += any(d.order is not None and d.order != d.record.production_order
for d in peers)
unresolved_runs += any(d.order is None for d in peers)
streams = {}
for d in peers:
streams.setdefault(d.record.identity[3:], []).append(d)
for stream in streams.values():
previous = object()
for d in sorted(stream, key=lambda d: d.record.timestamp.timestamp()):
state = (d.order, d.order is not None and d.order != d.record.production_order)
if state != previous:
unresolved_segments += d.order is None
corrected_segments += state[1]
previous = state
return (len(groups), proposed_runs, corrected_segments, unresolved_runs, unresolved_segments)
@@ -0,0 +1,116 @@
"""Nightly reconciliation composition and operator output."""
from datetime import datetime
import yaml
from production_analytics.context import build_enlyze_production_order
from production_analytics.enlyze.exploration import ExplorationClient, ExplorationSettings
from production_analytics.enlyze.gateway import EnlyzeApiGateway
from production_analytics.erp import ErpProductionConfirmationGateway, ErpSettings
from production_analytics.service.historical_reconcile import (
BERLIN,
grouped_counts,
reconcile_machine,
reconciliation_window,
)
from production_analytics.service.postgres_historical_reconcile import PostgresHistoricalRepository
from production_analytics.service.postgres_material import PostgresSettings
from production_analytics.service.shift_report_config import (
_StrictLoader,
load_shift_report_machines,
)
def _summarize_decisions(name, decisions, dry_run, verbose):
"""Print run and source stream summaries from existing decisions."""
corrections = {}
unresolved = {}
for decision in decisions:
record = decision.record
if decision.order is None:
if verbose:
print(f"Unresolved {name} {record.identity}: {decision.reason}")
# Keep distinct physical runs and source streams separate, even when
# they share the same unresolved reason.
key = (decision.reason, record.table, record.identity[0], record.run_id,
record.identity[3:])
groups = unresolved
elif decision.order != record.production_order:
if verbose:
print(f"{'Proposed' if dry_run else 'Corrected'} {name} "
f"{record.table} {record.identity}: "
f"{record.production_order} -> {decision.order}; {decision.reason}")
prefix = "closed ENLYZE run "
run_uuid = (decision.reason[len(prefix):].split(" [", 1)[0]
if decision.reason.startswith(prefix) else "unknown")
key = (record.production_order, decision.order, run_uuid)
groups = corrections
else:
continue
if key not in groups:
groups[key] = [0, record.timestamp, record.timestamp]
group = groups[key]
group[0] += 1
group[1] = min(group[1], record.timestamp)
group[2] = max(group[2], record.timestamp)
action = "proposed" if dry_run else "corrected"
for (old, new, run_uuid), (count, _first, _last) in corrections.items():
print(f"{name} | {action}: {old} -> {new} | ENLYZE run {run_uuid} | "
f"{count} records")
for (reason, table, calculation, run_id, stream), (count, first, last) in unresolved.items():
source = f"{table}/{calculation}"
if stream:
source += "/" + "/".join(map(str, stream))
print(f"{name} | {reason} | physical run {run_id} | source {source} | "
f"{count} records | {first.isoformat()} -> {last.isoformat()}")
def run(args, environment):
start, end = reconciliation_window(datetime.now(BERLIN), args.lookback_days)
machines = {name: config for name, config in load_shift_report_machines(args.config).items()
if config.capabilities.material}
with args.order_formats.open(encoding="utf-8") as stream:
formats = yaml.load(stream, Loader=_StrictLoader)
if not isinstance(formats, dict) or set(formats) != set(machines):
raise ValueError("Order formats must map every material machine name exactly once")
for template in formats.values():
if not isinstance(template, str):
raise ValueError("Order formats must be strings")
build_enlyze_production_order("1", template)
repository = PostgresHistoricalRepository(PostgresSettings.from_environment(environment))
source = EnlyzeApiGateway(ExplorationClient(ExplorationSettings.from_environment(environment)))
erp = ErpProductionConfirmationGateway(ErpSettings.from_environment(environment))
print("Historical reconciliation" + (" (DRY RUN)" if args.dry_run else ""))
print(f"Window: {start.isoformat()} to {end.isoformat()} (exclusive)")
grouped = [0] * 5
inspected = corrections = unresolved = unchanged = failures = 0
for name, config in machines.items():
try:
decisions, applied = reconcile_machine(
repository, source, erp, config, formats[name], start, end, args.dry_run,
)
grouped = [a + b for a, b in zip(grouped, grouped_counts(decisions))]
inspected += len(decisions)
proposed = 0
for d in decisions:
if d.order is None:
unresolved += 1
elif d.order == d.record.production_order:
unchanged += 1
else:
proposed += 1
_summarize_decisions(name, decisions, args.dry_run, getattr(args, "verbose", False))
corrections += proposed if args.dry_run else applied
except Exception as exc:
failures += 1
print(f"FAILED {name}: {type(exc).__name__}: {exc}; machine transaction rolled back")
print(f"Machines checked: {len(machines)}\nRecords inspected: {inspected}")
print(f"Corrections {'proposed' if args.dry_run else 'applied'}: {corrections}")
print(f"Ambiguous/unresolved: {unresolved}\nUnchanged: {unchanged}\nFailures: {failures}")
print(f"Physical runs inspected: {grouped[0]}\nRuns with proposed corrections: {grouped[1]}")
label = "proposed" if args.dry_run else "corrected"
print(f"Order segments {label}: {grouped[2]}")
print(f"Unresolved runs: {grouped[3]}\nUnresolved segments: {grouped[4]}")
return 1 if failures else 0
@@ -1,18 +1,45 @@
"""ERP nominal-width resolution for an explicitly matched production order."""
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.erp import ErpWorkplaceStatusGateway
from production_analytics.erp import ErpReadError, ErpWorkplaceStatusGateway
logger = logging.getLogger(__name__)
class ErpNominalWidthProvider:
def __init__(
self, gateway: ErpWorkplaceStatusGateway, *, workplace: str, format_template: str,
fallback_nominal_width_m: float | None = None,
) -> None:
self.gateway = gateway
self.workplace = workplace
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:
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)
if (status is None
or status.workplace.strip().casefold() != self.workplace.strip().casefold()
@@ -86,6 +86,7 @@ def build_material_runner(
ErpWorkplaceStatusGateway(ErpSettings.from_secret_file(erp_secrets_file)),
workplace=calculation.erp_workplace,
format_template=calculation.production_order_format,
fallback_nominal_width_m=calculation.fallback_nominal_width_m,
),
)
if calculation.source_mode == "linear_signal_discharge":
@@ -1,9 +1,19 @@
"""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
@@ -21,6 +31,31 @@ class PostgresDowntimeRepository:
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(
@@ -0,0 +1,139 @@
"""Transactional attribution-only updates with an atomic audit trail."""
from contextlib import nullcontext
from dataclasses import replace
import psycopg
from psycopg import sql
from psycopg.types.json import Jsonb
from production_analytics.service.historical_reconcile import HistoricalRecord
TABLES = {
"material_consumption_snapshots": ("calculation_id", "machine_id", "timestamp"),
"material_application_snapshots": ("calculation_id", "machine_id", "timestamp"),
"channel_material_consumption_snapshots": (
"calculation_id", "machine_id", "timestamp", "extruder", "doser_channel",
),
}
class PostgresHistoricalRepository:
def __init__(self, settings):
self.settings = settings
def connect(self):
s = self.settings
return psycopg.connect(host=s.host, port=s.port, dbname=s.dbname, user=s.user,
password=s.password, connect_timeout=10,
options="-c statement_timeout=30000")
def read(self, machine_id, start, end):
result = []
with self.connect() as connection:
for table, keys in TABLES.items():
rows = connection.execute(sql.SQL(
"SELECT {}, production_order, run_id FROM {} "
"WHERE machine_id = %s AND timestamp >= %s AND timestamp < %s"
).format(sql.SQL(', ').join(map(sql.Identifier, keys)), sql.Identifier(table)),
(machine_id, start, end)).fetchall()
result.extend(HistoricalRecord(table, tuple(row[:-2]), machine_id, row[2],
row[-2], row[-1]) for row in rows)
return result
def guard_runs(self, decisions, connection=None):
"""Reject partial run repairs, including historical rows outside the window."""
groups = {}
for d in decisions:
r = d.record
groups.setdefault((r.table, r.machine_id, r.identity[0], r.run_id), []).append(d)
blocked = set()
context = self.connect() if connection is None else nullcontext(connection)
with context as connection:
for key, peers in groups.items():
corrections = [d for d in peers if d.order is not None
and d.order != d.record.production_order]
if not corrections:
continue
table, machine, calculation, run = key
count = connection.execute(sql.SQL(
"SELECT count(*) FROM {} WHERE machine_id = %s "
"AND calculation_id = %s AND run_id = %s"
).format(sql.Identifier(table)), (machine, calculation, run)).fetchone()[0]
if count != len(peers) or any(d.order is None for d in peers):
blocked.add(key)
return [replace(d, order=None,
reason="unresolved: partial or unresolved cumulative run")
if (d.record.table, d.record.machine_id, d.record.identity[0],
d.record.run_id) in blocked else d for d in decisions]
def apply(self, decisions):
count = 0
with self.connect() as connection:
# Serialize this job; concurrent changes fail rather than silently overwrite.
connection.execute("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE")
connection.execute("SELECT pg_advisory_xact_lock(704301)")
if self.guard_runs(decisions, connection) != decisions:
raise RuntimeError("Historical run changed concurrently; retry reconciliation")
for d in decisions:
r = d.record
if d.order is None or d.order == r.production_order:
continue
keys = TABLES[r.table]
predicate = sql.SQL(' AND ').join(
sql.SQL('{} = %s').format(sql.Identifier(k)) for k in keys)
action = "updated"
retained_run_id = None
if r.table == "material_application_snapshots":
source = connection.execute(sql.SQL(
"SELECT application_g_m2 FROM {} WHERE {} "
"AND production_order = %s AND run_id = %s FOR UPDATE"
).format(sql.Identifier(r.table), predicate),
(*r.identity, r.production_order, r.run_id)).fetchone()
if source is None:
raise RuntimeError(
"Historical record changed concurrently; retry reconciliation"
)
target = connection.execute(
"""SELECT run_id, application_g_m2 IS NOT DISTINCT FROM %s
FROM material_application_snapshots
WHERE calculation_id = %s AND machine_id = %s
AND timestamp = %s AND production_order = %s FOR UPDATE""",
(source[0], *r.identity, d.order)).fetchone()
if target is not None:
if (not target[1] or d.desired_run_id is None
or target[0] != d.desired_run_id):
raise RuntimeError(
"Historical application collision has conflicting measurement "
"or unexpected target run; machine transaction rolled back"
)
deleted = connection.execute(sql.SQL(
"DELETE FROM {} WHERE {} AND production_order = %s "
"AND run_id = %s RETURNING timestamp"
).format(sql.Identifier(r.table), predicate),
(*r.identity, r.production_order, r.run_id)).fetchone()
if deleted is None:
raise RuntimeError(
"Historical record changed concurrently; retry reconciliation"
)
action = "deduplicated"
retained_run_id = target[0]
if action == "updated":
changed = connection.execute(sql.SQL(
"UPDATE {} SET production_order = %s WHERE {} "
"AND production_order = %s AND run_id = %s RETURNING timestamp"
).format(sql.Identifier(r.table), predicate),
(d.order, *r.identity, r.production_order, r.run_id)).fetchone()
if changed is None:
raise RuntimeError(
"Historical record changed concurrently; retry reconciliation"
)
connection.execute(
"""INSERT INTO historical_assignment_audit
(machine_id, source_table, record_identity, previous_order, new_order,
run_id, reason, action, retained_run_id)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)""",
(r.machine_id, r.table, Jsonb(dict(zip(keys, map(str, r.identity)))),
r.production_order, d.order, r.run_id, d.reason, action, retained_run_id))
count += 1
return count
@@ -0,0 +1,136 @@
"""Read-only baseline plus bounded-window queries for shift material deltas.
One valid baseline per calculation/channel, followed by every raw in-window
row. Missing baselines leave window rows intact for aggregation's fallback.
"""
from datetime import datetime
from production_analytics.calculations.shift_material import (
ShiftChannelMaterialSnapshot,
ShiftMaterialSnapshot,
validate_material_window,
)
from production_analytics.service.postgres_material import PostgresSettings
class ShiftMaterialReadError(RuntimeError):
"""Safe operator-facing cumulative snapshot read/result error."""
# A backward index scan per requested calculation stops at its first valid
# baseline. The other branch reads only the bounded shift, without filtering
# counters (invalid samples can mark run transitions).
_MATERIAL_SQL = """WITH request AS (
SELECT %s::text AS machine_id, %s::text[] AS calculation_ids,
%s::timestamptz AS start_time, %s::timestamptz AS end_time
), baseline AS (
SELECT sample.*
FROM request r
CROSS JOIN LATERAL unnest(r.calculation_ids) AS ids(calculation_id)
CROSS JOIN LATERAL (
SELECT timestamp, calculation_id, machine_id, production_order, run_id, consumption_kg
FROM material_consumption_snapshots
WHERE calculation_id = ids.calculation_id AND machine_id = r.machine_id
AND timestamp <= r.start_time
AND consumption_kg >= 0 AND consumption_kg < 'Infinity'::double precision
ORDER BY timestamp DESC, run_id, production_order
LIMIT 1
) sample
)
SELECT * FROM baseline
UNION ALL
SELECT timestamp, s.calculation_id, s.machine_id, production_order, run_id, consumption_kg
FROM material_consumption_snapshots s CROSS JOIN request r
WHERE s.machine_id = r.machine_id AND s.calculation_id = ANY(r.calculation_ids)
AND timestamp > r.start_time AND timestamp < r.end_time
ORDER BY calculation_id, timestamp, run_id, production_order"""
# The channel index has production_order between channel and timestamp, so it
# cannot directly support a backward timestamp seek per channel. DISTINCT ON
# selects all channel baselines in one filtered pass rather than rescanning
# pre-shift history separately for every channel. See the performance notes.
_CHANNEL_SQL = """WITH request AS (
SELECT %s::text AS machine_id, %s::text[] AS calculation_ids,
%s::timestamptz AS start_time, %s::timestamptz AS end_time
), baseline AS (
SELECT DISTINCT ON (s.calculation_id, extruder, doser_channel)
timestamp, s.calculation_id, s.machine_id, extruder, doser_channel,
production_order, run_id, cumulative_consumption_kg, material_number,
material_name, material_mapping_status, percentage_sum_valid
FROM channel_material_consumption_snapshots s CROSS JOIN request r
WHERE s.machine_id = r.machine_id AND s.calculation_id = ANY(r.calculation_ids)
AND timestamp <= r.start_time
AND cumulative_consumption_kg >= 0
AND cumulative_consumption_kg < 'Infinity'::double precision
ORDER BY s.calculation_id, extruder, doser_channel, timestamp DESC, run_id, production_order
)
SELECT * FROM baseline
UNION ALL
SELECT timestamp, s.calculation_id, s.machine_id, extruder, doser_channel,
production_order, run_id, cumulative_consumption_kg, material_number,
material_name, material_mapping_status, percentage_sum_valid
FROM channel_material_consumption_snapshots s CROSS JOIN request r
WHERE s.machine_id = r.machine_id AND s.calculation_id = ANY(r.calculation_ids)
AND timestamp > r.start_time AND timestamp < r.end_time
ORDER BY calculation_id, extruder, doser_channel, timestamp, run_id, production_order"""
class PostgresShiftMaterialRepository:
def __init__(self, settings: PostgresSettings) -> None:
self.settings = settings
def get_snapshots(
self, *, machine_id: str, calculation_ids: tuple[str, ...], start: datetime, end: datetime
) -> list[ShiftMaterialSnapshot]:
validate_material_window(
machine_id=machine_id, calculation_ids=calculation_ids, start=start, end=end
)
rows = _read(
self.settings, _MATERIAL_SQL, (machine_id, list(calculation_ids), start, end)
)
try:
return [ShiftMaterialSnapshot(*row) for row in rows]
except Exception:
raise ShiftMaterialReadError(
"PostgreSQL shift material returned an invalid row"
) from None
class PostgresShiftChannelMaterialRepository:
def __init__(self, settings: PostgresSettings) -> None:
self.settings = settings
def get_snapshots(
self, *, machine_id: str, calculation_ids: tuple[str, ...], start: datetime, end: datetime
) -> list[ShiftChannelMaterialSnapshot]:
validate_material_window(
machine_id=machine_id, calculation_ids=calculation_ids, start=start, end=end
)
rows = _read(
self.settings, _CHANNEL_SQL, (machine_id, list(calculation_ids), start, end)
)
try:
return [ShiftChannelMaterialSnapshot(*row) for row in rows]
except Exception:
raise ShiftMaterialReadError(
"PostgreSQL shift material returned an invalid row"
) from None
def _read(settings: PostgresSettings, sql: str, parameters: tuple) -> list[tuple]:
import psycopg
try:
with psycopg.connect(
host=settings.host,
port=settings.port,
dbname=settings.dbname,
user=settings.user,
password=settings.password,
connect_timeout=10,
options="-c statement_timeout=10000",
) as connection:
return connection.execute(sql, parameters).fetchall()
except Exception:
raise ShiftMaterialReadError("PostgreSQL shift material read failed") from None
@@ -0,0 +1,326 @@
"""Order-oriented view of positive ERP production confirmations."""
from collections import defaultdict
from collections.abc import Mapping
from dataclasses import dataclass, replace
from datetime import UTC, date, datetime
from math import fsum
from typing import Literal, Protocol
from zoneinfo import ZoneInfo
from production_analytics.calculations.shift_material import ShiftMaterialSummary
from production_analytics.calculations.shift_report import shift_containing
from production_analytics.enlyze.exploration import ExplorationError
from production_analytics.erp.gateway import (
ErpReadError,
OrderConfirmationGroup,
OrderConfirmationRow,
ProductionConfirmation,
)
from production_analytics.service.postgres_shift_material import ShiftMaterialReadError
from production_analytics.service.shift_material import (
ShiftChannelMaterialService,
ShiftMaterialService,
)
from production_analytics.service.shift_report_config import ShiftReportMachineConfig
from production_analytics.service.shift_speed import ShiftSpeedService
class ProductionOrderReader(Protocol):
def search_orders(self, query: str, *, limit: int = 25) -> list[OrderConfirmationGroup]: ...
def get_order_confirmations(self, production_order: str) -> list[OrderConfirmationRow]: ...
def get_confirmations(self, *, workplace: str, start: datetime, end: datetime,
timezone: ZoneInfo) -> list[ProductionConfirmation]: ...
class MaterialAllocator(Protocol):
def allocate(self, measured: ShiftMaterialSummary) -> ShiftMaterialSummary: ...
def totals_by_order(self, allocated: ShiftMaterialSummary) -> dict[str, float]: ...
@dataclass(frozen=True, slots=True)
class ProductionOrderPlacement:
workplace: str
machine_name: str | None
site: str | None
timezone: ZoneInfo | None
article_number: str | None
article_description: str | None
first_confirmation_local: datetime
last_confirmation_local: datetime
mapping_status: Literal["configured", "unknown", "ambiguous"]
@dataclass(frozen=True, slots=True)
class ProductionOrderSearchResult:
production_order: str
placements: tuple[ProductionOrderPlacement, ...]
@dataclass(frozen=True, slots=True)
class ProductionOrderSegment:
start: datetime
end: datetime
@dataclass(frozen=True, slots=True)
class ProductionOrderShiftKpi:
segments: tuple[ProductionOrderSegment, ...]
average_speed_m_min: float | None
material_consumption_kg: float | None
@dataclass(frozen=True, slots=True)
class ProductionOrderShift:
production_order: str
machine_name: str
workplace: str
site: str
timezone: ZoneInfo
date: date
shift: Literal["early", "late", "night"]
shift_start: datetime
shift_end: datetime
first_confirmation: datetime
last_confirmation: datetime
produced_m2: float
segments: tuple[ProductionOrderSegment, ...] = ()
average_speed_m_min: float | None = None
material_consumption_kg: float | None = None
@dataclass(frozen=True, slots=True)
class ProductionOrderDetail:
production_order: str
placements: tuple[ProductionOrderPlacement, ...]
shifts: tuple[ProductionOrderShift, ...]
class ProductionOrderService:
"""Resolve workplace and site timezone before assigning confirmation timestamps."""
def __init__(self, gateway: ProductionOrderReader,
machines: Mapping[str, ShiftReportMachineConfig], *,
speed: ShiftSpeedService | None = None,
materials: ShiftMaterialService | None = None,
channel_materials: ShiftChannelMaterialService | None = None,
material_allocators: Mapping[str, MaterialAllocator] | None = None) -> None:
self.gateway = gateway
self.speed = speed
self.materials = materials
self.channel_materials = channel_materials
self.material_allocators = dict(material_allocators or {})
self.machines = dict(machines)
workplace_map = defaultdict(list)
for name, config in machines.items():
workplace_map[config.erp_workplace].append((name, config))
self._workplaces = dict(workplace_map)
def _machine(self, workplace: str):
matches = self._workplaces.get(workplace, ())
return matches[0] if len(matches) == 1 else None
def _placement(self, workplace: str, article_number: str | None,
article_description: str | None, first: datetime,
last: datetime) -> ProductionOrderPlacement:
resolved = self._machine(workplace)
status = ("ambiguous" if len(self._workplaces.get(workplace, ())) > 1 else "unknown")
return ProductionOrderPlacement(
workplace=workplace, machine_name=resolved[0] if resolved else None,
site=resolved[1].site if resolved else None,
timezone=resolved[1].timezone if resolved else None,
article_number=article_number, article_description=article_description,
first_confirmation_local=first, last_confirmation_local=last,
mapping_status="configured" if resolved else status,
)
def search(self, query: str, *, limit: int = 25) -> tuple[ProductionOrderSearchResult, ...]:
query = _order_input(query)
if type(limit) is not int or not 1 <= limit <= 100:
raise ValueError("limit must be between 1 and 100")
groups = self.gateway.search_orders(query, limit=limit)
by_order = defaultdict(list)
for group in groups:
by_order[group.production_order].append(self._placement(
group.workplace, group.article_number, group.article_description,
group.first_confirmation_local, group.last_confirmation_local))
orders = sorted(by_order, key=lambda order: (order != query, order))[:limit]
return tuple(ProductionOrderSearchResult(
order, tuple(sorted(by_order[order], key=lambda placement: (
placement.workplace, placement.article_number or "",
placement.article_description or "")))) for order in orders)
def detail(self, production_order: str) -> ProductionOrderDetail | None:
order = _order_input(production_order)
rows = self.gateway.get_order_confirmations(order)
if not rows:
return None
placements = defaultdict(list)
shifts = defaultdict(list)
for row in rows:
if row.production_order != order:
raise ValueError("ERP returned a different production order")
placements[(row.workplace, row.article_number,
row.article_description)].append(row)
resolved = self._machine(row.workplace)
if resolved is None:
continue
name, config = resolved
timestamp = row.timestamp_local.replace(tzinfo=config.timezone, fold=0)
day, shift, start, end = shift_containing(timestamp, config.timezone)
shifts[(name, day, shift, start, end)].append(row)
place_models = tuple(self._placement(workplace, article, description,
min(row.timestamp_local for row in grouped),
max(row.timestamp_local for row in grouped))
for (workplace, article, description), grouped in sorted(
placements.items(), key=lambda item: tuple(
value or "" for value in item[0])))
shift_models = []
for (name, day, shift, start, end), grouped in shifts.items():
config = self._machine(grouped[0].workplace)[1]
stamps = [row.timestamp_local.replace(tzinfo=config.timezone, fold=0)
for row in grouped]
shift_models.append(ProductionOrderShift(
production_order=order, machine_name=name, workplace=config.erp_workplace,
site=config.site, timezone=config.timezone, date=day, shift=shift,
shift_start=start, shift_end=end,
first_confirmation=min(stamps, key=lambda value: value.astimezone(UTC)),
last_confirmation=max(stamps, key=lambda value: value.astimezone(UTC)),
produced_m2=fsum(row.feedback_quantity_m2 for row in grouped),
))
shift_models.sort(key=lambda item: (item.shift_start.astimezone(UTC),
item.machine_name))
enriched = []
for item in shift_models:
kpi = self.for_shift(machine_name=item.machine_name, start=item.shift_start,
end=item.shift_end, orders=(item.production_order,))[
item.production_order]
enriched.append(replace(item, segments=kpi.segments,
average_speed_m_min=kpi.average_speed_m_min,
material_consumption_kg=kpi.material_consumption_kg))
return ProductionOrderDetail(order, place_models, tuple(enriched))
def for_shift(self, *, machine_name: str, start: datetime, end: datetime,
orders: tuple[str, ...],
allocated_shift_materials: ShiftMaterialSummary | None = None,
) -> dict[str, ProductionOrderShiftKpi]:
"""Attribute one machine shift to all requested FAs with shared segmentation."""
if machine_name not in self.machines:
raise ValueError("Unknown machine")
if not orders:
return {}
config = self.machines[machine_name]
confirmations = self.gateway.get_confirmations(
workplace=config.erp_workplace, start=start, end=end, timezone=config.timezone)
by_order = _segments_by_order(
confirmations, workplace=config.erp_workplace, timezone=config.timezone,
start=start, end=end)
allocator = self.material_allocators.get(machine_name)
allocated_totals = None
if allocator is not None and config.material is not None:
try:
if allocated_shift_materials is None:
service = (self.channel_materials if config.material.mode == "channel"
else self.materials)
if service is not None:
measured = service.summarize(
machine_id=config.machine_id,
calculation_ids=config.material.calculation_ids,
start=start, end=end,
)
allocated_shift_materials = allocator.allocate(measured)
if allocated_shift_materials is not None:
allocated_totals = allocator.totals_by_order(allocated_shift_materials)
except (ShiftMaterialReadError, ErpReadError):
allocated_totals = None
result = {}
for order in dict.fromkeys(orders):
segments = by_order.get(order, ())
if allocator is not None:
material = allocated_totals.get(order) if allocated_totals is not None else None
elif segments:
material = self._material_for_segments(config, segments)
else:
material = None
result[order] = ProductionOrderShiftKpi(
segments=segments,
average_speed_m_min=self._speed_for_segments(config, segments) if segments
else None,
material_consumption_kg=material,
)
return result
def _speed_for_segments(self, config: ShiftReportMachineConfig,
segments: tuple[ProductionOrderSegment, ...]) -> float | None:
if config.speed is None or self.speed is None:
return None
try:
summaries = [self.speed.summarize(config=config.speed, start=part.start,
end=part.end) for part in segments]
except ExplorationError:
return None
count = sum(summary.active_sample_count for summary in summaries)
if count == 0:
return None
return fsum(summary.average_line_speed_m_min * (summary.active_sample_count / count)
for summary in summaries if summary.active_sample_count)
def _material_for_segments(self, config: ShiftReportMachineConfig,
segments: tuple[ProductionOrderSegment, ...]) -> float | None:
if config.material is None:
return None
service = (self.channel_materials if config.material.mode == "channel"
else self.materials)
if service is None:
return None
try:
measured = [service.summarize(
machine_id=config.machine_id,
calculation_ids=config.material.calculation_ids,
start=part.start, end=part.end,
) for part in segments]
except (ShiftMaterialReadError, ErpReadError):
return None
return fsum(summary.total_consumption_kg for summary in measured)
def _segments_by_order(
confirmations: list[ProductionConfirmation], *, workplace: str, timezone: ZoneInfo,
start: datetime, end: datetime,
) -> dict[str, tuple[ProductionOrderSegment, ...]]:
"""Partition one shift at midpoints between adjacent FA confirmation runs."""
first = start.astimezone(UTC)
last = end.astimezone(UTC)
ordered = sorted(
((row.timestamp.astimezone(UTC), row.production_order) for row in confirmations
if row.workplace == workplace and row.is_finished_goods
and first <= row.timestamp.astimezone(UTC) < last),
key=lambda entry: (entry[0], entry[1]),
)
if not ordered:
return {}
runs = []
for stamp, order in ordered:
if not runs or runs[-1][0] != order:
runs.append([order, stamp, stamp])
else:
runs[-1][2] = stamp
boundaries = [first]
for before, after in zip(runs, runs[1:]):
midpoint = before[2] + (after[1] - before[2]) / 2
boundaries.append(max(first, min(midpoint, last)))
boundaries.append(last)
by_order = defaultdict(list)
for index, run in enumerate(runs):
if boundaries[index] < boundaries[index + 1]:
by_order[run[0]].append(ProductionOrderSegment(
boundaries[index].astimezone(timezone),
boundaries[index + 1].astimezone(timezone)))
return {order: tuple(segments) for order, segments in by_order.items()}
def _order_input(value: str) -> str:
if (not isinstance(value, str) or not value.strip() or "\x00" in value
or len(value.strip()) > 80):
raise ValueError("production order must be 1–80 non-NUL characters")
return value.strip()
@@ -0,0 +1,27 @@
"""Compose persisted source downtime reads with pure shift aggregation."""
from datetime import datetime
from typing import Protocol
from production_analytics.calculations.shift_downtime import (
ShiftDowntimeEvent,
ShiftDowntimeSummary,
aggregate_shift_downtime,
validate_downtime_window,
)
class ShiftDowntimeReader(Protocol):
def get_events(
self, *, machine_id: str, start: datetime, end: datetime
) -> list[ShiftDowntimeEvent]: ...
class ShiftDowntimeService:
def __init__(self, repository: ShiftDowntimeReader) -> None:
self.repository = repository
def summarize(self, *, machine_id: str, start: datetime, end: datetime) -> ShiftDowntimeSummary:
validate_downtime_window(machine_id=machine_id, start=start, end=end)
events = self.repository.get_events(machine_id=machine_id, start=start, end=end)
return aggregate_shift_downtime(events, machine_id=machine_id, start=start, end=end)
@@ -0,0 +1,83 @@
"""Thin services composing explicit snapshot sources with pure shift aggregation."""
from datetime import datetime
from typing import Protocol
from production_analytics.calculations.shift_material import (
ShiftChannelMaterialSnapshot,
ShiftMaterialSnapshot,
ShiftMaterialSummary,
aggregate_shift_channel_material,
aggregate_shift_material,
validate_material_window,
)
class ShiftMaterialReader(Protocol):
def get_snapshots(
self, *, machine_id: str, calculation_ids: tuple[str, ...], start: datetime, end: datetime
) -> list[ShiftMaterialSnapshot]: ...
class ShiftChannelMaterialReader(Protocol):
def get_snapshots(
self, *, machine_id: str, calculation_ids: tuple[str, ...], start: datetime, end: datetime
) -> list[ShiftChannelMaterialSnapshot]: ...
class ShiftMaterialService:
def __init__(self, repository: ShiftMaterialReader) -> None:
self.repository = repository
def summarize(
self,
*,
machine_id: str,
calculation_ids: tuple[str, ...],
start: datetime,
end: datetime,
include_zero: bool = True,
) -> ShiftMaterialSummary:
validate_material_window(
machine_id=machine_id, calculation_ids=calculation_ids, start=start, end=end
)
snapshots = self.repository.get_snapshots(
machine_id=machine_id, calculation_ids=calculation_ids, start=start, end=end
)
return aggregate_shift_material(
snapshots,
machine_id=machine_id,
calculation_ids=calculation_ids,
start=start,
end=end,
include_zero=include_zero,
)
class ShiftChannelMaterialService:
def __init__(self, repository: ShiftChannelMaterialReader) -> None:
self.repository = repository
def summarize(
self,
*,
machine_id: str,
calculation_ids: tuple[str, ...],
start: datetime,
end: datetime,
include_zero: bool = True,
) -> ShiftMaterialSummary:
validate_material_window(
machine_id=machine_id, calculation_ids=calculation_ids, start=start, end=end
)
snapshots = self.repository.get_snapshots(
machine_id=machine_id, calculation_ids=calculation_ids, start=start, end=end
)
return aggregate_shift_channel_material(
snapshots,
machine_id=machine_id,
calculation_ids=calculation_ids,
start=start,
end=end,
include_zero=include_zero,
)
@@ -0,0 +1,35 @@
"""Compose historical ERP reads with pure shift-production aggregation."""
from datetime import datetime
from typing import Protocol
from zoneinfo import ZoneInfo
from production_analytics.calculations.shift_production import (
ShiftProductionSummary,
aggregate_shift_production,
validate_shift_window,
)
from production_analytics.erp import ProductionConfirmation
class ProductionConfirmationReader(Protocol):
def get_confirmations(
self, *, workplace: str, start: datetime, end: datetime,
timezone: ZoneInfo | None = None,
) -> list[ProductionConfirmation]: ...
class ShiftProductionService:
def __init__(self, gateway: ProductionConfirmationReader) -> None:
self.gateway = gateway
def summarize(
self, *, workplace: str, start: datetime, end: datetime,
timezone: ZoneInfo | None = None,
) -> ShiftProductionSummary:
workplace = validate_shift_window(workplace=workplace, start=start, end=end)
kwargs = {"workplace": workplace, "start": start, "end": end}
if timezone is not None:
kwargs["timezone"] = timezone
confirmations = self.gateway.get_confirmations(**kwargs)
return aggregate_shift_production(confirmations, workplace=workplace, start=start, end=end)
@@ -0,0 +1,104 @@
"""Sequential composition of validated services; mandatory failures propagate."""
from collections.abc import Mapping
from dataclasses import replace
from datetime import datetime
from types import MappingProxyType
from typing import Protocol
from production_analytics.calculations.shift_material import ShiftMaterialSummary
from production_analytics.calculations.shift_report import ShiftReport
from production_analytics.calculations.shift_speed import validate_speed_window
from production_analytics.service.production_order import ProductionOrderService
from production_analytics.service.shift_downtime import ShiftDowntimeService
from production_analytics.service.shift_material import (
ShiftChannelMaterialService,
ShiftMaterialService,
)
from production_analytics.service.shift_production import ShiftProductionService
from production_analytics.service.shift_report_config import ShiftReportMachineConfig
from production_analytics.service.shift_speed import ShiftSpeedService
class ShiftMaterialAllocator(Protocol):
def allocate(self, measured: ShiftMaterialSummary) -> ShiftMaterialSummary: ...
class ShiftReportService:
def __init__(
self,
*,
machines: Mapping[str, ShiftReportMachineConfig],
production: ShiftProductionService,
downtime: ShiftDowntimeService,
materials: ShiftMaterialService,
channel_materials: ShiftChannelMaterialService,
speed: ShiftSpeedService,
material_allocators: Mapping[str, ShiftMaterialAllocator] | None = None,
order_kpis: ProductionOrderService | None = None,
) -> None:
self.machines = MappingProxyType(dict(machines))
self.production = production
self.downtime = downtime
self.materials = materials
self.channel_materials = channel_materials
self.speed = speed
self.material_allocators = MappingProxyType(dict(material_allocators or {}))
self.order_kpis = order_kpis
def build(self, *, machine_name: str, start: datetime, end: datetime) -> ShiftReport:
validate_speed_window(start, end)
if not isinstance(machine_name, str) or machine_name not in self.machines:
raise ValueError("Unknown shift-report machine")
config = self.machines[machine_name]
start, end = start.astimezone(config.timezone), end.astimezone(config.timezone)
production = self.production.summarize(
workplace=config.erp_workplace,
start=start,
end=end,
timezone=config.timezone,
) if config.capabilities.production else None
downtime = (self.downtime.summarize(machine_id=config.machine_id, start=start, end=end)
if config.capabilities.downtime else None)
materials = None
if config.material is not None:
material_service = (
self.channel_materials if config.material.mode == "channel" else self.materials
)
materials = material_service.summarize(
machine_id=config.machine_id,
calculation_ids=config.material.calculation_ids,
start=start,
end=end,
)
if machine_name in self.material_allocators:
materials = self.material_allocators[machine_name].allocate(materials)
speed = (self.speed.summarize(config=config.speed, start=start, end=end)
if config.speed is not None else None)
if (production is not None and production.items and self.order_kpis is not None
and (config.speed is not None or config.material is not None)):
kpis = self.order_kpis.for_shift(
machine_name=machine_name, start=start, end=end,
orders=tuple(item.production_order for item in production.items),
allocated_shift_materials=(materials if machine_name in self.material_allocators
else None),
)
production = replace(production, items=tuple(
replace(item,
average_speed_m_min=kpis[item.production_order].average_speed_m_min,
material_consumption_kg=kpis[item.production_order].material_consumption_kg)
for item in production.items
))
return ShiftReport(
machine_name=machine_name,
machine_id=config.machine_id,
display_name=config.display_name,
site=config.site,
timezone=config.timezone,
start=start,
end=end,
production=production,
downtime=downtime,
materials=materials,
speed=speed,
)
@@ -0,0 +1,231 @@
"""Strict, self-contained configuration for shift-report composition."""
from collections.abc import Mapping
from dataclasses import dataclass
from pathlib import Path
from types import MappingProxyType
from typing import Literal
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
import yaml
from production_analytics.calculations.shift_speed import NumericDwellGate, ShiftSpeedConfig
@dataclass(frozen=True, slots=True)
class ShiftReportSiteConfig:
display_name: str
timezone: ZoneInfo
def __post_init__(self) -> None:
_text(self.display_name, "site.display_name")
if not isinstance(self.timezone, ZoneInfo):
raise ValueError("site.timezone must be a valid IANA timezone")
@dataclass(frozen=True, slots=True)
class ShiftReportCapabilities:
production: bool
downtime: bool
material: bool
speed: bool
def __post_init__(self) -> None:
if any(type(value) is not bool for value in (
self.production, self.downtime, self.material, self.speed,
)):
raise ValueError("capabilities must contain booleans")
if not any((self.production, self.downtime, self.material, self.speed)):
raise ValueError("at least one capability must be enabled")
@dataclass(frozen=True, slots=True)
class ShiftReportMaterialConfig:
mode: Literal["cumulative", "channel"]
calculation_ids: tuple[str, ...]
allocation: Literal["none", "erp_fiber_share"] = "none"
def __post_init__(self) -> None:
if self.mode not in ("cumulative", "channel"):
raise ValueError("material.mode must be cumulative or channel")
if self.allocation not in ("none", "erp_fiber_share"):
raise ValueError("material.allocation must be none or erp_fiber_share")
if not isinstance(self.calculation_ids, tuple) or not self.calculation_ids:
raise ValueError("material.calculation_ids must be a non-empty tuple")
for calculation_id in self.calculation_ids:
_text(calculation_id, "material.calculation_ids")
if len(set(self.calculation_ids)) != len(self.calculation_ids):
raise ValueError("material.calculation_ids must be unique")
@dataclass(frozen=True, slots=True)
class ShiftReportMachineConfig:
display_name: str
site: str
machine_id: str | None
erp_workplace: str
capabilities: ShiftReportCapabilities
timezone: ZoneInfo
material: ShiftReportMaterialConfig | None = None
speed: ShiftSpeedConfig | None = None
def __post_init__(self) -> None:
for name in ("display_name", "site", "erp_workplace"):
_text(getattr(self, name), name)
if not isinstance(self.timezone, ZoneInfo):
raise ValueError("machine timezone must be a valid IANA timezone")
if not isinstance(self.capabilities, ShiftReportCapabilities):
raise ValueError("capabilities must be a ShiftReportCapabilities")
if self.machine_id is not None:
_text(self.machine_id, "machine_id")
elif any((self.capabilities.downtime, self.capabilities.material,
self.capabilities.speed)):
raise ValueError("machine_id is required for downtime, material, or speed")
if self.capabilities.material != (self.material is not None):
raise ValueError("material configuration must match material capability")
if self.capabilities.speed != (self.speed is not None):
raise ValueError("speed configuration must match speed capability")
if self.material is not None and not isinstance(self.material, ShiftReportMaterialConfig):
raise ValueError("material must be a ShiftReportMaterialConfig")
if self.speed is not None:
if (not isinstance(self.speed, ShiftSpeedConfig)
or self.speed.machine_id != self.machine_id):
raise ValueError("speed configuration must refer to the report machine")
_text(self.speed.signal, "speed.signal")
@dataclass(frozen=True, slots=True)
class ShiftReportConfig:
sites: Mapping[str, ShiftReportSiteConfig]
machines: Mapping[str, ShiftReportMachineConfig]
def __post_init__(self) -> None:
object.__setattr__(self, "sites", MappingProxyType(dict(self.sites)))
object.__setattr__(self, "machines", MappingProxyType(dict(self.machines)))
class _StrictLoader(yaml.SafeLoader):
"""Reject duplicate YAML keys instead of silently replacing configuration."""
def _mapping(loader, node):
result = {}
for key_node, value_node in node.value:
key = loader.construct_object(key_node)
if not isinstance(key, str) or key in result:
raise ValueError("Configuration mapping keys must be unique strings")
result[key] = loader.construct_object(value_node)
return result
_StrictLoader.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, _mapping)
def _text(value: object, name: str) -> None:
if not isinstance(value, str) or not value.strip() or "\x00" in value:
raise ValueError(f"{name} must be a non-empty string without NUL bytes")
def _fields(value: object, expected: set[str], name: str) -> dict:
if not isinstance(value, dict) or set(value) != expected:
raise ValueError(f"{name} has missing or unknown fields")
return value
def load_shift_report_config(path: str | Path) -> ShiftReportConfig:
try:
with Path(path).open(encoding="utf-8") as stream:
document = yaml.load(stream, Loader=_StrictLoader)
except (OSError, UnicodeError, yaml.YAMLError) as exc:
raise ValueError("Cannot read shift-report machine configuration") from exc
document = _fields(document, {"sites", "machines"}, "Shift-report configuration")
raw_sites = document["sites"]
if not isinstance(raw_sites, dict) or not raw_sites:
raise ValueError("sites must be a non-empty mapping")
sites = {}
for key, entry in raw_sites.items():
_text(key, "site key")
entry = _fields(entry, {"display_name", "timezone"}, f"site {key}")
_text(entry["timezone"], "site.timezone")
try:
timezone = ZoneInfo(entry["timezone"])
except (ZoneInfoNotFoundError, ValueError, TypeError) as exc:
raise ValueError("site.timezone must be a valid IANA timezone") from exc
sites[key] = ShiftReportSiteConfig(entry["display_name"], timezone)
machines = document["machines"]
if not isinstance(machines, dict) or not machines:
raise ValueError("machines must be a non-empty mapping")
result = {}
for name, entry in machines.items():
_text(name, "machine name")
required = {"display_name", "site", "erp_workplace", "capabilities"}
if not isinstance(entry, dict) or not required <= set(entry) or set(entry) - (
required | {"machine_id", "material", "speed"}
):
raise ValueError(f"{name} has missing or unknown fields")
capabilities = _fields(entry["capabilities"],
{"production", "downtime", "material", "speed"},
"capabilities")
capabilities = ShiftReportCapabilities(**capabilities)
_text(entry["site"], "site")
if entry["site"] not in sites:
raise ValueError(f"{name} references an unknown site")
if capabilities.material != ("material" in entry):
raise ValueError("material configuration must match material capability")
if capabilities.speed != ("speed" in entry):
raise ValueError("speed configuration must match speed capability")
material = None
if capabilities.material:
material_entry = entry["material"]
if not isinstance(material_entry, dict) or not {"mode", "calculation_ids"} <= set(
material_entry
) or set(material_entry) - {"mode", "calculation_ids", "allocation"}:
raise ValueError("material has missing or unknown fields")
ids = material_entry["calculation_ids"]
if not isinstance(ids, list):
raise ValueError("material.calculation_ids must be a list")
material = ShiftReportMaterialConfig(
material_entry["mode"], tuple(ids), material_entry.get("allocation", "none")
)
speed = None
if capabilities.speed:
speed_entry = entry["speed"]
required_speed = {"signal_ref", "signal", "unit"}
optional_speed = {"production_gate_m_min", "running_signal_ref", "running_when",
"numeric_dwell_gate"}
if (not isinstance(speed_entry, dict) or not required_speed <= set(speed_entry)
or set(speed_entry) - (required_speed | optional_speed)):
raise ValueError("speed has missing or unknown fields")
if "running_when" in speed_entry and not speed_entry.get("running_signal_ref"):
raise ValueError("speed.running_when requires running_signal_ref")
dwell = None
if "numeric_dwell_gate" in speed_entry:
dwell_entry = _fields(
speed_entry["numeric_dwell_gate"],
{"signal_ref", "threshold", "comparison", "minimum_duration_seconds"},
"numeric_dwell_gate",
)
dwell = NumericDwellGate(**dwell_entry)
speed = ShiftSpeedConfig(
machine_id=entry.get("machine_id"), speed_signal_ref=speed_entry["signal_ref"],
signal=speed_entry["signal"], unit=speed_entry["unit"],
production_gate_m_min=speed_entry.get("production_gate_m_min"),
running_signal_ref=speed_entry.get("running_signal_ref"),
running_when=speed_entry.get("running_when", True),
numeric_dwell_gate=dwell,
)
result[name] = ShiftReportMachineConfig(
display_name=entry["display_name"], site=entry["site"],
machine_id=entry.get("machine_id"), erp_workplace=entry["erp_workplace"],
capabilities=capabilities, timezone=sites[entry["site"]].timezone,
material=material, speed=speed,
)
ids = [config.machine_id for config in result.values() if config.machine_id is not None]
if len(set(ids)) != len(ids):
raise ValueError("Shift-report machine IDs must be unique")
return ShiftReportConfig(sites, result)
def load_shift_report_machines(path: str | Path) -> dict[str, ShiftReportMachineConfig]:
"""Compatibility view used by report entry points and historical reconciliation."""
return dict(load_shift_report_config(path).machines)
@@ -0,0 +1,60 @@
"""Construct read-only sources for one explicit shift report."""
from collections.abc import Mapping
from production_analytics.enlyze.exploration import ExplorationClient, ExplorationSettings
from production_analytics.enlyze.gateway import EnlyzeApiGateway
from production_analytics.erp import (
ErpFiberBookingGateway,
ErpProductionConfirmationGateway,
ErpSettings,
)
from production_analytics.service.fiber_allocation import K7FiberAllocationService
from production_analytics.service.postgres_downtime import PostgresDowntimeRepository
from production_analytics.service.postgres_material import PostgresSettings
from production_analytics.service.postgres_shift_material import (
PostgresShiftChannelMaterialRepository,
PostgresShiftMaterialRepository,
)
from production_analytics.service.production_order import ProductionOrderService
from production_analytics.service.shift_downtime import ShiftDowntimeService
from production_analytics.service.shift_material import (
ShiftChannelMaterialService,
ShiftMaterialService,
)
from production_analytics.service.shift_production import ShiftProductionService
from production_analytics.service.shift_report import ShiftReportService
from production_analytics.service.shift_report_config import ShiftReportMachineConfig
from production_analytics.service.shift_speed import ShiftSpeedService
def build_shift_report_service(
machines: Mapping[str, ShiftReportMachineConfig],
environment: Mapping[str, str],
) -> ShiftReportService:
postgres = PostgresSettings.from_environment(environment)
erp = ErpSettings.from_environment(environment)
enlyze = ExplorationSettings.from_environment(environment)
allocators = {
name: K7FiberAllocationService(ErpFiberBookingGateway(erp))
for name, config in machines.items()
if config.material is not None and config.material.allocation == "erp_fiber_share"
}
confirmation_gateway = ErpProductionConfirmationGateway(erp)
materials = ShiftMaterialService(PostgresShiftMaterialRepository(postgres))
channel_materials = ShiftChannelMaterialService(
PostgresShiftChannelMaterialRepository(postgres))
speed = ShiftSpeedService(EnlyzeApiGateway(ExplorationClient(enlyze)))
order_kpis = ProductionOrderService(
confirmation_gateway, machines, speed=speed, materials=materials,
channel_materials=channel_materials, material_allocators=allocators)
return ShiftReportService(
machines=machines,
material_allocators=allocators,
order_kpis=order_kpis,
production=ShiftProductionService(confirmation_gateway),
downtime=ShiftDowntimeService(PostgresDowntimeRepository(postgres)),
materials=materials,
channel_materials=channel_materials,
speed=speed,
)
@@ -0,0 +1,41 @@
"""Compose bounded ENLYZE speed reads with the pure running-speed KPI."""
from datetime import UTC, datetime, timedelta
from typing import Protocol
from production_analytics.calculations.shift_speed import (
ShiftSpeedConfig,
ShiftSpeedSample,
ShiftSpeedSummary,
aggregate_shift_speed,
validate_speed_window,
)
class ShiftSpeedReader(Protocol):
def get_speed_samples(
self, *, machine_id: str, speed_signal_ref: str, start: datetime, end: datetime,
running_signal_ref: str | None = None,
numeric_gate_signal_ref: str | None = None,
) -> list[ShiftSpeedSample]: ...
class ShiftSpeedService:
def __init__(self, gateway: ShiftSpeedReader) -> None:
self.gateway = gateway
def summarize(
self, *, config: ShiftSpeedConfig, start: datetime, end: datetime,
) -> ShiftSpeedSummary:
validate_speed_window(start, end)
kwargs = {"machine_id": config.machine_id, "speed_signal_ref": config.speed_signal_ref,
"start": start, "end": end}
if config.running_signal_ref is not None:
kwargs["running_signal_ref"] = config.running_signal_ref
if config.numeric_dwell_gate is not None:
kwargs["numeric_gate_signal_ref"] = config.numeric_dwell_gate.signal_ref
dwell = timedelta(seconds=config.numeric_dwell_gate.minimum_duration_seconds)
kwargs["start"] = start.astimezone(UTC) - dwell
kwargs["end"] = end.astimezone(UTC) + dwell
samples = self.gateway.get_speed_samples(**kwargs)
return aggregate_shift_speed(samples, config=config, start=start, end=end)
+193
View File
@@ -0,0 +1,193 @@
"""Read-only live shift-report WSGI interface; no report cache or persistence."""
import argparse
import os
from collections.abc import Callable, Mapping
from datetime import UTC, datetime
from pathlib import Path
from urllib.parse import parse_qs
from wsgiref.simple_server import make_server
from production_analytics.calculations.shift_report import (
most_recent_completed_shift,
shift_report_window,
)
from production_analytics.presentation.production_order_html import render_detail, render_search
from production_analytics.presentation.shift_report import render_pdf
from production_analytics.presentation.shift_report_html import render_page
from production_analytics.service.shift_report_config import load_shift_report_config
from production_analytics.service.shift_report_runtime import build_shift_report_service
SHIFT_LABELS = {"early": "Frühschicht", "late": "Spätschicht", "night": "Nachtschicht"}
def create_app(machines: Mapping, service_factory: Callable, *, sites: Mapping | None = None,
clock=None, order_service_factory: Callable | None = None):
"""Inject the configured service factory and clock without connecting at startup."""
clock = clock or (lambda: datetime.now(UTC))
def app(environ, start_response):
headers = [("Cache-Control", "no-store"), ("X-Content-Type-Options", "nosniff")]
status = "200 OK"
content_type = "text/html; charset=utf-8"
path = environ.get("PATH_INFO", "/")
if path in ("/orders", "/order"):
status, payload = _order_response(environ, path, order_service_factory)
if status == "405 Method Not Allowed":
headers.append(("Allow", "GET"))
payload = payload.encode("utf-8")
headers.extend([("Content-Type", content_type), ("Content-Length", str(len(payload)))])
start_response(status, headers)
return [payload]
now = clock()
machine = next(iter(machines))
timezone = machines[machine].timezone
day, shift = most_recent_completed_shift(now, timezone)
error = None
report = None
generated_at = None
if path != "/":
status, error = "404 Not Found", "Seite nicht gefunden."
elif environ.get("REQUEST_METHOD", "GET") != "GET":
status, error = "405 Method Not Allowed", "Diese Anfrage wird nicht unterstützt."
headers.append(("Allow", "GET"))
else:
try:
params = parse_qs(
environ.get("QUERY_STRING", ""), keep_blank_values=True, max_num_fields=10
)
if any(len(values) != 1 for values in params.values()):
raise ValueError
from datetime import date
machine = params.get("machine", [machine])[0]
if machine not in machines:
raise ValueError
timezone = machines[machine].timezone
default_day, default_shift = most_recent_completed_shift(now, timezone)
day = date.fromisoformat(params.get("date", [default_day.isoformat()])[0])
shift = params.get("shift", [default_shift])[0]
output = params.get("format", ["html"])[0]
if shift not in SHIFT_LABELS:
raise ValueError
if output not in ("html", "pdf"):
raise ValueError
start, end = shift_report_window(day, shift, timezone)
except (ValueError, OverflowError):
status = "400 Bad Request"
error = "Ungültige Auswahl. Bitte Datum, Schicht und Maschine prüfen."
else:
try:
report = service_factory().build(machine_name=machine, start=start, end=end)
generated_at = clock().astimezone(timezone)
if output == "pdf":
payload = render_pdf(report)
content_type = "application/pdf"
# Filename excludes externally configured machine names.
headers.append(
(
"Content-Disposition",
f'attachment; filename="Schichtbericht-{day}-{shift}.pdf"',
)
)
else:
payload = None
except Exception:
status = "503 Service Unavailable"
error = (
"Schichtbericht konnte nicht erstellt werden. "
"Bitte später erneut versuchen oder die Datenquellen prüfen lassen."
)
report = None
if error or content_type != "application/pdf":
payload = render_page(
machines=machines,
sites=sites,
labels=SHIFT_LABELS,
day=day,
shift=shift,
machine=machine,
report=report,
generated_at=generated_at,
error=error,
).encode("utf-8")
headers.extend([("Content-Type", content_type), ("Content-Length", str(len(payload)))])
start_response(status, headers)
return [payload]
return app
def _order_response(environ, path: str, service_factory: Callable | None) -> tuple[str, str]:
if environ.get("REQUEST_METHOD", "GET") != "GET":
return "405 Method Not Allowed", render_search(error="Nur GET-Anfragen sind erlaubt.")
try:
params = parse_qs(environ.get("QUERY_STRING", ""), keep_blank_values=True,
max_num_fields=10)
key = "q" if path == "/orders" else "production_order"
if set(params) - {key} or any(len(values) != 1 for values in params.values()):
raise ValueError
if path == "/orders" and key not in params:
return "200 OK", render_search()
value = params[key][0].strip()
if not value or "\x00" in value or len(value) > 80:
raise ValueError
except (ValueError, KeyError):
message = "Bitte eine gültige Fertigungsauftragsnummer eingeben."
if path == "/orders":
return "400 Bad Request", render_search(error=message)
return "400 Bad Request", render_detail(detail=None, error=message)
try:
if service_factory is None:
raise RuntimeError("Order service unavailable")
service = service_factory()
if path == "/orders":
return "200 OK", render_search(query=value, results=service.search(value),
searched=True)
detail = service.detail(value)
return ("200 OK" if detail is not None else "404 Not Found"), render_detail(detail=detail)
except Exception:
message = "Fertigungsauftrag konnte nicht geladen werden. Bitte später erneut versuchen."
if path == "/orders":
return "503 Service Unavailable", render_search(query=value, error=message)
return "503 Service Unavailable", render_detail(detail=None, error=message)
def main(argv=None):
from production_analytics.enlyze.exploration import load_secret_file
parser = argparse.ArgumentParser(description="Live-Schichtberichte")
parser.add_argument("--host", default="127.0.0.1")
parser.add_argument(
"--port", type=int, default=int(os.environ.get("SHIFT_REPORT_PORT", "8087"))
)
parser.add_argument("--config", type=Path, default=Path("config/shift-report-machines.yaml"))
parser.add_argument("--secrets-file", type=Path, default=Path("secrets/enlyze.env"))
parser.add_argument("--erp-secrets-file", type=Path, default=Path("secrets/erp.env"))
parser.add_argument("--db-secrets-file", type=Path, default=Path("secrets/postgres.env"))
args = parser.parse_args(argv)
config = load_shift_report_config(args.config)
machines = config.machines
def service():
environment = dict(os.environ)
for path in (args.secrets_file, args.erp_secrets_file, args.db_secrets_file):
environment.update(load_secret_file(path))
return build_shift_report_service(machines, environment)
def order_service():
environment = dict(os.environ)
for path in (args.secrets_file, args.erp_secrets_file, args.db_secrets_file):
environment.update(load_secret_file(path))
sources = build_shift_report_service(machines, environment)
return sources.order_kpis
app = create_app(machines, service, sites=config.sites,
order_service_factory=order_service)
with make_server(args.host, args.port, app) as server:
print(f"Schichtberichte: http://{args.host}:{args.port}/", flush=True)
server.serve_forever()
if __name__ == "__main__":
main()
+105 -1
View File
@@ -16,6 +16,7 @@ from production_analytics.calculations.material_consumption import (
area_application_rate_kg_per_hour,
)
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_polling import MaterialPollingService
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.get_current_workplace_status.return_value = SimpleNamespace(
workplace='Bento 1', production_order='12026000814', article_number='180305',
@@ -77,9 +78,111 @@ def width_provider():
)
return ErpNominalWidthProvider(
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', [
('Bento 1', 'BENTO 1'),
('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():
config = load_material_calculation('config/k7-material-consumption.yaml')
assert config.source_mode == 'direct_mass_rate'
assert config.fallback_nominal_width_m is None
assert config.rotational_speed_signal_refs == ()
assert config.application_signal_refs == ()
assert config.gate_threshold == 0.5
+203 -1
View File
@@ -54,6 +54,10 @@ def test_e1_config_dry_run_resolves_every_signal_through_gateway_without_samplin
}
for index, origin in enumerate(sorted(origins))
]
+ [
{"uuid": channel.material_name_signal_ref[5:], "details": {"origin_identifier": None}}
for channel in config.channels
]
}
resolved = EnlyzeApiGateway(client).resolve_dosing_channel_signal_refs(
@@ -65,7 +69,13 @@ def test_e1_config_dry_run_resolves_every_signal_through_gateway_without_samplin
assert len(config.channels) == 14
assert len(origins) == 44
assert len(resolved) == 14
assert all(len(refs) == 5 and refs[-1] is None for refs in resolved.values())
for channel in config.channels:
refs = resolved[channel.channel + "\0" + channel.extruder]
assert len(refs) == 6 and refs[-2] is None
assert refs[-1] == channel.material_name_signal_ref[5:]
assert config.channels[1].material_name_signal_ref == (
"uuid:b8be6b5a-0ce7-40ed-9754-107175468c8d"
)
client.get.assert_called_once_with("/v2/variables", {"machine": config.machine_ref})
client.post_json.assert_not_called()
@@ -156,3 +166,195 @@ def test_bootstrap_replays_closed_runs_without_integrating_the_inter_run_gap(tmp
).poll_once(now=NOW + timedelta(seconds=30))
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)
]
+95
View File
@@ -0,0 +1,95 @@
"""Configured downtime runners share the existing machine and order contracts."""
from datetime import timedelta
from pathlib import Path
import pytest
from production_analytics.context import build_enlyze_production_order
from production_analytics.service import downtime_runtime
from production_analytics.service.downtime_runtime import load_downtime_config
from production_analytics.service.shift_report_config import load_shift_report_config
ROOT = Path(__file__).resolve().parents[1]
NEW_RUNNERS = (
("e4", "E4", "12026001013", "E 4-12026001013"),
("gitter1", "Gitter 1", "82026400869", "Gitter 1-82026400869"),
("gitter2", "Gitter 2", "82026400909", "Gitter 2-82026400909"),
("gitter3", "Gitter 3", "82026400900", "Gitter 3-82026400900"),
("gitter4", "Gitter 4", "82026400876", "Gitter 4-82026400876"),
("k5", "K5", "82026400921", "K 5-82026400921"),
("secumat12", "Secumat 1/2", "82026400920", "Sec 1/2-82026400920"),
("secumat3", "Secumat 3", "82026400912", "Sec 3-82026400912"),
)
@pytest.mark.parametrize("slug,name,erp_order,enlyze_order", NEW_RUNNERS)
def test_new_downtime_config_matches_report_machine_and_verified_order(
slug, name, erp_order, enlyze_order,
):
config = load_downtime_config(ROOT / "config" / f"{slug}-downtime.yaml")
report_config = load_shift_report_config(ROOT / "config" / "shift-report-machines.yaml")
machine = report_config.machines[name]
assert (config.machine_id, config.erp_workplace) == (
machine.machine_id, machine.erp_workplace,
)
assert build_enlyze_production_order(erp_order, config.production_order_format) == enlyze_order
assert (config.poll_interval_seconds, config.lookback_hours,
config.full_reconciliation_hours, config.completion_tolerance_m2) == (
300, 48, 24, 0.001,
)
assert machine.capabilities.production and machine.capabilities.downtime
assert not machine.capabilities.material and machine.material is None
speed_enabled = name in {"Gitter 1", "Gitter 2", "Gitter 3", "Gitter 4", "K5"}
assert machine.capabilities.speed is speed_enabled
assert (machine.speed is not None) is speed_enabled
unit = ROOT / "deploy" / "systemd" / f"production-analytics-downtime-{slug}.service"
text = unit.read_text(encoding="utf-8")
assert f"--config {ROOT / 'config' / f'{slug}-downtime.yaml'}" in text
assert "run downtime-reconcile" in text
assert "--secrets-file" in text and "--erp-secrets-file" in text
def test_existing_downtime_configs_and_capabilities_are_unchanged():
machines = load_shift_report_config(ROOT / "config" / "shift-report-machines.yaml").machines
for slug, name in (("bento1", "B1"), ("e1", "E1"), ("k7", "K7")):
config = load_downtime_config(ROOT / "config" / f"{slug}-downtime.yaml")
assert config.machine_id == machines[name].machine_id
assert machines[name].capabilities.downtime
assert (config.poll_interval_seconds, config.lookback_hours,
config.full_reconciliation_hours, config.completion_tolerance_m2) == (
300, 48, 24, 0.001,
)
@pytest.mark.parametrize("slug,name,erp_order,enlyze_order", NEW_RUNNERS)
def test_existing_generic_runtime_builds_each_new_runner(
monkeypatch, slug, name, erp_order, enlyze_order,
):
monkeypatch.setattr(downtime_runtime, "load_secret_file", lambda path: {})
for settings in (downtime_runtime.ExplorationSettings,
downtime_runtime.ErpSettings, downtime_runtime.PostgresSettings):
monkeypatch.setattr(settings, "from_environment", lambda env: object())
runner = downtime_runtime.build_downtime_runner(
ROOT / "config" / f"{slug}-downtime.yaml",
secrets_file=ROOT / "secrets" / "enlyze.env",
erp_secrets_file=ROOT / "secrets" / "erp.env",
)
report_config = load_shift_report_config(ROOT / "config" / "shift-report-machines.yaml")
machine = report_config.machines[name]
assert runner.machine_id == runner.service.machine_id == machine.machine_id
assert runner.service.workplace == machine.erp_workplace
assert runner.interval == 300
assert runner.service.lookback == timedelta(hours=48)
assert runner.service.full_reconciliation_interval == timedelta(hours=24)
assert runner.service.tolerance == 0.001
assert build_enlyze_production_order(
erp_order, runner.service.production_order_format) == enlyze_order
def test_only_expected_machines_have_downtime_enabled():
machines = load_shift_report_config(ROOT / "config" / "shift-report-machines.yaml").machines
assert {name for name, config in machines.items() if config.capabilities.downtime} == {
"B1", "E1", "K7", *(name for _, name, _, _ in NEW_RUNNERS),
}
+76
View File
@@ -0,0 +1,76 @@
import traceback
from decimal import Decimal
from unittest.mock import MagicMock
import pytest
from test_erp_gateway import ENV
from production_analytics.erp import ErpFiberBookingGateway, ErpReadError, ErpSettings
@pytest.fixture
def db(monkeypatch):
connect = MagicMock()
monkeypatch.setattr("production_analytics.erp.gateway.pymssql.connect", connect)
connection = connect.return_value.__enter__.return_value
cursor = connection.cursor.return_value.__enter__.return_value
cursor.fetchall.return_value = [("12026000994 ", "41070418 ", "Fiber ", Decimal("6877.80"))]
return connect, connection, cursor
def gateway():
return ErpFiberBookingGateway(ErpSettings.from_environment(ENV))
def test_order_query_is_parameterized_positive_and_not_shift_bounded(db):
connect, connection, cursor = db
rows = gateway().get_fiber_bookings("12026000994")
assert len(rows) == 1
assert rows[0].production_order == "12026000994"
assert rows[0].material_number == "41070418"
assert rows[0].material_name == "Fiber"
assert rows[0].quantity_kg == 6877.8
sql, parameters = cursor.execute.call_args.args
assert parameters == ("12026000994",)
assert "[Fertigungsauftragsnummer] = %s" in sql
assert "[Fasermenge] > 0" in sql
assert "NULLIF(LTRIM(RTRIM([Rohstoffnummer])), '') IS NOT NULL" in sql
assert "Zeitstempel" not in sql
assert "12026000994" not in sql
connect.assert_called_once_with(
server="localhost",
port=49601,
database="NV_DWH",
user=ENV["ERP_DB_USER"],
password=ENV["ERP_DB_PASSWORD"],
login_timeout=10,
timeout=10,
)
connection.commit.assert_not_called()
connection.cursor.return_value.__exit__.assert_called_once()
connect.return_value.__exit__.assert_called_once()
def test_no_rows_returns_empty(db):
db[2].fetchall.return_value = []
assert gateway().get_fiber_bookings("123") == []
@pytest.mark.parametrize("order", [None, "", " ", "\x00"])
def test_invalid_order_rejected_before_connect(db, order):
with pytest.raises(ValueError):
gateway().get_fiber_bookings(order)
db[0].assert_not_called()
def test_read_failure_does_not_expose_credentials(db):
db[2].execute.side_effect = RuntimeError(ENV["ERP_DB_PASSWORD"])
with pytest.raises(ErpReadError, match="read failed") as caught:
gateway().get_fiber_bookings("123")
assert ENV["ERP_DB_PASSWORD"] not in "".join(traceback.format_exception(caught.value))
def test_invalid_numeric_row_rejected(db):
db[2].fetchall.return_value = [("123", "M1", "Fiber", float("nan"))]
with pytest.raises(ErpReadError, match="invalid row"):
gateway().get_fiber_bookings("123")
+17 -3
View File
@@ -1,9 +1,10 @@
import re
import traceback
from dataclasses import FrozenInstanceError, replace
from datetime import UTC, datetime
from datetime import UTC, datetime, timedelta
from decimal import Decimal
from unittest.mock import MagicMock
from zoneinfo import ZoneInfo
import pytest
@@ -90,8 +91,9 @@ def test_valid_row_and_resource_lifecycle(db):
assert status.production_order == '12026000815'
assert status.article_number == '212520'
assert status.article_description == 'Stex R 1501 C (PR) 5,80 x 50 m'
assert status.feedback_timestamp is NOW
assert status.feedback_timestamp.tzinfo is None
assert status.feedback_timestamp.isoformat() == '2026-09-04T21:20:50+02:00'
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,
status.remaining_time_hours, status.remaining_rolls) == (
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,
status.article_description) == (' K7', ' K 7-001', ' 001', ' description')
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):
@@ -185,3 +189,13 @@ def test_driver_errors_are_safe(db, stage):
assert 'private-password' not in rendered
if stage != 'connect':
connect.return_value.__exit__.assert_called_once()
def test_naive_winter_timestamp_uses_berlin_standard_time(db):
row = list(ROW)
row[4] = datetime(2026, 1, 4, 21, 20, 50)
db[2].fetchmany.return_value = [row]
status = read().get_current_workplace_status('K7')
assert status.feedback_timestamp.isoformat() == '2026-01-04T21:20:50+01:00'
assert status.feedback_timestamp.tzinfo == ZoneInfo('Europe/Berlin')
assert status.feedback_timestamp.utcoffset() == timedelta(hours=1)
+335
View File
@@ -0,0 +1,335 @@
import re
import traceback
from dataclasses import FrozenInstanceError
from datetime import UTC, datetime, timedelta
from decimal import Decimal
from unittest.mock import MagicMock
from zoneinfo import ZoneInfo
import pytest
from production_analytics.erp import (
ErpProductionConfirmationGateway,
ErpReadError,
ErpSettings,
ProductionConfirmation,
)
BERLIN = ZoneInfo("Europe/Berlin")
START = datetime(2026, 9, 4, 6, tzinfo=BERLIN)
END = START + timedelta(hours=8)
DB_TIME = datetime(2026, 9, 4, 8, 20)
ROW = (
"tenant ",
"order-001 ",
DB_TIME,
"BENTO 1 ",
"article-001 ",
"4.85 x 40 m ",
"roll-001 ",
Decimal("194.0000"),
None,
None,
None,
Decimal("194.0000"),
Decimal("0"),
)
@pytest.fixture
def db(monkeypatch):
connect = MagicMock()
monkeypatch.setattr("production_analytics.erp.gateway.pymssql.connect", connect)
connection = connect.return_value.__enter__.return_value
cursor = connection.cursor.return_value.__enter__.return_value
cursor.fetchall.return_value = [ROW]
return connect, connection, cursor
def gateway():
return ErpProductionConfirmationGateway(
ErpSettings("localhost", 49601, "NV_DWH", "private-user", "private-password")
)
def read(**kwargs):
return gateway().get_confirmations(
**{"workplace": "BENTO 1", "start": START, "end": END, **kwargs}
)
def test_finished_goods_mapping_and_connection_lifecycle(db):
connect, connection, cursor = db
confirmation = read()[0]
assert isinstance(confirmation, ProductionConfirmation)
assert confirmation.workplace == "BENTO 1"
assert confirmation.production_order == "order-001"
assert confirmation.tenant == "tenant"
assert confirmation.article_number == "article-001"
assert confirmation.article_description == "4.85 x 40 m"
assert confirmation.roll_number == "roll-001"
assert confirmation.production_quantity_m2 == confirmation.feedback_quantity_m2 == 194.0
assert type(confirmation.feedback_quantity_m2) is float
assert confirmation.raw_material_quantity == 0.0
assert confirmation.raw_material_number is None
assert confirmation.raw_material_description is None
assert confirmation.batch_number is None
assert confirmation.is_finished_goods
assert confirmation.timestamp == DB_TIME.replace(tzinfo=BERLIN)
assert confirmation.timestamp.tzinfo is BERLIN
assert confirmation.timestamp.astimezone(UTC) == datetime(2026, 9, 4, 6, 20, tzinfo=UTC)
with pytest.raises(FrozenInstanceError):
confirmation.workplace = "other"
connect.assert_called_once_with(
server="localhost",
port=49601,
database="NV_DWH",
user="private-user",
password="private-password",
login_timeout=10,
timeout=10,
)
cursor.fetchall.assert_called_once_with()
connection.cursor.return_value.__exit__.assert_called_once()
connect.return_value.__exit__.assert_called_once()
connection.commit.assert_not_called()
def test_exact_parameterized_workplace_and_half_open_window(db):
workplace = " BENTO 1'; DELETE FROM anything; -- "
read(workplace=workplace, start=START.astimezone(UTC), end=END.astimezone(UTC))
sql, params = db[2].execute.call_args.args
assert params == (workplace.strip(), START.replace(tzinfo=None), END.replace(tzinfo=None))
assert workplace.strip() not in sql
assert "WHERE [Arbeitsplatz] = %s AND [Zeitstempel] >= %s AND [Zeitstempel] < %s" in sql
assert re.findall(r"FROM\s+(\S+)", sql) == ["[dbo].[GRAFANA_PRODUCTION_CONFIRMATION]"]
assert "ORDER BY [Zeitstempel], [Mandant], [Fertigungsauftragsnummer], [Rollennummer]" in sql
assert not re.search(r"\b(INSERT|UPDATE|DELETE|MERGE|EXEC|TOP|LIKE)\b", sql, re.I)
assert "[Rückmeldemenge] >" not in sql
@pytest.mark.parametrize("timezone_name,expected_utc_hour", [
("Europe/Berlin", 6), ("Asia/Kuala_Lumpur", 0),
])
def test_explicit_site_timezone_interprets_naive_sql_rows(
db, timezone_name, expected_utc_hour,
):
timezone = ZoneInfo(timezone_name)
start = datetime(2026, 10, 19, 6, tzinfo=timezone)
end = datetime(2026, 10, 19, 14, tzinfo=timezone)
local_row = datetime(2026, 10, 19, 8, 20)
db[2].fetchall.return_value = [(*ROW[:2], local_row, *ROW[3:])]
confirmation = read(start=start.astimezone(UTC), end=end.astimezone(UTC),
timezone=timezone)[0]
assert db[2].execute.call_args.args[1] == (
"BENTO 1", datetime(2026, 10, 19, 6), datetime(2026, 10, 19, 14),
)
assert confirmation.timestamp == local_row.replace(tzinfo=timezone)
assert confirmation.timestamp.tzinfo is timezone
assert confirmation.timestamp.astimezone(UTC).hour == expected_utc_hour
def test_malaysia_evening_confirmation_remains_local_evening(db):
malaysia = ZoneInfo("Asia/Kuala_Lumpur")
local_row = datetime(2026, 10, 19, 18)
db[2].fetchall.return_value = [(*ROW[:2], local_row, *ROW[3:])]
confirmation = read(
start=datetime(2026, 10, 19, 14, tzinfo=malaysia),
end=datetime(2026, 10, 19, 22, tzinfo=malaysia), timezone=malaysia,
)[0]
assert confirmation.timestamp.hour == 18
assert confirmation.timestamp.astimezone(UTC) == datetime(2026, 10, 19, 10, tzinfo=UTC)
def test_half_open_boundaries_with_query_simulation(db):
rows = [
tuple([*ROW[:2], timestamp, *ROW[3:]])
for timestamp in (
START.replace(tzinfo=None) - timedelta(seconds=1),
START.replace(tzinfo=None),
END.replace(tzinfo=None) - timedelta(seconds=1),
END.replace(tzinfo=None),
)
]
def execute(sql, params):
assert "[Zeitstempel] >= %s AND [Zeitstempel] < %s" in sql
db[2].fetchall.return_value = [row for row in rows if params[1] <= row[2] < params[2]]
db[2].execute.side_effect = execute
assert [value.timestamp for value in read()] == [START, END - timedelta(seconds=1)]
@pytest.mark.parametrize("workplace", [None, 123, "", " ", "BENTO\x00 1"])
def test_invalid_workplace_before_connect(db, workplace):
with pytest.raises(ValueError, match="workplace"):
read(workplace=workplace)
db[0].assert_not_called()
@pytest.mark.parametrize("field", ["start", "end"])
@pytest.mark.parametrize("value", [DB_TIME, None, "2026-09-04"])
def test_requires_aware_datetimes(db, field, value):
with pytest.raises(ValueError, match=f"{field} must be a timezone-aware datetime"):
read(**{field: value})
db[0].assert_not_called()
@pytest.mark.parametrize("end", [START, START - timedelta(seconds=1)])
def test_end_must_follow_start(db, end):
with pytest.raises(ValueError, match="end must follow start"):
read(end=end)
db[0].assert_not_called()
def test_raw_material_row_returned_without_finished_goods_filter(db):
row = list(ROW)
row[6:13] = [
None,
Decimal("0"),
"raw-001 ",
"Raw material ",
"batch-001 ",
Decimal("0"),
Decimal("123.1250"),
]
db[2].fetchall.return_value = [ROW, row]
finished, material = read()
assert finished.is_finished_goods
assert not material.is_finished_goods
assert material.production_quantity_m2 == material.feedback_quantity_m2 == 0.0
assert material.raw_material_quantity == 123.125
assert (
material.raw_material_number,
material.raw_material_description,
material.batch_number,
) == ("raw-001", "Raw material", "batch-001")
assert material.roll_number is None
def test_nullable_fields_and_empty_result(db):
db[2].fetchall.return_value = [(None, "order", DB_TIME, "K7", *([None] * 9))]
value = read(workplace="K7")[0]
assert not value.is_finished_goods
assert all(
getattr(value, field) is None
for field in (
"tenant",
"article_number",
"article_description",
"roll_number",
"production_quantity_m2",
"feedback_quantity_m2",
"raw_material_number",
"raw_material_description",
"batch_number",
"raw_material_quantity",
)
)
db[2].fetchall.return_value = []
assert read() == []
@pytest.mark.parametrize("index", [7, 11, 12])
@pytest.mark.parametrize(
"value",
[
Decimal("NaN"),
Decimal("Infinity"),
Decimal("1e999"),
float("nan"),
float("-inf"),
True,
"private-password",
],
)
def test_invalid_numeric_values_are_safe(db, index, value):
row = list(ROW)
row[index] = value
db[2].fetchall.return_value = [row]
with pytest.raises(ErpReadError, match="invalid row") as error:
read()
assert "private-password" not in "".join(traceback.format_exception(error.value))
@pytest.mark.parametrize(
"row",
[
ROW[:-1],
(*ROW, "extra"),
(*ROW[:2], None, *ROW[3:]),
(*ROW[:2], DB_TIME.replace(tzinfo=UTC), *ROW[3:]),
(*ROW[:3], None, *ROW[4:]),
(ROW[0], 123, *ROW[2:]),
],
)
def test_malformed_rows_are_safe(db, row):
db[2].fetchall.return_value = [row]
with pytest.raises(ErpReadError, match="invalid row"):
read()
@pytest.mark.parametrize("stage", ["connect", "execute", "fetch", "cursor_close", "close"])
def test_driver_errors_are_safe(db, stage):
connect, connection, cursor = db
target = {
"connect": connect,
"execute": cursor.execute,
"fetch": cursor.fetchall,
"cursor_close": connection.cursor.return_value.__exit__,
"close": connect.return_value.__exit__,
}[stage]
target.side_effect = RuntimeError("private-user private-password")
with pytest.raises(ErpReadError, match="read failed") as error:
read()
rendered = "".join(traceback.format_exception(error.value))
assert "private-user" not in rendered and "private-password" not in rendered
if stage != "connect":
connect.return_value.__exit__.assert_called_once()
@pytest.mark.parametrize(
"local,offset",
[
(datetime(2026, 3, 29, 1, 30), 1),
(datetime(2026, 3, 29, 3, 30), 2),
(datetime(2026, 10, 25, 1, 30), 2),
(datetime(2026, 10, 25, 3, 30), 1),
],
)
def test_dst_offsets_follow_local_plant_time(db, local, offset):
db[2].fetchall.return_value = [(*ROW[:2], local, *ROW[3:])]
start = local.replace(tzinfo=BERLIN)
confirmation = read(start=start.astimezone(UTC), end=start + timedelta(minutes=10))[0]
assert confirmation.timestamp.replace(tzinfo=None) == local
assert confirmation.timestamp.utcoffset() == timedelta(hours=offset)
assert db[2].execute.call_args.args[1][1] == local
def test_window_across_spring_dst_transition(db):
start = datetime(2026, 3, 29, 0, 30, tzinfo=UTC)
end = datetime(2026, 3, 29, 1, 30, tzinfo=UTC)
read(start=start, end=end)
assert db[2].execute.call_args.args[1][1:] == (
datetime(2026, 3, 29, 1, 30),
datetime(2026, 3, 29, 3, 30),
)
def test_ambiguous_db_timestamp_uses_documented_first_occurrence(db):
local = datetime(2026, 10, 25, 2, 30)
db[2].fetchall.return_value = [(*ROW[:2], local, *ROW[3:])]
confirmation = read(
start=datetime(2026, 10, 25, 0, tzinfo=UTC), end=datetime(2026, 10, 25, 3, tzinfo=UTC)
)[0]
assert confirmation.timestamp.fold == 0
assert confirmation.timestamp.astimezone(UTC) == datetime(2026, 10, 25, 0, 30, tzinfo=UTC)
def test_unrepresentable_repeated_hour_interval_is_rejected(db):
with pytest.raises(ValueError, match="plant-local SQL time"):
read(
start=datetime(2026, 10, 25, 2, 45, tzinfo=BERLIN, fold=0),
end=datetime(2026, 10, 25, 2, 15, tzinfo=BERLIN, fold=1),
)
db[0].assert_not_called()
+250
View File
@@ -0,0 +1,250 @@
from dataclasses import replace
from math import fsum
from unittest.mock import Mock
import pytest
from test_shift_report import END, START, composition
from production_analytics.calculations.fiber_allocation import (
FiberBooking,
allocate_fiber_materials,
)
from production_analytics.calculations.shift_material import ShiftMaterialSummary
from production_analytics.presentation.shift_report import (
MaterialPieBlock,
TableBlock,
present_report,
render_pdf,
)
from production_analytics.service.fiber_allocation import K7FiberAllocationService
ORDER = "12026000994"
NAMES = ("PP 1A, weiß, 6,0, hf - 90- Drittland", "PP 1A, weiß, 6,0, hf - 90")
BOOKINGS = (
FiberBooking(ORDER, "41070418", NAMES[0], 6878),
FiberBooking(ORDER, "41070419", NAMES[1], 3122),
)
def measured_item(order=f"K 7-{ORDER}", quantity=3468.77):
_, stubs, _, _ = composition("K7")
return replace(
stubs["materials"].result.items[0], production_order=order, consumption_kg=quantity
)
def test_ratios_allocate_measured_mass_without_rounding():
item = measured_item()
allocated = allocate_fiber_materials(item, BOOKINGS, erp_order=ORDER)
assert [value.material_number for value in allocated] == ["41070418", "41070419"]
assert [value.erp_booking_share for value in allocated] == pytest.approx([0.6878, 0.3122])
assert [value.consumption_kg for value in allocated] == pytest.approx(
[2385.819006, 1082.950994]
)
assert fsum(value.consumption_kg for value in allocated) == pytest.approx(item.consumption_kg)
assert allocated[0].consumption_kg != pytest.approx(item.consumption_kg * 0.69)
assert all(value.baseline_timestamp == item.baseline_timestamp for value in allocated)
assert all(value.end_timestamp == item.end_timestamp for value in allocated)
assert all(value.baseline_missing == item.baseline_missing for value in allocated)
assert item.material_number is None
def test_duplicate_bookings_aggregate_by_number_and_name():
allocated = allocate_fiber_materials(
measured_item(),
[
FiberBooking(ORDER, "M1", "Fiber", 20),
FiberBooking(ORDER, "M1", "Fiber", 30),
FiberBooking(ORDER, "M2", "Fiber", 50),
],
erp_order=ORDER,
)
assert len(allocated) == 2
assert [item.material_number for item in allocated] == ["M1", "M2"]
assert [item.erp_booking_share for item in allocated] == [0.5, 0.5]
@pytest.mark.parametrize(
"bookings",
[
[],
[FiberBooking(ORDER, "181900", "Product", 0)],
[
FiberBooking(ORDER, "M1", "Fiber", -1),
FiberBooking(ORDER, "", "Fiber", 10),
FiberBooking(ORDER, None, "Fiber", 10),
FiberBooking(ORDER, "M1", "Fiber", None),
],
],
)
def test_no_usable_bookings_preserves_unassigned_measured_item(bookings):
item = measured_item()
assert allocate_fiber_materials(item, bookings, erp_order=ORDER) == (item,)
def test_invalid_rows_ignored_and_single_material_has_full_share():
allocated = allocate_fiber_materials(
measured_item(),
[
FiberBooking(ORDER, "M1", "Fiber", 25),
FiberBooking(ORDER, "M2", "Fiber", 0),
FiberBooking(ORDER, "M3", "Fiber", -10),
FiberBooking(ORDER, " ", "Fiber", 100),
FiberBooking(ORDER, "M4", "Fiber", float("nan")),
FiberBooking("other", "M5", "Fiber", 1000),
],
erp_order=ORDER,
)
assert len(allocated) == 1
assert allocated[0].material_number == "M1"
assert allocated[0].erp_booking_share == 1
assert allocated[0].consumption_kg == 3468.77
def test_order_aware_service_preserves_totals_runs_and_caches_order_reads():
reader = Mock()
reader.get_fiber_bookings.side_effect = lambda order: (
BOOKINGS if order == ORDER else [FiberBooking(order, "M3", "Other fiber", 1)]
)
items = (
measured_item(quantity=100),
replace(measured_item(quantity=200), run_id="run2"),
measured_item("K 7-123", 400),
)
measured = ShiftMaterialSummary(items[0].machine_id, START, END, 700, items)
allocated = K7FiberAllocationService(reader).allocate(measured)
assert allocated.total_consumption_kg == measured.total_consumption_kg
assert fsum(item.consumption_kg for item in allocated.items) == pytest.approx(700)
assert len(allocated.items) == 5
assert allocated.items[-1].material_number == "M3"
assert allocated.items[-1].production_order == "K 7-123"
assert reader.get_fiber_bookings.call_count == 2
assert measured.items == items
@pytest.mark.parametrize("order", ["K 7-123-K 7-456", "unknown", ""])
def test_ambiguous_order_never_queries_or_invents_recipe(order):
reader = Mock()
item = measured_item(order)
measured = ShiftMaterialSummary(item.machine_id, START, END, item.consumption_kg, (item,))
allocated = K7FiberAllocationService(reader).allocate(measured)
assert allocated.items == measured.items
reader.get_fiber_bookings.assert_not_called()
@pytest.mark.parametrize("machine", ["B1", "E1", "K7"])
def test_report_wiring_applies_adapter_only_to_k7(machine):
service, stubs, _, _ = composition(machine)
reader = Mock()
reader.get_fiber_bookings.return_value = BOOKINGS
service.material_allocators = {"K7": K7FiberAllocationService(reader)}
stubs["materials"].result = (
replace(stubs["materials"].result, items=(measured_item(quantity=42),))
if machine == "K7"
else stubs["materials"].result
)
value = service.build(machine_name=machine, start=START, end=END)
if machine == "K7":
assert len(value.materials.items) == 2
reader.get_fiber_bookings.assert_called_once_with(ORDER)
else:
reader.get_fiber_bookings.assert_not_called()
assert (
value.materials is stubs["channel_materials" if machine == "E1" else "materials"].result
)
def test_same_allocation_behavior_for_differently_named_machine():
service, stubs, _, config = composition("K7")
service.machines = {"Synthetic": config}
reader = Mock()
reader.get_fiber_bookings.return_value = BOOKINGS
service.material_allocators = {"Synthetic": K7FiberAllocationService(reader)}
item = measured_item(quantity=42)
stubs["materials"].result = replace(stubs["materials"].result, items=(item,))
report = service.build(machine_name="Synthetic", start=START, end=END)
assert len(report.materials.items) == 2
assert sum(part.consumption_kg for part in report.materials.items) == pytest.approx(42)
reader.get_fiber_bookings.assert_called_once_with(ORDER)
def test_pdf_displays_whole_shares_and_estimation_note():
service, stubs, _, _ = composition("K7")
item = measured_item()
stubs["materials"].result = replace(
stubs["materials"].result, items=(item,), total_consumption_kg=item.consumption_kg
)
reader = Mock()
reader.get_fiber_bookings.return_value = BOOKINGS
service.material_allocators = {"K7": K7FiberAllocationService(reader)}
report = service.build(machine_name="K7", start=START, end=END)
blocks = present_report(report)
table = next(
block for block in blocks if isinstance(block, TableBlock) and "ERP-Anteil" in block.headers
)
rows = {row[2]: row for row in table.rows}
assert rows["41070418"][1:] == (NAMES[0], "41070418", "2.385,82 kg", "69%")
assert rows["41070419"][1:] == (NAMES[1], "41070419", "1.082,95 kg", "31%")
assert any(
getattr(block, "text", "")
== "Verbrauchsaufteilung geschätzt nach ERP-Buchungsverhältnis; Gesamtverbrauch aus ENLYZE."
for block in blocks
)
chart = next(block for block in blocks if isinstance(block, MaterialPieBlock))
assert fsum(chart.consumption_kg) == pytest.approx(3468.77)
def test_source_ratios_retain_precision_beyond_displayed_percentage():
bookings = (replace(BOOKINGS[0], quantity_kg=6877.8), replace(BOOKINGS[1], quantity_kg=3122.2))
allocated = allocate_fiber_materials(measured_item(), bookings, erp_order=ORDER)
assert [item.consumption_kg for item in allocated] == pytest.approx(
[2385.7496306, 1083.0203694]
)
assert [f"{item.erp_booking_share * 100:.0f}%" for item in allocated] == ["69%", "31%"]
assert fsum(item.consumption_kg for item in allocated) == pytest.approx(3468.77)
def test_pdf_keeps_different_order_shares_separate_and_combines_material_pie():
service, stubs, _, _ = composition("K7")
items = (measured_item(quantity=100), measured_item("K 7-123", 200))
stubs["materials"].result = replace(
stubs["materials"].result, items=items, total_consumption_kg=300
)
reader = Mock()
reader.get_fiber_bookings.side_effect = lambda order: (
BOOKINGS if order == ORDER else [replace(BOOKINGS[0], production_order=order)]
)
service.material_allocators = {"K7": K7FiberAllocationService(reader)}
report = service.build(machine_name="K7", start=START, end=END)
blocks = present_report(report)
table = next(
block for block in blocks if isinstance(block, TableBlock) and "ERP-Anteil" in block.headers
)
assert len(table.rows) == 3
assert {(row[0], row[-1]) for row in table.rows} == {
(f"K 7-{ORDER}", "69%"),
(f"K 7-{ORDER}", "31%"),
("K 7-123", "100%"),
}
chart = next(block for block in blocks if isinstance(block, MaterialPieBlock))
assert len(chart.labels) == 2
assert sorted(chart.consumption_kg) == pytest.approx([31.22, 268.78])
assert render_pdf(report) == render_pdf(report)
def test_missing_erp_data_keeps_pdf_unassigned_and_measured_total():
service, stubs, _, _ = composition("K7")
stubs["materials"].result = replace(
stubs["materials"].result, items=(measured_item(),), total_consumption_kg=3468.77
)
reader = Mock()
reader.get_fiber_bookings.return_value = []
service.material_allocators = {"K7": K7FiberAllocationService(reader)}
report = service.build(machine_name="K7", start=START, end=END)
table = next(
block
for block in present_report(report)
if isinstance(block, TableBlock) and "Materialname" in block.headers
)
assert table.rows == (("Materialzuordnung fehlt", "–", "3.468,77 kg"),)
assert report.materials.total_consumption_kg == 3468.77
+548
View File
@@ -0,0 +1,548 @@
from dataclasses import replace
from datetime import UTC, datetime
from types import SimpleNamespace
from unittest.mock import MagicMock
import pytest
from production_analytics.enlyze.gateway import EnlyzeProductionRun
from production_analytics.service.historical_reconcile import (
Decision,
HistoricalRecord,
decide,
reconcile_machine,
reconciliation_window,
)
from production_analytics.service.postgres_historical_reconcile import PostgresHistoricalRepository
def at(hour=12):
return datetime(2026, 10, 13, hour, tzinfo=UTC)
def record(order="old", machine="generic"):
return HistoricalRecord("material_consumption_snapshots", ("calc", machine, at()),
machine, at(), order, "retained-counter-run")
def run(order="Machine-123", machine="generic"):
return EnlyzeProductionRun("source-run", machine, None, order, at(10), at(14))
def confirmation(order="123", hour=12):
return SimpleNamespace(production_order=order, workplace="workplace",
timestamp=at(hour), is_finished_goods=True)
def decision(r=None, runs=None, confirmations=None):
return decide(r or record(), runs if runs is not None else [run()],
confirmations if confirmations is not None else [confirmation()],
"workplace", "Machine-{production_order}")
def test_correct_and_stale_assignments():
assert decision(record("Machine-123")).order == "Machine-123"
d = decision()
assert d.order == "Machine-123"
assert d.record.run_id == "retained-counter-run"
@pytest.mark.parametrize("machine", ["arbitrary-machine", "another-machine"])
def test_machine_independent(machine):
assert decision(record(machine=machine), [run(machine=machine)]).order == "Machine-123"
@pytest.mark.parametrize("runs, confirmations", [
([run(), run("Machine-456")], [confirmation()]),
([run()], [confirmation(), confirmation("456")]),
([], [confirmation()]),
([replace(run(), end=None)], [confirmation()]),
([run(), replace(run(), end=None)], [confirmation()]),
([run()], []),
])
def test_ambiguous_or_missing_evidence(runs, confirmations):
assert decision(runs=runs, confirmations=confirmations).order is None
def test_previous_order_at_start_is_ignored_when_current_order_is_inside():
start = confirmation("1030", 10)
current = confirmation("12026001032")
d = decide(record("K 7-12026001030", "reference-machine"),
[replace(run("K 7-12026001032", "reference-machine"),
start=at(10), end=at(14))], [start, current],
"workplace", "K 7-{production_order}")
assert d.order == "K 7-12026001032"
def test_interior_conflicting_order_remains_unresolved():
assert decision(confirmations=[confirmation("123"), confirmation("456", 13)]).order is None
def test_correct_order_at_start_without_interior_evidence_is_unresolved():
boundary = confirmation("123", 10)
assert decision(confirmations=[boundary]).order is None
def test_correct_order_strictly_inside_run_reconciles():
assert decision(confirmations=[confirmation("123", 11)]).order == "Machine-123"
def test_confirmation_at_run_end_is_ignored():
end = confirmation("123", 14)
assert decision(confirmations=[end]).order is None
def test_shared_boundary_confirmation_corroborates_neither_adjacent_run():
left = replace(run("Machine-123"), start=at(10), end=at(12))
right = replace(run("Machine-456"), uuid="right", start=at(12), end=at(14))
boundary = confirmation("123", 12)
left_record = replace(record(), timestamp=at(11))
right_record = replace(record(), timestamp=at(13))
assert decide(left_record, [left, right], [boundary], "workplace",
"Machine-{production_order}").order is None
assert decide(right_record, [left, right], [boundary], "workplace",
"Machine-{production_order}").order is None
def test_k7_repaired_1030_to_1032_boundary_case_is_correctable():
r = record("K 7-12026001030", "reference-machine")
run_start = at(11)
k7_run = replace(run("K 7-12026001032", "reference-machine"),
start=run_start, end=at(17))
previous = confirmation("12026001030", 11)
d = decide(r, [k7_run], [previous, confirmation("12026001032", 12)],
"workplace", "K 7-{production_order}")
assert d.order == "K 7-12026001032"
d = decide(r, [k7_run], [confirmation("12026001032"), confirmation("12026001037", 13)],
"workplace", "K 7-{production_order}")
assert d.order is None
def test_calendar_days_and_berlin_dst():
start, end = reconciliation_window(datetime(2026, 10, 15, 2, 30, tzinfo=UTC))
assert start.isoformat() == "2026-10-12T00:00:00+02:00"
assert end.isoformat() == "2026-10-15T00:00:00+02:00"
start, end = reconciliation_window(datetime(2026, 10, 27, tzinfo=UTC))
assert (end.timestamp() - start.timestamp()) / 3600 == 73
# UTC date still previous day; use Berlin's date.
assert reconciliation_window(datetime(2026, 10, 14, 23, tzinfo=UTC))[1].day == 15
@pytest.mark.parametrize("days", [0, -1, True])
def test_invalid_window(days):
with pytest.raises(ValueError):
reconciliation_window(at(), days)
def test_dry_run_and_source_failure():
repository = MagicMock()
repository.read.return_value = [record()]
repository.guard_runs.side_effect = lambda decisions: decisions
source = MagicMock()
source.get_production_runs.return_value = [run()]
erp = MagicMock()
erp.get_confirmations.return_value = [confirmation()]
config = SimpleNamespace(machine_id="generic", erp_workplace="workplace")
decisions, applied = reconcile_machine(repository, source, erp, config,
"Machine-{production_order}", at(11), at(13), True)
assert decisions[0].order == "Machine-123" and applied == 0
repository.apply.assert_not_called()
assert erp.get_confirmations.call_args.kwargs["start"] == at(10)
assert erp.get_confirmations.call_args.kwargs["end"] == at(14)
source.get_production_runs.side_effect = RuntimeError("source unavailable")
with pytest.raises(RuntimeError, match="source unavailable"):
reconcile_machine(repository, source, erp, config, "Machine-{production_order}",
at(11), at(13))
repository.apply.assert_not_called()
def repository_with_connection():
repository = PostgresHistoricalRepository(None)
connection = MagicMock()
repository.connect = MagicMock()
repository.connect.return_value.__enter__.return_value = connection
return repository, connection
def test_atomic_update_audit_and_repeated_run():
repository, connection = repository_with_connection()
connection.execute.return_value.fetchone.side_effect = [(1,), (at(),)]
assert repository.apply([decision()]) == 1
calls = connection.execute.call_args_list
assert len(calls) == 5 # isolation, lock, run guard, update, audit
update_args = calls[3].args[1]
assert update_args == ("Machine-123", "calc", "generic", at(), "old", "retained-counter-run")
audit_args = calls[4].args[1]
assert audit_args[0] == "generic"
assert audit_args[3:6] == ("old", "Machine-123", "retained-counter-run")
connection.reset_mock()
assert repository.apply([decision(record("Machine-123"))]) == 0
assert connection.execute.call_count == 2 # no update or audit
def test_concurrent_change_fails_without_audit():
repository, connection = repository_with_connection()
connection.execute.return_value.fetchone.side_effect = [(1,), None]
with pytest.raises(RuntimeError, match="concurrently"):
repository.apply([decision()])
assert connection.execute.call_count == 4
assert repository.connect.return_value.__exit__.call_args.args[0] is RuntimeError
def test_partial_and_split_run_guard():
repository, connection = repository_with_connection()
connection.execute.return_value.fetchone.return_value = (2,)
assert repository.guard_runs([decision()])[0].order is None
d = decision()
other = replace(d, record=replace(d.record, timestamp=at(13)), order="Machine-456")
assert repository.guard_runs([d, other]) == [d, other]
assert all(d.order is None for d in repository.guard_runs([d, replace(other, order=None)]))
connection.execute.return_value.fetchone.return_value = (1,)
assert repository.guard_runs([decision()])[0].order == "Machine-123"
def test_database_failure_propagates():
repository = PostgresHistoricalRepository(None)
repository.connect = MagicMock(side_effect=RuntimeError("database unavailable"))
with pytest.raises(RuntimeError, match="database unavailable"):
repository.read("machine", at(10), at(14))
def test_cli_defaults():
from production_analytics.cli.__main__ import _parser
args = _parser().parse_args(["historical-reconcile", "--dry-run"])
assert args.lookback_days == 3 and args.dry_run and not args.verbose
assert _parser().parse_args(["historical-reconcile", "--verbose"]).verbose
assert _parser().parse_args(["historical-reconcile", "--dry-run", "--verbose"]).verbose
@pytest.mark.parametrize("split", [False, True])
def test_end_to_end_dry_run_idempotency_and_physical_values(sqlite_schema, split):
import sqlite3
database = sqlite3.connect(":memory:")
database.executescript(sqlite_schema)
database.execute(
"INSERT INTO material_consumption_snapshots VALUES (?, ?, ?, ?, ?, ?)",
(at().isoformat(), "calc", "generic", "old", "retained-counter-run", 1234.5),
)
if split:
database.execute("DELETE FROM material_consumption_snapshots")
database.executemany(
"INSERT INTO material_consumption_snapshots VALUES (?, ?, ?, ?, ?, ?)",
[(at(hour).isoformat(), "calc", "generic", "OLD", "R1", value)
for hour, value in zip([10, 11, 12, 13], [1000, 1010, 1025, 1040])],
)
class Connection:
def __enter__(self):
return self
def __exit__(self, exc_type, *_):
database.rollback() if exc_type else database.commit()
def execute(self, statement, parameters=()):
statement = statement if isinstance(statement, str) else statement.as_string()
if statement.startswith(("SET TRANSACTION", "SELECT pg_advisory")):
return None
parameters = tuple(
str(p.obj) if hasattr(p, "obj") else p.isoformat()
if isinstance(p, datetime) else p for p in parameters
)
return database.execute(statement.replace("%s", "?"), parameters)
class Repository(PostgresHistoricalRepository):
def connect(self):
return Connection()
def read(self, machine_id, start, end):
return [replace(r, timestamp=datetime.fromisoformat(r.timestamp),
identity=(*r.identity[:2], datetime.fromisoformat(r.identity[2])))
for r in super().read(machine_id, start, end)]
repository = Repository(None)
source = SimpleNamespace(get_production_runs=lambda machine: [run()])
erp = SimpleNamespace(get_confirmations=lambda **kwargs: [confirmation()])
config = SimpleNamespace(machine_id="generic", erp_workplace="workplace")
if split:
source = SimpleNamespace(get_production_runs=lambda machine: [
replace(run("1032"), start=at(10), end=at(12)),
replace(run("1037"), uuid="second", start=at(12), end=at(14)),
])
erp = SimpleNamespace(get_confirmations=lambda **kwargs: [
confirmation("1032", 11), confirmation("1037", 13)])
template = "{production_order}" if split else "Machine-{production_order}"
args = (repository, source, erp, config, template, at(10), at(14))
decisions, count = reconcile_machine(*args, dry_run=True)
assert count == 0 and decisions[0].order == ("1032" if split else "Machine-123")
assert database.execute("SELECT count(*) FROM historical_assignment_audit").fetchone() == (0,)
assert database.execute(
"SELECT production_order FROM material_consumption_snapshots"
).fetchone() == (("OLD",) if split else ("old",))
assert reconcile_machine(*args)[1] == (4 if split else 1)
assert reconcile_machine(*args)[1] == 0
assert database.execute("SELECT count(*) FROM historical_assignment_audit").fetchone() == (
4 if split else 1,)
if split:
from production_analytics.calculations.shift_material import (
ShiftMaterialSnapshot,
aggregate_shift_material,
)
from production_analytics.service.historical_reconcile import grouped_counts
assert grouped_counts(decisions) == (1, 1, 2, 0, 0)
rows = database.execute(
"SELECT timestamp, calculation_id, machine_id, production_order, run_id, "
"consumption_kg FROM material_consumption_snapshots ORDER BY timestamp"
).fetchall()
snapshots = [ShiftMaterialSnapshot(datetime.fromisoformat(r[0]), *r[1:]) for r in rows]
assert [(r.timestamp.hour, r.run_id, r.consumption_kg) for r in snapshots] == [
(10, "R1", 1000), (11, "R1", 1010), (12, "R1", 1025), (13, "R1", 1040)]
summary = aggregate_shift_material(snapshots, machine_id="generic",
calculation_ids=("calc",), start=at(10), end=at(14))
assert [(i.production_order, i.consumption_kg) for i in summary.items] == [
("1032", 10), ("1037", 30)]
assert summary.total_consumption_kg == 40
return
assert database.execute(
"SELECT timestamp, run_id, consumption_kg, production_order "
"FROM material_consumption_snapshots"
).fetchone() == (at().isoformat(), "retained-counter-run", 1234.5, "Machine-123")
def test_erp_failure_never_becomes_no_changes():
repository = MagicMock()
repository.read.return_value = [record()]
source = SimpleNamespace(get_production_runs=lambda machine: [run()])
erp = MagicMock()
erp.get_confirmations.side_effect = RuntimeError("ERP offline")
with pytest.raises(RuntimeError, match="ERP offline"):
reconcile_machine(repository, source, erp,
SimpleNamespace(machine_id="generic", erp_workplace="workplace"),
"Machine-{production_order}", at(10), at(14))
repository.apply.assert_not_called()
def test_runtime_reports_machine_failures_and_continues(monkeypatch, capsys):
from pathlib import Path
from production_analytics.service import historical_runtime
for factory in ("PostgresHistoricalRepository", "EnlyzeApiGateway",
"ExplorationClient", "ErpProductionConfirmationGateway"):
monkeypatch.setattr(historical_runtime, factory, MagicMock())
for settings in (historical_runtime.PostgresSettings, historical_runtime.ErpSettings,
historical_runtime.ExplorationSettings):
monkeypatch.setattr(settings, "from_environment", MagicMock())
reconcile = MagicMock(side_effect=[RuntimeError("source offline"), ([], 0), ([], 0)])
monkeypatch.setattr(historical_runtime, "reconcile_machine", reconcile)
args = SimpleNamespace(lookback_days=3, dry_run=True,
config=Path("config/shift-report-machines.yaml"),
order_formats=Path("config/historical-order-formats.yaml"))
assert historical_runtime.run(args, {}) == 1
assert reconcile.call_count == 3
output = capsys.readouterr().out
assert "Physical runs inspected:" in output and "Unresolved segments:" in output
assert "Order segments proposed:" in output
assert "DRY RUN" in output and "FAILED B1" in output and "Failures: 1" in output
assert "source offline" in output
@pytest.mark.parametrize("dry_run", [True, False])
@pytest.mark.parametrize("verbose", [True, False])
def test_runtime_groups_record_output_and_preserves_totals(monkeypatch, capsys, dry_run, verbose):
from datetime import timedelta
from pathlib import Path
from production_analytics.service import historical_runtime
for factory in ("PostgresHistoricalRepository", "EnlyzeApiGateway",
"ExplorationClient", "ErpProductionConfirmationGateway"):
monkeypatch.setattr(historical_runtime, factory, MagicMock())
for settings in (historical_runtime.PostgresSettings, historical_runtime.ErpSettings,
historical_runtime.ExplorationSettings):
monkeypatch.setattr(settings, "from_environment", MagicMock())
start = at(10)
correction_reason = ("closed ENLYZE run e0f474e0-1234 "
"[2026-10-13T10:00:00+00:00, 2026-10-13T14:00:00+00:00) "
"corroborated by ERP order K 7-12026001032")
corrections = [
Decision(HistoricalRecord(
"material_consumption_snapshots", ("calc", "machine", start + timedelta(seconds=i)),
"machine", start + timedelta(seconds=i), "K 7-12026001030", "counter-run",
), "K 7-12026001032", correction_reason)
for i in range(1964)
]
unresolved = [
Decision(HistoricalRecord(
"material_application_snapshots", ("application", "machine",
start + timedelta(seconds=i)),
"machine", start + timedelta(seconds=i), "B 1-42", "application-run",
), None, "unresolved: missing or overlapping closed ENLYZE runs")
for i in range(8421)
]
reconcile = MagicMock(side_effect=[(corrections, 1964 if not dry_run else 0),
(unresolved, 0), ([], 0)])
monkeypatch.setattr(historical_runtime, "reconcile_machine", reconcile)
args = SimpleNamespace(lookback_days=3, dry_run=dry_run, verbose=verbose,
config=Path("config/shift-report-machines.yaml"),
order_formats=Path("config/historical-order-formats.yaml"))
assert historical_runtime.run(args, {}) == 0
output = capsys.readouterr().out
correction_action = "proposed" if dry_run else "corrected"
assert (f"B1 | {correction_action}: K 7-12026001030 -> K 7-12026001032 | "
"ENLYZE run e0f474e0-1234 | 1964 records") in output
assert ("E1 | unresolved: missing or overlapping closed ENLYZE runs | "
"physical run application-run | source material_application_snapshots/application | "
"8421 records | 2026-10-13T10:00:00+00:00 -> "
"2026-10-13T12:20:20+00:00") in output
assert output.count("1964 records") == 1
assert output.count("8421 records") == 1
if verbose:
assert output.count("Proposed B1 " if dry_run else "Corrected B1 ") == 1964
assert output.count("Unresolved E1 ") == 8421
else:
assert "Proposed B1 " not in output
assert "Corrected B1 " not in output
assert "Unresolved E1 " not in output
assert "('calc', 'machine'" not in output
assert len(output.splitlines()) == 15
assert "Machines checked: 3\nRecords inspected: 10385" in output
assert f"Corrections {'proposed' if dry_run else 'applied'}: 1964" in output
assert "Ambiguous/unresolved: 8421\nUnchanged: 0\nFailures: 0" in output
assert "Physical runs inspected: 2\nRuns with proposed corrections: 1" in output
assert f"Order segments {correction_action}: 1" in output
assert "Unresolved runs: 1\nUnresolved segments: 1" in output
def test_grouped_counts_distinguish_rows_runs_and_segments():
from production_analytics.service.historical_reconcile import grouped_counts
d = decision()
decisions = [replace(d, record=replace(d.record, timestamp=at(hour)), order=order)
for hour, order in [(10, "A"), (11, "A"), (12, "B"), (13, None)]]
assert grouped_counts(decisions) == (1, 1, 2, 1, 1)
assert grouped_counts([]) == (0, 0, 0, 0, 0)
@pytest.mark.parametrize("calculation", [
"bento1-fresh-bentonite-application", "bento1-spreader3-application",
])
def test_application_collision_deduplicates_audits_and_is_idempotent(
sqlite_schema, calculation,
):
database, repository = application_repository(sqlite_schema)
for hour in (11, 12, 13):
insert_application(database, calculation, hour, "old", "old-run", 4730.169159683733)
insert_application(database, calculation, hour, "Machine-123", "source-run",
4730.169159683733)
args = application_reconcile_args(repository)
decisions, count = reconcile_machine(*args, dry_run=True)
assert count == 0 and len([d for d in decisions if d.order != d.record.production_order]) == 3
assert application_rows(database, calculation) == 6
assert database.execute("SELECT count(*) FROM historical_assignment_audit").fetchone() == (0,)
assert reconcile_machine(*args)[1] == 3
assert application_rows(database, calculation) == 3
assert database.execute(
"SELECT production_order, run_id, application_g_m2 FROM material_application_snapshots "
"WHERE calculation_id = ? ORDER BY timestamp", (calculation,)
).fetchall() == [("Machine-123", "source-run", 4730.169159683733)] * 3
assert database.execute(
"SELECT previous_order, new_order, run_id, retained_run_id, action, reason, "
"record_identity FROM historical_assignment_audit ORDER BY id"
).fetchall() == [
("old", "Machine-123", "old-run", "source-run", "deduplicated",
decisions[0].reason, str({"calculation_id": calculation, "machine_id": "generic",
"timestamp": str(at(hour))}))
for hour in (11, 12, 13)
]
assert reconcile_machine(*args)[1] == 0
def test_application_without_target_updates_normally(sqlite_schema):
database, repository = application_repository(sqlite_schema)
insert_application(database, "calc", 12, "old", "old-run", 42.5)
assert reconcile_machine(*application_reconcile_args(repository))[1] == 1
assert database.execute(
"SELECT production_order, run_id, application_g_m2 FROM material_application_snapshots"
).fetchone() == ("Machine-123", "old-run", 42.5)
assert database.execute(
"SELECT action, retained_run_id FROM historical_assignment_audit"
).fetchone() == ("updated", None)
@pytest.mark.parametrize("target_value,target_run", [
(99.0, "source-run"), (42.5, "unexpected-run"),
])
def test_application_collision_rolls_back_whole_machine(
sqlite_schema, target_value, target_run,
):
database, repository = application_repository(sqlite_schema)
for hour in (11, 12):
insert_application(database, "calc", hour, "old", "old-run", 42.5)
insert_application(database, "calc", hour, "Machine-123", "source-run" if hour == 11
else target_run, 42.5 if hour == 11 else target_value)
with pytest.raises(RuntimeError, match="conflicting measurement|unexpected target run"):
reconcile_machine(*application_reconcile_args(repository))
assert application_rows(database, "calc") == 4
assert database.execute("SELECT count(*) FROM historical_assignment_audit").fetchone() == (0,)
def application_repository(sqlite_schema):
import sqlite3
database = sqlite3.connect(":memory:")
database.executescript(sqlite_schema)
class Connection:
def __enter__(self):
return self
def __exit__(self, exc_type, *_):
database.rollback() if exc_type else database.commit()
def execute(self, statement, parameters=()):
statement = statement if isinstance(statement, str) else statement.as_string()
if statement.startswith(("SET TRANSACTION", "SELECT pg_advisory")):
return None
parameters = tuple(
str(p.obj) if hasattr(p, "obj") else p.isoformat()
if isinstance(p, datetime) else p for p in parameters
)
return database.execute(statement.replace(" FOR UPDATE", "").replace("%s", "?"),
parameters)
class Repository(PostgresHistoricalRepository):
def connect(self):
return Connection()
def read(self, machine_id, start, end):
return [replace(r, timestamp=datetime.fromisoformat(r.timestamp),
identity=(*r.identity[:2], datetime.fromisoformat(r.identity[2])))
for r in super().read(machine_id, start, end)]
return database, Repository(None)
def insert_application(database, calculation, hour, order, run_id, value):
database.execute("INSERT INTO material_application_snapshots VALUES (?, ?, ?, ?, ?, ?)",
(at(hour).isoformat(), calculation, "generic", order, run_id, value))
database.commit()
def application_rows(database, calculation):
return database.execute(
"SELECT count(*) FROM material_application_snapshots WHERE calculation_id = ?",
(calculation,),
).fetchone()[0]
def application_reconcile_args(repository):
source = SimpleNamespace(get_production_runs=lambda machine: [run()])
erp = SimpleNamespace(get_confirmations=lambda **kwargs: [confirmation()])
config = SimpleNamespace(machine_id="generic", erp_workplace="workplace")
return repository, source, erp, config, "Machine-{production_order}", at(10), at(14)
+1
View File
@@ -120,6 +120,7 @@ def test_runtime_isolation_and_disjoint_runs(tmp_path, monkeypatch):
assert separate.service._signal_discharge == (
configs[0].specific_discharge_kg_per_signal_unit_m)
assert separate.service._nominal_width_provider.format_template == 'Bento 1-{production_order}'
assert separate.service._nominal_width_provider.fallback_nominal_width_m == 5.0
machine = configs[0].machine_ref
order = 'Bento 1-test'
separate_path = separate.service._state_store.store._path(machine, order)
+215
View File
@@ -0,0 +1,215 @@
import traceback
from datetime import UTC, datetime, timedelta
from unittest.mock import MagicMock
import pytest
from production_analytics.service.postgres_material import PostgresSettings
from production_analytics.service.postgres_shift_material import (
PostgresShiftChannelMaterialRepository,
PostgresShiftMaterialRepository,
ShiftMaterialReadError,
)
START = datetime(2026, 10, 7, 4, tzinfo=UTC)
END = START + timedelta(hours=8)
@pytest.fixture(params=[False, True], ids=["machine", "channel"])
def db(request, monkeypatch):
connect = MagicMock()
monkeypatch.setattr("psycopg.connect", connect)
connection = connect.return_value.__enter__.return_value
channel = request.param
row = (
(
START,
"calc",
"machine",
"Ex1",
"C2",
"order",
"run",
123.0,
None,
None,
"UNAVAILABLE",
True,
)
if channel
else (START, "calc", "machine", "order", "run", 123.0)
)
connection.execute.return_value.fetchall.return_value = [row]
cls = PostgresShiftChannelMaterialRepository if channel else PostgresShiftMaterialRepository
return (
cls(PostgresSettings("localhost", 5432, "db", "user", "pw")),
connect,
connection,
channel,
)
def read(repository, **changes):
return repository.get_snapshots(
**{
"machine_id": "machine",
"calculation_ids": ("calc",),
"start": START,
"end": END,
**changes,
}
)
def test_one_query_parameterization_baseline_and_strict_end(db):
repository, connect, connection, channel = db
snapshots = read(repository)
sql, params = connection.execute.call_args.args
assert params == ("machine", ["calc"], START, END)
assert "timestamp <= r.start_time" in sql
assert "timestamp > r.start_time AND timestamp < r.end_time" in sql
assert "UNION ALL" in sql
assert "EXISTS" not in sql and "DENSE_RANK" not in sql and "scoped" not in sql
assert "MIN(" not in sql and "MAX(" not in sql
assert "calculation_id = ANY(r.calculation_ids)" in sql
assert ("FROM channel_material_consumption_snapshots" in sql) is channel
assert ("FROM material_consumption_snapshots" in sql) is not channel
if channel:
assert "DISTINCT ON (s.calculation_id, extruder, doser_channel)" in sql
assert "ORDER BY s.calculation_id, extruder, doser_channel, timestamp DESC" in sql
else:
assert "unnest(r.calculation_ids)" in sql
assert "calculation_id = ids.calculation_id AND machine_id = r.machine_id" in sql
assert "ORDER BY timestamp DESC, run_id, production_order" in sql
assert "LIMIT 1" in sql
# Valid baseline filters never affect the in-window branch, which must keep
# null, non-finite, and negative counters for run/reset validation.
baseline, window = sql.split("UNION ALL")
counter = "cumulative_consumption_kg" if channel else "consumption_kg"
assert f"{counter} >= 0" in baseline
assert f"{counter} < 'Infinity'::double precision" in baseline
assert f"{counter} >=" not in window and f"{counter} <" not in window
order = "calculation_id, " + ("extruder, doser_channel, " if channel else "")
assert sql.rstrip().endswith(f"ORDER BY {order}timestamp, run_id, production_order")
connection.execute.assert_called_once()
connection.execute.return_value.fetchall.assert_called_once()
connect.assert_called_once_with(
host="localhost",
port=5432,
dbname="db",
user="user",
password="pw",
connect_timeout=10,
options="-c statement_timeout=10000",
)
connect.return_value.__exit__.assert_called_once()
assert snapshots[0].run_id == "run"
assert snapshots[0].timestamp is START
if channel:
assert snapshots[0].material_name is None
assert snapshots[0].doser_channel == "C2"
assert snapshots[0].material_mapping_status == "UNAVAILABLE"
connection.commit.assert_not_called()
def test_parameterized_multiple_calculations(db):
ids = ("calc'; DELETE FROM x; --", "second")
read(db[0], calculation_ids=ids)
sql, params = db[2].execute.call_args.args
assert params[1] == list(ids)
assert ids[0] not in sql
def test_validation_before_connect(db):
for changes in (
{"start": START.replace(tzinfo=None)},
{"end": START},
{"machine_id": "bad\x00"},
{"calculation_ids": ()},
):
with pytest.raises(ValueError):
read(db[0], **changes)
db[1].assert_not_called()
def test_empty_result(db):
db[2].execute.return_value.fetchall.return_value = []
assert read(db[0]) == []
@pytest.mark.parametrize("stage", ["connect", "execute", "fetch", "close"])
def test_safe_driver_errors(db, stage):
repository, connect, connection, _ = db
target = {
"connect": connect,
"execute": connection.execute,
"fetch": connection.execute.return_value.fetchall,
"close": connect.return_value.__exit__,
}[stage]
target.side_effect = RuntimeError("private-password")
with pytest.raises(ShiftMaterialReadError, match="read failed") as error:
read(repository)
assert "private-password" not in "".join(traceback.format_exception(error.value))
def test_invalid_row_shape_wrapped(db):
db[2].execute.return_value.fetchall.return_value = [("bad",)]
with pytest.raises(ShiftMaterialReadError, match="invalid row"):
read(db[0])
def test_multiple_baselines_and_raw_window_rows_are_preserved(db):
repository, _, connection, channel = db
original = connection.execute.return_value.fetchall.return_value[0]
counter_index = 7 if channel else 5
def row(timestamp, value, calculation="calc", stream="C2"):
values = list(original)
values[0], values[1], values[counter_index] = timestamp, calculation, value
if channel:
values[4] = stream
return tuple(values)
# A baseline per calculation (and per channel), exact-start baseline, and
# raw null/reset rows all survive repository decoding without carry-forward.
rows = [
row(START, 100),
row(START + timedelta(seconds=1), None),
row(START + timedelta(seconds=2), -1),
row(END - timedelta(microseconds=1), 110),
]
if channel:
rows += [row(START, 200, stream="C3"), row(START + timedelta(seconds=1), 205, stream="C3")]
rows += [row(START - timedelta(seconds=1), 300, calculation="second")]
connection.execute.return_value.fetchall.return_value = rows
snapshots = read(repository, calculation_ids=("calc", "second"))
assert [snapshot.timestamp for snapshot in snapshots] == [row[0] for row in rows]
counter = "cumulative_consumption_kg" if channel else "consumption_kg"
assert [getattr(snapshot, counter) for snapshot in snapshots] == [
row[counter_index] for row in rows
]
assert {snapshot.calculation_id for snapshot in snapshots} == {"calc", "second"}
if channel:
assert {snapshot.doser_channel for snapshot in snapshots} == {"C2", "C3"}
assert all(snapshot.material_name is None for snapshot in snapshots)
connection.execute.assert_called_once()
def test_missing_baseline_leaves_in_window_sample_for_fallback(db):
repository, _, connection, _ = db
values = list(connection.execute.return_value.fetchall.return_value[0])
values[0] = START + timedelta(minutes=1)
connection.execute.return_value.fetchall.return_value = [tuple(values)]
snapshots = read(repository)
assert len(snapshots) == 1
assert snapshots[0].timestamp == START + timedelta(minutes=1)
from production_analytics.calculations.shift_material import (
aggregate_shift_channel_material,
aggregate_shift_material,
)
aggregate = aggregate_shift_channel_material if db[3] else aggregate_shift_material
summary = aggregate(snapshots, machine_id="machine", calculation_ids=("calc",),
start=START, end=END)
assert summary.total_consumption_kg == 0
assert summary.items[0].baseline_missing
+287
View File
@@ -0,0 +1,287 @@
"""Order search, shift assignment, and read-only web routes use fake ERP rows."""
from datetime import date, datetime
from unittest.mock import MagicMock
from urllib.parse import urlencode
from wsgiref.util import setup_testing_defaults
from zoneinfo import ZoneInfo
import pytest
from production_analytics import web
from production_analytics.erp.gateway import (
ErpProductionConfirmationGateway,
ErpSettings,
OrderConfirmationGroup,
OrderConfirmationRow,
ProductionConfirmation,
)
from production_analytics.presentation.production_order_html import render_detail, render_search
from production_analytics.service.production_order import ProductionOrderService
from production_analytics.service.shift_report_config import load_shift_report_machines
ORDER = "82026400900"
BERLIN = ZoneInfo("Europe/Berlin")
MALAYSIA = ZoneInfo("Asia/Kuala_Lumpur")
MACHINES = load_shift_report_machines("config/shift-report-machines.yaml")
def row(hour, minute, *, workplace="GITTERIII", day=19, amount=10,
order=ORDER, article="A"):
return OrderConfirmationRow(order, workplace, article, "Article name",
datetime(2026, 10, day, hour, minute), amount)
class FakeGateway:
def __init__(self, rows=(), groups=(), shift_rows=None):
self.rows = list(rows)
self.shift_rows = list(rows if shift_rows is None else shift_rows)
self.groups = list(groups)
self.calls = []
def search_orders(self, query, *, limit=25):
self.calls.append(("search", query, limit))
return self.groups
def get_order_confirmations(self, production_order):
self.calls.append(("detail", production_order))
return self.rows
def get_confirmations(self, *, workplace, start, end, timezone):
self.calls.append(("shift", workplace, start, end, timezone))
return [ProductionConfirmation(
workplace=value.workplace, production_order=value.production_order,
timestamp=value.timestamp_local.replace(tzinfo=timezone),
article_number=value.article_number,
article_description=value.article_description,
roll_number=None, production_quantity_m2=None,
feedback_quantity_m2=value.feedback_quantity_m2,
raw_material_number=None, raw_material_description=None, batch_number=None,
raw_material_quantity=None, tenant=None,
) for value in self.shift_rows if value.workplace == workplace and
start <= value.timestamp_local.replace(tzinfo=timezone) < end]
def group(order=ORDER, workplace="GITTERIII", article="A"):
return OrderConfirmationGroup(order, workplace, article, "Article name",
datetime(2026, 10, 19, 6), datetime(2026, 10, 19, 14))
def test_search_trims_and_collapses_rows_by_fa_with_multiple_workplaces():
gateway = FakeGateway(groups=[group(workplace="BENTO 1"), group(),
group("82026400901"), group(article="B")])
result = ProductionOrderService(gateway, MACHINES).search(" 82026400900 ")
assert gateway.calls == [("search", ORDER, 25)]
assert [entry.production_order for entry in result] == [ORDER, "82026400901"]
assert len(result[0].placements) == 3
assert {place.machine_name for place in result[0].placements} == {"B1", "Gitter 3"}
assert {place.timezone for place in result[0].placements} == {BERLIN}
def test_search_limit_and_order_are_deterministic_even_with_unsorted_gateway():
groups = [group("8202642"), group("8202641"), group("8202643"), group("8202641")]
service = ProductionOrderService(FakeGateway(groups=groups), MACHINES)
assert [value.production_order for value in service.search("820264", limit=2)] == [
"8202641", "8202642"]
assert [value.production_order for value in service.search("8202642", limit=2)] == [
"8202642", "8202641"]
@pytest.mark.parametrize("query", ["", " ", "\x00", "x" * 81])
def test_blank_or_invalid_search_never_queries_gateway(query):
gateway = FakeGateway()
with pytest.raises(ValueError):
ProductionOrderService(gateway, MACHINES).search(query)
assert gateway.calls == []
def test_unknown_workplace_is_visible_without_shift_assignment():
gateway = FakeGateway(rows=[row(7, 0, workplace="UNCONFIGURED")],
groups=[group(workplace="UNCONFIGURED")])
service = ProductionOrderService(gateway, MACHINES)
placement = service.search(ORDER)[0].placements[0]
assert placement.mapping_status == "unknown"
assert placement.machine_name is placement.site is placement.timezone is None
detail = service.detail(ORDER)
assert detail.placements[0].mapping_status == "unknown"
assert detail.shifts == ()
def test_ambiguous_workplace_is_visible_without_arbitrary_machine_choice():
from dataclasses import replace
machines = {"B1": MACHINES["B1"],
"Other": replace(MACHINES["B1"], display_name="Other")}
service = ProductionOrderService(FakeGateway(rows=[row(7, 0, workplace="BENTO 1")],
groups=[group(workplace="BENTO 1")]), machines)
assert service.search(ORDER)[0].placements[0].mapping_status == "ambiguous"
assert service.detail(ORDER).shifts == ()
def test_one_shift_aggregates_positive_feedback_and_confirmation_bounds():
service = ProductionOrderService(FakeGateway(rows=[row(6, 1, amount=2),
row(13, 59, amount=3)]), MACHINES)
detail = service.detail(ORDER)
assert len(detail.shifts) == 1
item = detail.shifts[0]
assert (item.machine_name, item.site, item.date, item.shift, item.produced_m2) == (
"Gitter 3", "adorf", date(2026, 10, 19), "early", 5)
assert (item.first_confirmation.hour, item.last_confirmation.hour) == (6, 13)
assert (item.shift_start.hour, item.shift_end.hour) == (6, 14)
def test_two_shifts_and_night_across_midnight():
rows = [row(13, 59), row(14, 0), row(22, 0), row(5, 59, day=20),
row(6, 0, day=20)]
shifts = ProductionOrderService(FakeGateway(rows=rows), MACHINES).detail(ORDER).shifts
assert [(item.date, item.shift, item.produced_m2) for item in shifts] == [
(date(2026, 10, 19), "early", 10),
(date(2026, 10, 19), "late", 10),
(date(2026, 10, 19), "night", 20),
(date(2026, 10, 20), "early", 10),
]
assert shifts[2].shift_end == datetime(2026, 10, 20, 6, tzinfo=BERLIN)
def test_same_fa_on_multiple_machines_uses_each_site_timezone():
rows = [row(7, 0), row(7, 0, workplace="K1", amount=4)]
shifts = ProductionOrderService(FakeGateway(rows=rows), MACHINES).detail(ORDER).shifts
assert len(shifts) == 2
assert {(item.machine_name, item.timezone) for item in shifts} == {
("Gitter 3", BERLIN), ("K1", MALAYSIA)}
assert shifts[0].shift_start.astimezone(ZoneInfo("UTC")) != (
shifts[1].shift_start.astimezone(ZoneInfo("UTC")))
def test_malaysia_before_six_belongs_to_previous_night_start_date():
shift = ProductionOrderService(FakeGateway(rows=[row(5, 45, workplace="K1",
day=20)]), MACHINES).detail(ORDER).shifts[0]
assert (shift.date, shift.shift, shift.timezone) == (
date(2026, 10, 19), "night", MALAYSIA)
assert shift.shift_start == datetime(2026, 10, 19, 22, tzinfo=MALAYSIA)
assert shift.shift_end == datetime(2026, 10, 20, 6, tzinfo=MALAYSIA)
def web_request(app, path, query="", method="GET"):
env = {}
setup_testing_defaults(env)
env.update(PATH_INFO=path, QUERY_STRING=query, REQUEST_METHOD=method)
result = []
body = b"".join(app(env, lambda status, headers: result.append((status, headers))))
return result[0][0], body.decode()
def test_search_and_detail_web_pages_and_encoded_report_link():
gateway = FakeGateway(rows=[row(7, 0)], groups=[group()])
service = ProductionOrderService(gateway, MACHINES)
app = web.create_app(MACHINES, lambda: None,
order_service_factory=lambda: service)
status, text = web_request(app, "/orders")
assert status == "200 OK" and "Fertigungsauftrag suchen" in text
assert gateway.calls == []
status, text = web_request(app, "/orders", urlencode({"q": " 820264 "}))
assert status == "200 OK" and ORDER in text and "/order?production_order=" in text
status, text = web_request(app, "/order", urlencode({"production_order": ORDER}))
assert status == "200 OK"
assert '<a href="/orders" aria-current="page">Fertigungsauftrag</a>' in text
assert "Article name" in text and "10.00 m²" in text
assert "Schichtbericht" in text
assert "/?date=2026-10-19&amp;shift=early&amp;machine=Gitter+3" in text
@pytest.mark.parametrize("html", [render_search(), render_detail(detail=None)],
ids=["search", "detail"])
def test_order_pages_mark_order_mode_active(html):
assert '<nav class="mode-nav" aria-label="Bereich wählen">' in html
assert '<a href="/">Schichtbericht</a>' in html
assert '<a href="/orders" aria-current="page">Fertigungsauftrag</a>' in html
assert html.split("</style>", 1)[1].count('aria-current="page"') == 1
assert ".mode-nav a:focus-visible" in html
def test_order_pages_escape_erp_text():
unsafe = "<script>alert(1)</script>"
gateway = FakeGateway(
rows=[OrderConfirmationRow(ORDER, "GITTERIII", "A", unsafe,
datetime(2026, 10, 19, 7), 1)],
groups=[OrderConfirmationGroup(ORDER, "GITTERIII", "A", unsafe,
datetime(2026, 10, 19, 7),
datetime(2026, 10, 19, 7))],
)
app = web.create_app(MACHINES, lambda: None,
order_service_factory=lambda: ProductionOrderService(gateway, MACHINES))
for path, query in (("/orders", "q=820264"), ("/order", f"production_order={ORDER}")):
assert "<script>" not in web_request(app, path, query)[1]
assert "&lt;script&gt;" in web_request(app, path, query)[1]
@pytest.mark.parametrize("path,query,status", [
("/orders", "q=", "400 Bad Request"),
("/order", "", "400 Bad Request"),
("/order", "production_order=", "400 Bad Request"),
("/orders", "q=a&q=b", "400 Bad Request"),
("/orders", "extra=1", "400 Bad Request"),
])
def test_malformed_web_parameters_do_not_query(path, query, status):
gateway = FakeGateway()
service = ProductionOrderService(gateway, MACHINES)
app = web.create_app(MACHINES, lambda: None, order_service_factory=lambda: service)
actual, _ = web_request(app, path, query)
assert actual == status
assert gateway.calls == []
def test_order_web_errors_are_safe():
def fail():
raise RuntimeError("password=secret.internal")
app = web.create_app(MACHINES, lambda: None, order_service_factory=fail)
status, body = web_request(app, "/orders", "q=820264")
assert status == "503 Service Unavailable"
assert "secret.internal" not in body
assert web_request(app, "/order", "production_order=820264")[0] == (
"503 Service Unavailable")
assert web_request(app, "/orders", "q=820264", method="POST")[0] == (
"405 Method Not Allowed")
def test_missing_order_returns_404_without_source_details():
gateway = FakeGateway()
app = web.create_app(MACHINES, lambda: None, order_service_factory=lambda: (
ProductionOrderService(gateway, MACHINES)))
status, body = web_request(app, "/order", f"production_order={ORDER}")
assert status == "404 Not Found"
assert "nicht gefunden" in body
def test_gateway_search_is_parameterized_bounded_and_escapes_like(monkeypatch):
connect = MagicMock()
monkeypatch.setattr("production_analytics.erp.gateway.pymssql.connect", connect)
cursor = connect.return_value.__enter__.return_value.cursor.return_value.__enter__.return_value
cursor.fetchall.return_value = [
(ORDER, "GITTERIII", "A", "Article name", datetime(2026, 10, 19, 6),
datetime(2026, 10, 19, 14)),
(ORDER, "K1", "A", "Article name", datetime(2026, 10, 19, 6),
datetime(2026, 10, 19, 14)),
]
gateway = ErpProductionConfirmationGateway(ErpSettings("host", 1433, "db", "u", "p"))
result = gateway.search_orders(" 820264%_ ", limit=12)
assert len(result) == 2
sql, params = cursor.execute.call_args.args
assert "TOP (%s)" in sql and "GROUP BY" in sql
assert params == (12, "%820264\\%\\_%", "820264%_", "820264%_")
assert "820264%_" not in sql
assert connect.return_value.__exit__.called
def test_gateway_detail_uses_exact_fa_and_reuses_positive_feedback_semantics(monkeypatch):
connect = MagicMock()
monkeypatch.setattr("production_analytics.erp.gateway.pymssql.connect", connect)
cursor = connect.return_value.__enter__.return_value.cursor.return_value.__enter__.return_value
cursor.fetchall.return_value = [(ORDER, "GITTERIII", "A", "Article name",
datetime(2026, 10, 19, 7), 3)]
gateway = ErpProductionConfirmationGateway(ErpSettings("host", 1433, "db", "u", "p"))
assert gateway.get_order_confirmations(" " + ORDER + " ")[0].feedback_quantity_m2 == 3
sql, params = cursor.execute.call_args.args
assert params == (ORDER,)
assert "[Fertigungsauftragsnummer] = %s" in sql
assert "[Rückmeldemenge] > 0" in sql
+380
View File
@@ -0,0 +1,380 @@
"""Approximate FA windows feed existing speed and material services."""
from dataclasses import replace
from datetime import datetime
from math import fsum
from types import SimpleNamespace
import pytest
from test_production_order import BERLIN, MACHINES, FakeGateway, row
from test_shift_report import composition
from production_analytics.calculations.fiber_allocation import FiberBooking
from production_analytics.calculations.shift_material import (
ShiftMaterialItem,
ShiftMaterialSnapshot,
ShiftMaterialSummary,
)
from production_analytics.enlyze.exploration import ExplorationError
from production_analytics.presentation.production_order_html import render_detail
from production_analytics.presentation.shift_report import TableBlock, present_report
from production_analytics.service.fiber_allocation import K7FiberAllocationService
from production_analytics.service.postgres_shift_material import ShiftMaterialReadError
from production_analytics.service.production_order import ProductionOrderService
from production_analytics.service.shift_material import ShiftMaterialService
A, B, C = "FA-A", "FA-B", "FA-C"
class Speed:
def __init__(self, count=2, error=None):
self.calls = []
self.count = count
self.error = error
def summarize(self, *, config, start, end):
self.calls.append((config, start, end))
if self.error:
raise self.error
speed = float(start.hour + 1) if self.count else None
return SimpleNamespace(average_line_speed_m_min=speed,
active_sample_count=self.count)
class Material:
def __init__(self, value=0, error=None):
self.calls = []
self.value = value
self.error = error
def summarize(self, *, machine_id, calculation_ids, start, end):
self.calls.append((machine_id, calculation_ids, start, end))
if self.error:
raise self.error
value = self.value(start, end) if callable(self.value) else self.value
return SimpleNamespace(total_consumption_kg=value, items=())
def service(selected, all_rows, *, speed=None, materials=None, machines=MACHINES):
return ProductionOrderService(FakeGateway(rows=selected, shift_rows=all_rows), machines,
speed=speed, materials=materials)
def b1(hour, minute=0, *, order=A, day=19, amount=10):
return row(hour, minute, workplace="BENTO 1", order=order, day=day, amount=amount)
def windows(detail):
return [(part.start, part.end) for shift in detail.shifts for part in shift.segments]
def test_one_fa_occupies_full_shift_and_sources_receive_segment_window():
speed, material = Speed(), Material(12)
detail = service([b1(9)], [b1(9)], speed=speed, materials=material).detail(A)
shift = detail.shifts[0]
assert windows(detail) == [(datetime(2026, 10, 19, 6, tzinfo=BERLIN),
datetime(2026, 10, 19, 14, tzinfo=BERLIN))]
assert speed.calls[0][1:] == windows(detail)[0]
assert material.calls[0][2:] == windows(detail)[0]
assert (shift.average_speed_m_min, shift.material_consumption_kg) == (7, 12)
def test_two_fas_have_distinct_nonoverlapping_windows_and_kpis():
a, b = b1(7, order=A), b1(11, order=B)
speed, material = Speed(), Material(lambda start, end: 5 if start.hour == 6 else 12)
service_a = service([a], [a, b], speed=speed, materials=material)
service_b = service([b], [a, b], speed=speed, materials=material)
first, second = service_a.detail(A).shifts[0], service_b.detail(B).shifts[0]
assert first.segments[0].start.hour == 6
assert first.segments[0].end.hour == 9
assert second.segments[0].start == first.segments[0].end
assert second.segments[0].end.hour == 14
assert (first.average_speed_m_min, second.average_speed_m_min) == (7, 10)
assert (first.material_consumption_kg, second.material_consumption_kg) == (5, 12)
assert speed.calls[0][1:] == (first.segments[0].start, first.segments[0].end)
assert material.calls[1][2:] == (second.segments[0].start, second.segments[0].end)
def test_shift_report_and_order_detail_use_same_kpi_attribution():
a, b = b1(7, order=A), b1(11, order=B)
speed, material = Speed(), Material(lambda start, end: 5 if start.hour == 6 else 12)
order_service = service([a], [a, b], speed=speed, materials=material)
start = datetime(2026, 10, 19, 6, tzinfo=BERLIN)
end = datetime(2026, 10, 19, 14, tzinfo=BERLIN)
shift_kpis = order_service.for_shift(machine_name="B1", start=start, end=end,
orders=(A, B))
detail = order_service.detail(A).shifts[0]
assert shift_kpis[A].segments == detail.segments
assert shift_kpis[A].average_speed_m_min == detail.average_speed_m_min
assert shift_kpis[A].material_consumption_kg == detail.material_consumption_kg
assert shift_kpis[B].segments[0].start == shift_kpis[A].segments[0].end
assert shift_kpis[A].material_consumption_kg + shift_kpis[B].material_consumption_kg == 17
def test_three_sequential_fas_and_midpoints_are_clamped():
a, b, c = b1(6, order=A), b1(9, order=B), b1(13, order=C)
details = [service([selected], [a, b, c]).detail(selected.production_order)
for selected in (a, b, c)]
segments = [detail.shifts[0].segments[0] for detail in details]
assert [part.start.strftime("%H:%M") for part in segments] == ["06:00", "07:30", "11:00"]
assert [part.end.strftime("%H:%M") for part in segments] == ["07:30", "11:00", "14:00"]
assert all(left.end == right.start for left, right in zip(segments, segments[1:]))
def test_repeated_adjacent_fa_rows_keep_one_segment_and_sum_production():
a1, a2, b = b1(7, order=A, amount=3), b1(8, order=A, amount=4), b1(10, order=B)
detail = service([a1, a2], [a1, a2, b]).detail(A)
assert len(detail.shifts) == len(detail.shifts[0].segments) == 1
assert detail.shifts[0].produced_m2 == 7
assert detail.shifts[0].segments[0].end.hour == 9
def test_alternating_fa_confirmation_runs_remain_two_disjoint_segments():
a1, b, a2 = b1(7, order=A), b1(9, order=B), b1(11, order=A)
speed, material = Speed(), Material(4)
detail = service([a1, a2], [a1, b, a2], speed=speed, materials=material).detail(A)
parts = detail.shifts[0].segments
assert len(parts) == 2
assert parts[0].end.hour == 8 and parts[1].start.hour == 10
assert parts[0].end < parts[1].start
assert len(speed.calls) == len(material.calls) == 2
assert detail.shifts[0].material_consumption_kg == 8
assert detail.shifts[0].average_speed_m_min == 9
def test_simultaneous_three_fa_tie_gives_middle_order_unavailable_kpis():
a, b, c = (b1(9, order=order) for order in (A, B, C))
speed, material = Speed(), Material(4)
shift = service([b], [a, b, c], speed=speed, materials=material).detail(B).shifts[0]
assert shift.produced_m2 == 10
assert shift.segments == ()
assert shift.average_speed_m_min is shift.material_consumption_kg is None
assert speed.calls == material.calls == []
def test_cross_shift_and_night_keep_separate_kpis():
first = b1(21, order=A)
second = b1(1, order=A, day=20)
speed, material = Speed(), Material(3)
detail = service([first, second], [first, second], speed=speed, materials=material).detail(A)
assert [(item.date.day, item.shift) for item in detail.shifts] == [
(19, "late"), (19, "night")]
assert detail.shifts[0].segments[0].end.hour == 22
assert detail.shifts[1].segments[0].start.hour == 22
assert detail.shifts[1].segments[0].end == datetime(2026, 10, 20, 6, tzinfo=BERLIN)
assert [item.material_consumption_kg for item in detail.shifts] == [3, 3]
assert len(speed.calls) == len(material.calls) == 2
def test_disabled_capabilities_never_query_optional_sources():
k1 = row(7, 0, workplace="K1", order=A)
speed, material = Speed(), Material(10)
shift = service([k1], [k1], speed=speed, materials=material).detail(A).shifts[0]
assert shift.average_speed_m_min is shift.material_consumption_kg is None
assert speed.calls == material.calls == []
gitter = row(7, 0, workplace="GITTERIII", order=A)
service([gitter], [gitter], speed=speed, materials=material).detail(A)
assert len(speed.calls) == 1 and material.calls == []
@pytest.mark.parametrize("workplace,machine", [("GITTERIII", "Gitter 3"), ("K5", "K5")])
def test_machine_speed_gate_configuration_is_forwarded_unchanged(workplace, machine):
confirmation = row(7, 0, workplace=workplace, order=A)
speed = Speed()
shift = service([confirmation], [confirmation], speed=speed).detail(A).shifts[0]
assert speed.calls[0][0] is MACHINES[machine].speed
assert shift.average_speed_m_min == 7
def test_channel_material_uses_existing_channel_path():
e1 = row(7, 0, workplace="1568705", order=A)
cumulative, channel = Material(99), Material(6)
order_service = ProductionOrderService(
FakeGateway(rows=[e1]), MACHINES, materials=cumulative,
channel_materials=channel)
shift = order_service.detail(A).shifts[0]
assert shift.material_consumption_kg == 6
assert cumulative.calls == [] and len(channel.calls) == 1
def test_order_aware_allocator_uses_full_shift_summary():
k7 = row(7, 0, workplace="K7", order=A)
material = Material(9)
class Allocator:
def __init__(self):
self.calls = []
def allocate(self, measured):
self.calls.append(measured)
return measured
def totals_by_order(self, allocated):
return {A: allocated.total_consumption_kg}
allocator = Allocator()
order_service = ProductionOrderService(
FakeGateway(rows=[k7]), MACHINES, materials=material,
material_allocators={"K7": allocator})
shift = order_service.detail(A).shifts[0]
assert shift.material_consumption_kg == 9
assert len(allocator.calls) == 1
assert material.calls[0][2:] == (shift.shift_start, shift.shift_end)
def test_k7_compact_material_matches_allocated_shift_items_not_time_segments():
first_order, second_order = "12026001032", "12026001037"
start = datetime(2026, 10, 13, 14, tzinfo=BERLIN)
end = datetime(2026, 10, 13, 22, tzinfo=BERLIN)
config = MACHINES["K7"]
template = ShiftMaterialItem(
source="material_consumption_snapshots",
calculation_id=config.material.calculation_ids[0], machine_id=config.machine_id,
production_order=f"K 7-{first_order}", run_id="run", consumption_kg=3317.58,
baseline_timestamp=start, end_timestamp=end, baseline_missing=False,
)
measured = ShiftMaterialSummary(
config.machine_id, start, end, 5180.94,
(template, replace(template, production_order=f"K 7-{second_order}",
consumption_kg=1863.36)),
)
class Bookings:
def get_fiber_bookings(self, order):
amounts = ((2288.71, 1028.87) if order == first_order else (1312.62, 550.74))
return [FiberBooking(order, str(index), f"Fiber {index}", amount)
for index, amount in enumerate(amounts)]
allocator = K7FiberAllocationService(Bookings())
service, stubs, _, _ = composition("K7")
stubs["materials"].result = measured
first = row(15, 0, day=13, workplace="K7", order=first_order)
second = row(20, 0, day=13, workplace="K7", order=second_order)
order_service = ProductionOrderService(
FakeGateway(rows=[first], shift_rows=[first, second]), MACHINES,
speed=Speed(), materials=stubs["materials"],
material_allocators={"K7": allocator},
)
service.order_kpis = order_service
service.material_allocators = {"K7": allocator}
production = stubs["production"].result
production_items = tuple(
replace(production.items[0], production_order=order,
first_confirmation_at=start, last_confirmation_at=start)
for order in (first_order, second_order)
)
stubs["production"].result = replace(production, items=production_items)
report = service.build(machine_name="K7", start=start, end=end)
assert [item.material_consumption_kg for item in report.production.items] == pytest.approx(
[3317.58, 1863.36])
assert report.materials.total_consumption_kg == pytest.approx(5180.94)
assert fsum(item.consumption_kg for item in report.materials.items) == pytest.approx(5180.94)
assert len(report.materials.items) == 4
assert [item.consumption_kg for item in report.materials.items] == pytest.approx(
[2288.71, 1028.87, 1312.62, 550.74])
material_calls = [kwargs for name, kwargs in stubs["materials"].calls if name == "materials"]
assert material_calls == [{"machine_id": config.machine_id,
"calculation_ids": config.material.calculation_ids,
"start": start, "end": end}]
table = next(block for block in present_report(report)
if isinstance(block, TableBlock) and "Ø Geschwindigkeit" in block.headers)
assert [entry[-1] for entry in table.rows] == ["3.317,58 kg", "1.863,36 kg"]
material_table = next(block for block in present_report(report)
if isinstance(block, TableBlock) and "ERP-Anteil" in block.headers)
assert [entry[3] for entry in material_table.rows] == [
"2.288,71 kg", "1.028,87 kg", "1.312,62 kg", "550,74 kg"]
assert len(order_service.speed.calls) == 2
assert order_service.speed.calls[0][2] == order_service.speed.calls[1][1]
assert order_service.detail(first_order).shifts[0].material_consumption_kg == pytest.approx(
3317.58)
def test_k7_allocated_zero_remains_zero_and_absent_order_is_unavailable():
start = datetime(2026, 10, 13, 14, tzinfo=BERLIN)
end = datetime(2026, 10, 13, 22, tzinfo=BERLIN)
config = MACHINES["K7"]
item = ShiftMaterialItem(
source="material_consumption_snapshots",
calculation_id=config.material.calculation_ids[0], machine_id=config.machine_id,
production_order="K 7-12026001032", run_id="run", consumption_kg=0,
baseline_timestamp=start, end_timestamp=end, baseline_missing=False,
)
allocated = ShiftMaterialSummary(config.machine_id, start, end, 0, (item,))
allocator = K7FiberAllocationService(SimpleNamespace(get_fiber_bookings=lambda order: []))
first = row(15, 0, day=13, workplace="K7", order="12026001032")
second = row(20, 0, day=13, workplace="K7", order="12026001037")
order_service = ProductionOrderService(
FakeGateway(shift_rows=[first, second]), MACHINES,
material_allocators={"K7": allocator},
)
kpis = order_service.for_shift(
machine_name="K7", start=start, end=end,
orders=(first.production_order, second.production_order),
allocated_shift_materials=allocated,
)
assert kpis[first.production_order].material_consumption_kg == 0
assert kpis[second.production_order].material_consumption_kg is None
def test_no_active_speed_is_unavailable_and_material_zero_is_not():
speed, material = Speed(count=0), Material(0)
shift = service([b1(7)], [b1(7)], speed=speed, materials=material).detail(A).shifts[0]
assert shift.average_speed_m_min is None
assert shift.material_consumption_kg == 0
html = render_detail(detail=service([b1(7)], [b1(7)], speed=speed,
materials=material).detail(A))
assert "Ø Geschwindigkeit" in html and "Materialverbrauch" in html
assert "<td>—</td>" in html and "<td>0,00 kg</td>" in html
def test_order_html_formats_per_shift_kpis_in_german():
detail = service([b1(7)], [b1(7)]).detail(A)
enriched = replace(detail, shifts=(replace(detail.shifts[0],
average_speed_m_min=4.77,
material_consumption_kg=1234),))
html = render_detail(detail=enriched)
assert "<td>4,77 m/min</td>" in html
assert "<td>1.234,00 kg</td>" in html
def test_optional_source_failure_degrades_only_that_kpi():
speed = Speed(error=ExplorationError("unavailable"))
material = Material(2)
shift = service([b1(7)], [b1(7)], speed=speed, materials=material).detail(A).shifts[0]
assert shift.average_speed_m_min is None and shift.material_consumption_kg == 2
speed = Speed()
material = Material(error=ShiftMaterialReadError("unavailable"))
shift = service([b1(7)], [b1(7)], speed=speed, materials=material).detail(A).shifts[0]
assert shift.average_speed_m_min == 7 and shift.material_consumption_kg is None
def test_unexpected_programming_error_still_propagates():
with pytest.raises(ValueError, match="invalid configuration"):
service([b1(7)], [b1(7)], speed=Speed(error=ValueError("invalid configuration"))).detail(A)
def test_cumulative_material_segments_use_snapshot_deltas_without_double_counting():
a, b = b1(7, order=A), b1(12, order=B)
config = MACHINES["B1"]
stamps = [(6, 0), (8, 20), (10, 40), (13, 70)]
snapshots = [ShiftMaterialSnapshot(datetime(2026, 10, 19, hour, tzinfo=BERLIN),
config.material.calculation_ids[0], config.machine_id,
A, "run", value) for hour, value in stamps]
class Repository:
def get_snapshots(self, *, machine_id, calculation_ids, start, end):
earlier = [sample for sample in snapshots if sample.timestamp <= start]
inside = [sample for sample in snapshots if start < sample.timestamp < end]
return earlier[-1:] + inside
material = ShiftMaterialService(Repository())
first = service([a], [a, b], materials=material).detail(A).shifts[0]
second = service([b], [a, b], materials=material).detail(B).shifts[0]
whole = material.summarize(machine_id=config.machine_id,
calculation_ids=config.material.calculation_ids,
start=first.shift_start, end=first.shift_end)
assert first.segments[0].end == second.segments[0].start
assert (first.material_consumption_kg, second.material_consumption_kg) == (20, 50)
assert first.material_consumption_kg + second.material_consumption_kg == (
whole.total_consumption_kg)
@@ -119,4 +119,5 @@ def test_bento_runtime_wiring(tmp_path, monkeypatch):
assert service._gate_variable_id == 'fef41976-1103-4090-b780-eaeecc02fdfa'
assert service._config == MaterialIntegratorConfig(0.3, 20)
assert service._nominal_width_provider.workplace == 'Bento 1'
assert service._nominal_width_provider.fallback_nominal_width_m == 5.0
erp_settings.from_secret_file.assert_called_once_with(tmp_path / 'erp.env')
+465
View File
@@ -0,0 +1,465 @@
import sqlite3
import traceback
from dataclasses import FrozenInstanceError, replace
from datetime import UTC, datetime, timedelta
from unittest.mock import MagicMock, Mock
from zoneinfo import ZoneInfo
import pytest
from production_analytics.calculations.shift_downtime import (
ShiftDowntimeEvent,
aggregate_shift_downtime,
)
from production_analytics.service.postgres_downtime import (
DowntimeReadError,
PostgresDowntimeRepository,
)
from production_analytics.service.postgres_material import PostgresSettings
from production_analytics.service.shift_downtime import ShiftDowntimeService
BERLIN = ZoneInfo("Europe/Berlin")
START = datetime(2026, 10, 7, 6, tzinfo=BERLIN)
END = START + timedelta(hours=8)
def event(identifier="event", *, start=START, end=END, reason="Reason", **changes):
return replace(
ShiftDowntimeEvent(
identifier,
"machine",
start,
end,
"reason-id",
reason,
"Description",
"Group",
"PLANNED",
"Comment",
),
**changes,
)
def summarize(events, **changes):
return aggregate_shift_downtime(
events,
**{
"machine_id": "machine",
"start": START,
"end": END,
**changes,
},
)
def test_clip_both_boundaries_preserve_source_and_immutable_results():
source = event(start=START - timedelta(hours=1), end=END + timedelta(hours=1))
summary = summarize([source])
assert summary.shift_duration_seconds == summary.total_downtime_seconds == 480 * 60
assert summary.non_downtime_seconds == 0
clipped = summary.events[0]
assert clipped.source is source
assert clipped.start is START and clipped.end is END
assert clipped.duration_seconds == 480 * 60
assert summary.reasons[0].duration_seconds == 480 * 60
assert summary.reasons[0].event_count == 1
assert summary.reasons[0].reason_description == "Description"
assert clipped.source.comment == "Comment"
for value, field in (
(source, "comment"),
(summary, "machine_id"),
(clipped, "start"),
(summary.reasons[0], "reason_name"),
):
with pytest.raises(FrozenInstanceError):
setattr(value, field, None)
def test_open_event_clipped_to_shift_end():
summary = summarize([event(start=START + timedelta(hours=7), end=None)])
assert summary.total_downtime_seconds == 3600
assert summary.non_downtime_seconds == 7 * 3600
assert summary.events[0].end is END
assert summary.events[0].source.source_end is None
def test_raw_closed_event_without_attribution():
source = event(start=START + timedelta(hours=1), end=START + timedelta(hours=2))
summary = summarize([source])
assert source.attributed_start is source.attributed_end is None
assert summary.events[0].start == source.source_start
assert summary.events[0].end == source.source_end
assert summary.total_downtime_seconds == 3600
def test_attributed_end_closes_raw_open_event():
attributed_end = START + timedelta(hours=2)
source = event(end=None, attributed_end=attributed_end)
summary = summarize([source])
assert summary.events[0].start == START
assert summary.events[0].end is attributed_end
assert summary.events[0].source.source_end is None
assert summary.total_downtime_seconds == 2 * 3600
def test_attributed_start_with_no_end_remains_open():
summary = summarize([event(end=None, attributed_start=START + timedelta(hours=7))])
assert summary.total_downtime_seconds == 3600
assert summary.events[0].end is END
def test_attribution_overrides_conflicting_raw_interval():
attributed_start = START + timedelta(hours=1)
attributed_end = START + timedelta(hours=2)
source = event(
start=END,
end=END + timedelta(hours=2),
attributed_start=attributed_start,
attributed_end=attributed_end,
)
summary = summarize([source])
assert summary.events[0].start is attributed_start
assert summary.events[0].end is attributed_end
assert summary.total_downtime_seconds == 3600
assert source.source_start == END
assert source.source_end == END + timedelta(hours=2)
def test_attributed_interval_clips_both_shift_boundaries():
source = event(
start=END,
end=END,
attributed_start=START - timedelta(hours=1),
attributed_end=END + timedelta(hours=1),
)
summary = summarize([source])
assert summary.events[0].start is START
assert summary.events[0].end is END
assert summary.total_downtime_seconds == 8 * 3600
def test_production_reconciled_no_data_event_does_not_overlap_later_shift():
source_start = datetime(2026, 10, 12, 8, 56, 30, tzinfo=UTC)
source = event(
start=source_start,
end=None,
attributed_start=source_start,
attributed_end=datetime(2026, 10, 12, 12, 36, 2, tzinfo=UTC),
)
summary = summarize(
[source],
start=datetime(2026, 10, 13, 12, tzinfo=UTC),
end=datetime(2026, 10, 13, 20, tzinfo=UTC),
)
assert summary.events == summary.reasons == ()
assert summary.total_downtime_seconds == 0
assert summary.non_downtime_seconds == 8 * 3600
def test_attributed_intervals_preserve_union_and_reason_aggregation():
sources = [
event(
identifier,
end=None,
reason=reason,
attributed_start=START + timedelta(hours=lower),
attributed_end=START + timedelta(hours=upper),
)
for identifier, reason, lower, upper in [
("a", "A", 0, 2),
("b", "A", 1, 3),
("c", "B", 2, 4),
]
]
summary = summarize(sources)
assert summary.total_downtime_seconds == 4 * 3600
assert summary.non_downtime_seconds == 4 * 3600
assert [
(reason.reason_name, reason.duration_seconds, reason.event_count)
for reason in summary.reasons
] == [("A", 3 * 3600, 2), ("B", 2 * 3600, 1)]
def test_overlap_nested_duplicates_and_adjacent_intervals_are_not_double_counted():
events = [
event("a", end=START + timedelta(hours=2)),
event("b", start=START + timedelta(hours=1), end=START + timedelta(hours=3)),
event("c", start=START + timedelta(minutes=30), end=START + timedelta(hours=1)),
event("d", start=START + timedelta(hours=3), end=START + timedelta(hours=4)),
]
summary = summarize([*events, events[0]])
assert summary.total_downtime_seconds == 4 * 3600
assert summary.non_downtime_seconds == 4 * 3600
assert summary.reasons[0].duration_seconds == 4 * 3600
def test_overlapping_different_reasons_do_not_inflate_total():
summary = summarize(
[
event("a", end=START + timedelta(hours=2), reason="A"),
event(
"b", start=START + timedelta(hours=1), end=START + timedelta(hours=3), reason="B"
),
]
)
assert summary.total_downtime_seconds == 3 * 3600
assert sum(reason.duration_seconds for reason in summary.reasons) == 4 * 3600
assert summary.non_downtime_seconds == 5 * 3600
def test_half_open_window_excludes_touching_zero_length_and_other_machine_events():
summary = summarize(
[
event("before", start=START - timedelta(hours=1), end=START),
event("after", start=END, end=END + timedelta(hours=1)),
event("zero", start=START, end=START),
event("other", machine_id="other"),
event("future-open", start=END, end=None),
]
)
assert summary.events == summary.reasons == ()
assert summary.total_downtime_seconds == 0
assert summary.non_downtime_seconds == 480 * 60
def test_empty_shift():
summary = summarize([])
assert summary.total_downtime_seconds == 0
assert summary.non_downtime_seconds == summary.shift_duration_seconds == 480 * 60
def test_example_reason_totals_using_synthetic_intervals_matching_supplied_approximations():
# Exact synthetic durations chosen within the supplied rounded real-data examples.
intervals = [
("clean", "Reinigung", -10, 50.84),
("setup1", "Rüstzeit Auftragsbeginn", 60, 91.34),
("mechanical", "212 - Hülsenzuführung mechanisch", 180, 59.22),
("setup2", "Rüstzeit Auftragsbeginn", 469.2, 10.8),
]
events = [
event(
identifier,
reason=reason,
start=START + timedelta(minutes=minute),
end=START + timedelta(minutes=max(0, minute) + duration),
)
for identifier, reason, minute, duration in intervals
]
summary = summarize(events)
assert summary.total_downtime_seconds / 60 == pytest.approx(212.2)
assert summary.non_downtime_seconds / 60 == pytest.approx(267.8)
assert [
(value.reason_name, round(value.duration_seconds / 60, 1)) for value in summary.reasons
] == [
("Rüstzeit Auftragsbeginn", 102.1),
("212 - Hülsenzuführung mechanisch", 59.2),
("Reinigung", 50.8),
]
assert summary.reasons[0].event_count == 2
def test_nullable_reasons_and_deterministic_order():
events = [
event(
"z",
reason=None,
reason_id=None,
reason_description=None,
reason_group=None,
category=None,
comment=None,
end=START + timedelta(minutes=1),
),
event("a", reason="A", end=START + timedelta(minutes=1)),
]
summary = summarize(events)
assert summary == summarize(reversed(events))
assert [value.source.external_id for value in summary.events] == ["a", "z"]
assert any(reason.reason_id is None for reason in summary.reasons)
@pytest.mark.parametrize("date,hours", [(datetime(2026, 3, 29), 7), (datetime(2026, 10, 25), 9)])
def test_dst_uses_elapsed_time_not_wall_clock_duration(date, hours):
start = date.replace(tzinfo=BERLIN)
end = start + timedelta(hours=8)
summary = summarize([event(start=start, end=end)], start=start, end=end)
assert summary.total_downtime_seconds == summary.shift_duration_seconds == hours * 3600
assert summary.start is start and summary.end is end
@pytest.fixture
def db(monkeypatch):
connect = MagicMock()
monkeypatch.setattr("psycopg.connect", connect)
connection = connect.return_value.__enter__.return_value
connection.execute.return_value.fetchall.return_value = [
(
"id",
"machine",
START.astimezone(UTC),
None,
None,
None,
None,
None,
"UNKNOWN",
None,
START.astimezone(UTC),
END.astimezone(UTC),
)
]
repository = PostgresDowntimeRepository(PostgresSettings("localhost", 5432, "db", "user", "pw"))
return repository, connect, connection
def test_repository_sql_parameters_mapping_and_lifecycle(db):
repository, connect, connection = db
values = repository.get_events(machine_id="machine", start=START, end=END)
sql, params = connection.execute.call_args.args
assert params == ("machine", END, START)
assert "WHERE machine_id = %s AND COALESCE(attributed_start, source_start) < %s" in sql
assert "COALESCE(attributed_end, source_end) IS NULL" in sql
assert "OR COALESCE(attributed_end, source_end) > %s" in sql
assert "ORDER BY COALESCE(attributed_start, source_start), external_id" in sql
assert "category, comment, attributed_start, attributed_end" in sql
assert "production_order" not in sql
assert values[0].attributed_start == START.astimezone(UTC)
assert values[0].attributed_end == END.astimezone(UTC)
assert len(values) == 1 and values[0].source_end is None
assert values[0].source_start.tzinfo is UTC
connect.assert_called_once_with(
host="localhost",
port=5432,
dbname="db",
user="user",
password="pw",
connect_timeout=10,
options="-c statement_timeout=10000",
)
connect.return_value.__exit__.assert_called_once()
connection.commit.assert_not_called()
def test_machine_id_is_parameterized(db):
machine_id = "id'; DELETE FROM anything; --"
db[0].get_events(machine_id=machine_id, start=START, end=END)
sql, params = db[2].execute.call_args.args
assert machine_id not in sql
assert params[0] == machine_id
def test_repository_excludes_production_reconciled_event_from_later_shift(db):
repository, _, connection = db
# Execute the repository's overlap predicate, translating only driver placeholders.
with sqlite3.connect(":memory:") as database:
database.execute(
"""CREATE TABLE production_downtime_events (
external_id, machine_id, source_start, source_end,
reason_id, reason_name, reason_description, reason_group,
category, comment, attributed_start, attributed_end)"""
)
database.execute(
"""INSERT INTO production_downtime_events
(external_id, machine_id, source_start, attributed_start, attributed_end)
VALUES (?, ?, ?, ?, ?)""",
(
"reconciled-no-data",
"machine",
"2026-10-12T08:56:30+00:00",
"2026-10-12T08:56:30+00:00",
"2026-10-12T12:36:02+00:00",
),
)
def execute(sql, params):
return database.execute(
sql.replace("%s", "?"),
tuple(
value.isoformat() if isinstance(value, datetime) else value
for value in params
),
)
connection.execute.side_effect = execute
assert repository.get_events(
machine_id="machine",
start=datetime(2026, 10, 13, 12, tzinfo=UTC),
end=datetime(2026, 10, 13, 20, tzinfo=UTC),
) == []
@pytest.mark.parametrize(
"changes",
[
{"machine_id": ""},
{"machine_id": " "},
{"machine_id": "bad\x00"},
{"start": START.replace(tzinfo=None)},
{"end": END.replace(tzinfo=None)},
{"start": None},
{"end": START},
{"end": START - timedelta(seconds=1)},
],
)
def test_invalid_window_before_database_read(db, changes):
inputs = {"machine_id": "machine", "start": START, "end": END, **changes}
with pytest.raises(ValueError):
db[0].get_events(**inputs)
db[1].assert_not_called()
with pytest.raises(ValueError):
aggregate_shift_downtime([], **inputs)
reader = Mock()
with pytest.raises(ValueError):
ShiftDowntimeService(reader).summarize(**inputs)
reader.get_events.assert_not_called()
@pytest.mark.parametrize("stage", ["connect", "execute", "fetch", "close"])
def test_repository_errors_are_safe(db, stage):
repository, connect, connection = db
target = {
"connect": connect,
"execute": connection.execute,
"fetch": connection.execute.return_value.fetchall,
"close": connect.return_value.__exit__,
}[stage]
target.side_effect = RuntimeError("private-password")
with pytest.raises(DowntimeReadError, match="read failed") as error:
repository.get_events(machine_id="machine", start=START, end=END)
assert "private-password" not in "".join(traceback.format_exception(error.value))
@pytest.mark.parametrize(
"changes",
[
{"source_start": START.replace(tzinfo=None)},
{"source_end": END.replace(tzinfo=None)},
{"attributed_start": START.replace(tzinfo=None)},
{"attributed_end": END.replace(tzinfo=None)},
{"attributed_start": "invalid"},
{"attributed_end": "invalid"},
{"source_end": START - timedelta(seconds=1)},
{"reason_name": 123},
],
)
def test_invalid_source_model(changes):
with pytest.raises(ValueError):
event(**changes)
def test_repository_invalid_row_is_wrapped(db):
db[2].execute.return_value.fetchall.return_value = [("invalid-row",)]
with pytest.raises(DowntimeReadError, match="invalid row"):
db[0].get_events(machine_id="machine", start=START, end=END)
def test_service_reads_once_and_propagates_errors():
reader = Mock()
reader.get_events.return_value = [event()]
summary = ShiftDowntimeService(reader).summarize(machine_id="machine", start=START, end=END)
assert summary == summarize([event()])
reader.get_events.assert_called_once_with(machine_id="machine", start=START, end=END)
reader.get_events.side_effect = DowntimeReadError("read failed")
with pytest.raises(DowntimeReadError):
ShiftDowntimeService(reader).summarize(machine_id="machine", start=START, end=END)
+674
View File
@@ -0,0 +1,674 @@
from dataclasses import FrozenInstanceError, replace
from datetime import UTC, datetime, timedelta
from unittest.mock import Mock
from zoneinfo import ZoneInfo
import pytest
from production_analytics.calculations.shift_material import (
ShiftChannelMaterialSnapshot,
ShiftMaterialSnapshot,
aggregate_shift_channel_material,
aggregate_shift_material,
)
from production_analytics.service.shift_material import (
ShiftChannelMaterialService,
ShiftMaterialService,
)
START = datetime(2026, 10, 7, 6, tzinfo=ZoneInfo("Europe/Berlin"))
END = START + timedelta(hours=8)
def machine_sample(minutes=0, value=100.0, *, run="r1", calculation="calc", order="order"):
return ShiftMaterialSnapshot(
START + timedelta(minutes=minutes), calculation, "machine", order, run, value
)
def channel_sample(
minutes=0,
value=100.0,
*,
name="Material A",
number=None,
status="ASSIGNED",
run="r1",
extruder="Ex1",
channel="C1",
order="order",
quality=True,
):
return ShiftChannelMaterialSnapshot(
START + timedelta(minutes=minutes),
"calc",
"machine",
extruder,
channel,
order,
run,
value,
number,
name,
status,
quality,
)
def aggregate(rows, *, channel=False, **changes):
function = aggregate_shift_channel_material if channel else aggregate_shift_material
return function(
rows,
**{
"machine_id": "machine",
"calculation_ids": ("calc",),
"start": START,
"end": END,
**changes,
},
)
def test_single_run_boundary_baseline_and_end_are_latest_not_min_max():
summary = aggregate(
[
machine_sample(-20, 1),
machine_sample(-1, 100),
machine_sample(10, 110),
machine_sample(479, 120),
machine_sample(480, 500),
machine_sample(500, 600),
]
)
assert summary.total_consumption_kg == 20
assert summary.items[0].baseline_timestamp == START - timedelta(minutes=1)
assert summary.items[0].end_timestamp == END - timedelta(minutes=1)
assert not summary.items[0].baseline_missing
assert summary.items[0].material_name is None
assert summary.items[0].production_order == "order"
assert summary.items[0].run_id == "r1"
assert isinstance(summary.items, tuple)
with pytest.raises(FrozenInstanceError):
summary.total_consumption_kg = 0
with pytest.raises(FrozenInstanceError):
summary.items[0].consumption_kg = 0
def test_exact_start_baseline_and_end_exclusion():
summary = aggregate(
[
machine_sample(-1, 90),
machine_sample(0, 100),
machine_sample(479, 125),
machine_sample(480, 500),
]
)
assert summary.total_consumption_kg == 25
assert summary.items[0].baseline_timestamp is not None
assert summary.items[0].baseline_timestamp == START
@pytest.mark.parametrize("channel", [False, True])
def test_run_change_never_differences_counters_across_runs(channel):
sample = channel_sample if channel else machine_sample
summary = aggregate(
[
sample(-1, 100),
sample(120, 120),
sample(121, 10, run="r2", order="order-2"),
sample(479, 45, run="r2", order="order-2"),
],
channel=channel,
)
assert [item.consumption_kg for item in summary.items] == [20, 35]
assert summary.total_consumption_kg == 55
assert summary.items[1].baseline_missing
assert summary.items[1].production_order == "order-2"
@pytest.mark.parametrize("channel", [False, True])
def test_missing_baseline_uses_first_sample_without_fabricating_consumption(channel):
sample = channel_sample if channel else machine_sample
summary = aggregate([sample(10, 1000), sample(20, 1005)], channel=channel)
assert summary.total_consumption_kg == 5
assert all(item.baseline_missing for item in summary.items)
assert aggregate([sample(10, 1000)], channel=channel).total_consumption_kg == 0
@pytest.mark.parametrize("channel", [False, True])
def test_no_samples_and_zero_items_filter(channel):
assert aggregate([], channel=channel).items == ()
sample = channel_sample if channel else machine_sample
rows = [sample(0, 100), sample(10, 100)]
summary = aggregate(rows, channel=channel)
assert len(summary.items) == 1 and summary.total_consumption_kg == 0
assert aggregate(rows, channel=channel, include_zero=False).items == ()
@pytest.mark.parametrize("channel", [False, True])
@pytest.mark.parametrize("values", [(100, 90), (100, 90, 150)])
def test_counter_reset_rejected_even_when_final_value_recovers(channel, values):
sample = channel_sample if channel else machine_sample
with pytest.raises(ValueError, match="decreased/reset"):
aggregate(
[sample(index * 10, value) for index, value in enumerate(values)], channel=channel
)
def test_last_valid_baseline_and_end_skip_null_and_nonfinite_counters():
summary = aggregate(
[
machine_sample(-2, 100),
machine_sample(-1, None),
machine_sample(0, float("nan")),
machine_sample(10, 105),
machine_sample(479, float("inf")),
]
)
assert summary.total_consumption_kg == 5
assert summary.items[0].baseline_timestamp == START - timedelta(minutes=2)
assert summary.items[0].end_timestamp == START + timedelta(minutes=10)
def test_multiple_calculations_and_supplied_k7_b1_examples():
examples = {
"k7-fiber-consumption": (12083.537, 15552.303, 3468.766),
"bento1-fresh-bentonite-consumption": (34604.833, 47320.628, 12715.795),
"bento1-spreader3-consumption": (9540.429, 11303.167, 1762.738),
}
rows = [
machine_sample(minutes, value, calculation=calculation)
for calculation, (baseline, end, _) in examples.items()
for minutes, value in ((-1, baseline), (479, end))
]
summary = aggregate(rows, calculation_ids=tuple(examples))
assert {item.calculation_id: item.consumption_kg for item in summary.items} == pytest.approx(
{calculation: values[2] for calculation, values in examples.items()}
)
assert summary.total_consumption_kg == pytest.approx(
sum(values[2] for values in examples.values())
)
def test_channel_b_identity_attribution_and_no_null_carry_forward():
rows = [
channel_sample(-1, 100, name="Old"),
channel_sample(10, 110, name="Material A"),
channel_sample(20, 130, name="Material A"),
channel_sample(30, 135, name=None),
channel_sample(40, 140, name=" "),
channel_sample(50, 155, name="Material A"),
channel_sample(60, 165, name="Material B"),
]
summary = aggregate(rows, channel=True)
assert [(item.material_name, item.consumption_kg) for item in summary.items] == [
("Material A", 45),
(None, 10),
("Material B", 10),
]
assert summary.items[1].material_mapping_status == "UNAVAILABLE"
assert all(item.material_number is None for item in summary.items)
assert summary.total_consumption_kg == 65
assert all(item.material_name != "Old" for item in summary.items)
def test_material_number_metadata_and_quality_are_preserved():
summary = aggregate(
[
channel_sample(0, 100, number="123", name=None),
channel_sample(10, 105, number="123", name=None, quality=False),
channel_sample(20, 110, number="123", name=None, quality=True),
],
channel=True,
)
item = summary.items[0]
assert item.material_number == "123" and item.material_name is None
assert item.material_mapping_status == "ASSIGNED"
assert not item.percentage_sum_valid
assert item.consumption_kg == 10
def test_e1_historical_null_channel_fixtures():
expected = {
"Ex1": [0, 4890.271, 4890.271, 1772.723, 0, 0, 672.412],
"Ex2": [7596.677, 822.973, 2481.581, 1266.113, 0, 0, 493.784],
}
rows = [
channel_sample(
minutes, value, extruder=extruder, channel=f"C{index}", name=None, status="UNAVAILABLE"
)
for extruder, deltas in expected.items()
for index, delta in enumerate(deltas, 1)
for minutes, value in ((-1, 5000), (479, 5000 + delta))
]
summary = aggregate(rows, channel=True)
assert summary.total_consumption_kg == pytest.approx(24_886.805)
assert len(summary.items) == 14
assert {(item.extruder, item.doser_channel): item.consumption_kg for item in summary.items} == (
pytest.approx(
{
(extruder, f"C{index}"): delta
for extruder, deltas in expected.items()
for index, delta in enumerate(deltas, 1)
}
)
)
assert all(item.material_name is None for item in summary.items)
assert all(item.material_mapping_status == "UNAVAILABLE" for item in summary.items)
assert summary == aggregate(reversed(rows), channel=True)
assert len(aggregate(rows, channel=True, include_zero=False).items) == 9
@pytest.mark.parametrize("channel", [False, True])
def test_dst_fold_boundaries_use_instants(channel):
berlin = ZoneInfo("Europe/Berlin")
start = datetime(2026, 10, 25, 2, 30, tzinfo=berlin, fold=0)
end = start.replace(fold=1)
sample = channel_sample if channel else machine_sample
rows = [
replace(sample(value=value), timestamp=timestamp)
for timestamp, value in (
(start, 100),
(datetime(2026, 10, 25, 1, 20, tzinfo=UTC), 110),
(end, 500),
)
]
summary = aggregate(rows, channel=channel, start=start, end=end)
assert summary.total_consumption_kg == 10
assert summary.start is start and summary.end is end
@pytest.mark.parametrize("channel", [False, True])
def test_invalid_windows_precede_reader_call(channel):
reader = Mock()
service = ShiftChannelMaterialService(reader) if channel else ShiftMaterialService(reader)
for changes in (
{"start": START.replace(tzinfo=None)},
{"end": END.replace(tzinfo=None)},
{"end": START},
{"end": START - timedelta(hours=1)},
{"machine_id": ""},
{"calculation_ids": ()},
{"calculation_ids": ("calc", "calc")},
):
inputs = {
"machine_id": "machine",
"calculation_ids": ("calc",),
"start": START,
"end": END,
**changes,
}
with pytest.raises(ValueError):
service.summarize(**inputs)
with pytest.raises(ValueError):
aggregate([], channel=channel, **changes)
reader.get_snapshots.assert_not_called()
@pytest.mark.parametrize("channel", [False, True])
def test_service_composes_once_and_propagates_errors(channel):
reader = Mock()
reader.get_snapshots.return_value = [channel_sample() if channel else machine_sample()]
service = ShiftChannelMaterialService(reader) if channel else ShiftMaterialService(reader)
inputs = {"machine_id": "machine", "calculation_ids": ("calc",), "start": START, "end": END}
assert service.summarize(**inputs) == aggregate(
reader.get_snapshots.return_value, channel=channel
)
reader.get_snapshots.assert_called_once_with(**inputs)
reader.get_snapshots.side_effect = RuntimeError("reader failed")
with pytest.raises(RuntimeError, match="reader failed"):
service.summarize(**inputs)
@pytest.mark.parametrize("channel", [False, True])
def test_ambiguous_stream_timestamps_and_reappearing_runs_allowed(channel):
sample = channel_sample if channel else machine_sample
with pytest.raises(ValueError, match="same stream timestamp"):
aggregate([sample(0, 100), sample(0, 100)], channel=channel)
summary = aggregate([
sample(0, 100), sample(10, 110), sample(20, 500, run="r2"),
sample(30, 520, run="r2"), sample(40, 200), sample(50, 230),
], channel=channel)
assert summary.total_consumption_kg == 60
assert [(item.run_id, item.consumption_kg) for item in summary.items] == [
("r1", 10), ("r2", 20), ("r1", 30),
]
assert summary.items[2].baseline_missing
summary = aggregate([sample(0, 100), sample(10, 110, order="different")], channel=channel)
assert [(i.production_order, i.consumption_kg) for i in summary.items] == [("different", 10)]
@pytest.mark.parametrize("channel", [False, True])
def test_reappearing_run_keeps_order_attribution_within_each_segment(channel):
sample = channel_sample if channel else machine_sample
rows = [
sample(0, 100, run="A", order="first"),
sample(1, 110, run="A", order="second"),
sample(2, 500, run="B", order="second"),
sample(3, 520, run="B", order="third"),
sample(4, 200, run="A", order="third"),
sample(5, 230, run="A", order="fourth"),
]
summary = aggregate(rows, channel=channel)
assert [(i.run_id, i.production_order, i.consumption_kg) for i in summary.items] == [
("A", "second", 10), ("B", "third", 20), ("A", "fourth", 30),
]
def test_channel_identity_gap_does_not_bridge_across_reappearing_run_segment():
rows = [
channel_sample(0, 100, run="A", name="Known"),
channel_sample(1, 110, run="A", name=None),
channel_sample(2, 500, run="B", name="Other"),
channel_sample(3, 520, run="B", name="Other"),
channel_sample(4, 200, run="A", name=None),
channel_sample(5, 230, run="A", name="Known"),
]
summary = aggregate(rows, channel=True)
assert summary.total_consumption_kg == 60
assert [(item.run_id, item.material_name, item.consumption_kg) for item in summary.items] == [
("A", None, 10), ("B", "Other", 20), ("A", "Known", 30),
]
def test_machine_and_calculation_scoping():
summary = aggregate(
[
machine_sample(),
machine_sample(10, 110),
replace(machine_sample(20, 1000), machine_id="other"),
machine_sample(20, 1000, calculation="other"),
]
)
assert summary.total_consumption_kg == 10
def test_channel_invalid_numeric_samples_are_not_used_as_baseline_or_end():
summary = aggregate(
[
channel_sample(-2, 100),
channel_sample(-1, None),
channel_sample(10, 120, name=None),
channel_sample(479, float("nan")),
],
channel=True,
)
assert summary.total_consumption_kg == 20
assert summary.items[0].material_name is None
assert summary.items[0].material_mapping_status == "UNAVAILABLE"
@pytest.mark.parametrize("channel", [False, True])
def test_new_run_exactly_at_shift_start_is_its_own_baseline(channel):
sample = channel_sample if channel else machine_sample
summary = aggregate(
[sample(-1, 10000, run="old"), sample(0, 50, run="new"), sample(10, 60, run="new")],
channel=channel,
)
assert len(summary.items) == 1
assert summary.items[0].run_id == "new"
assert not summary.items[0].baseline_missing
assert summary.total_consumption_kg == 10
@pytest.mark.parametrize("channel", [False, True])
def test_invalid_counters_do_not_hide_run_boundaries(channel):
sample = channel_sample if channel else machine_sample
summary = aggregate(
[
sample(-2, 1000),
sample(-1, None, run="r2"),
sample(10, 50, run="r2"),
sample(20, 60, run="r2"),
],
channel=channel,
)
assert summary.total_consumption_kg == 10
assert len(summary.items) == 1
assert summary.items[0].run_id == "r2"
assert summary.items[0].baseline_missing
summary = aggregate(
[sample(0, 100), sample(10, None, run="r2"), sample(20, 120)], channel=channel
)
assert summary.total_consumption_kg == 0
@pytest.mark.parametrize("channel", [False, True])
def test_negative_counter_is_rejected(channel):
sample = channel_sample if channel else machine_sample
with pytest.raises(ValueError, match="non-negative"):
aggregate([sample(0, 100), sample(10, -1)], channel=channel)
@pytest.mark.parametrize("channel", [False, True])
def test_spring_dst_window_uses_elapsed_instants(channel):
berlin = ZoneInfo("Europe/Berlin")
start = datetime(2026, 3, 29, 1, 30, tzinfo=berlin)
end = datetime(2026, 3, 29, 3, 30, tzinfo=berlin)
sample = channel_sample if channel else machine_sample
rows = [
replace(sample(value=value), timestamp=timestamp)
for timestamp, value in [
(start, 100),
(datetime(2026, 3, 29, 1, 20, tzinfo=UTC), 110),
(end, 999),
]
]
assert (end.astimezone(UTC) - start.astimezone(UTC)).total_seconds() == 3600
assert aggregate(rows, channel=channel, start=start, end=end).total_consumption_kg == 10
@pytest.mark.parametrize("middle", [None, "Material B"])
@pytest.mark.parametrize("missing", [False, True])
def test_repeated_channel_identity_consolidates_after_interval_attribution(middle, missing):
offset = 1 if missing else 0
rows = [
channel_sample(offset, 100, name="Material A"),
channel_sample(10, 110, name="Material A"),
channel_sample(20, 115, name=middle),
channel_sample(30, 135, name="Material A", quality=False),
]
summary = aggregate(rows, channel=True)
assert len(summary.items) == 2
a, other = summary.items
assert (a.material_name, a.consumption_kg) == ("Material A", 30)
assert (other.material_name, other.consumption_kg) == (middle, 5)
assert a.baseline_timestamp == rows[0].timestamp
assert a.end_timestamp == rows[-1].timestamp
assert not a.percentage_sum_valid
assert other.percentage_sum_valid
assert all(item.baseline_missing == missing for item in summary.items)
if middle is None:
assert other.material_mapping_status == "UNAVAILABLE"
assert summary.total_consumption_kg == 35
assert summary == aggregate(reversed(rows), channel=True)
def test_hundreds_of_alternating_channel_identities_consolidate():
rows = [channel_sample(0, 100)] + [
channel_sample(index, 100 + index, name="Material A" if index % 2 else None)
for index in range(1, 401)
]
summary = aggregate(rows, channel=True)
assert [(item.material_name, item.consumption_kg) for item in summary.items] == [
("Material A", 399),
(None, 1),
]
assert summary.total_consumption_kg == 400
assert summary == aggregate(reversed(rows), channel=True)
@pytest.mark.parametrize("context", ["channel", "extruder", "run", "order", "calculation"])
def test_channel_consolidation_keeps_unrelated_streams_and_runs_separate(context):
rows = [channel_sample(0, 100), channel_sample(10, 110)]
changes = {
"channel": {"doser_channel": "C2"},
"extruder": {"extruder": "Ex2"},
"run": {"run_id": "r2"},
"order": {"run_id": "r2", "production_order": "other"},
"calculation": {"calculation_id": "calc2"},
}[context]
rows += [
replace(channel_sample(20, 500), **changes),
replace(channel_sample(30, 520), **changes),
]
summary = aggregate(rows, channel=True, calculation_ids=("calc", "calc2"))
assert len(summary.items) == 2
assert sorted(item.consumption_kg for item in summary.items) == [10, 20]
assert summary.total_consumption_kg == 30
@pytest.mark.parametrize(
"field,value", [("material_number", "123"), ("material_mapping_status", "OTHER")]
)
def test_channel_consolidation_preserves_distinct_identity_metadata(field, value):
rows = [
channel_sample(0, 100),
channel_sample(10, 110),
replace(channel_sample(20, 120), **{field: value}),
channel_sample(30, 130),
]
summary = aggregate(rows, channel=True)
assert len(summary.items) == 2
assert sorted(item.consumption_kg for item in summary.items) == [10, 20]
assert summary.total_consumption_kg == 30
@pytest.mark.parametrize("include_zero", [False, True])
def test_consolidated_channel_zero_handling(include_zero):
rows = [
channel_sample(0, 100),
channel_sample(10, 100),
channel_sample(20, 105, name=None),
channel_sample(30, 105),
]
summary = aggregate(rows, channel=True, include_zero=include_zero)
assert summary.total_consumption_kg == 5
assert len(summary.items) == (2 if include_zero else 1)
if include_zero:
assert summary.items[0].consumption_kg == 0
assert summary.items[0].baseline_timestamp == rows[0].timestamp
assert summary.items[0].end_timestamp == rows[-1].timestamp
@pytest.mark.parametrize("minutes", [(0, 1, 2), (0, 0.5, 1, 1.5), (0, 5, 10)])
def test_short_bounded_unknown_gap_bridges_all_deltas(minutes):
rows = [
channel_sample(
minute,
100 + index * 10,
name=" Material A " if index in (0, len(minutes) - 1) else None,
quality=index != 1,
)
for index, minute in enumerate(minutes)
]
summary = aggregate(rows, channel=True)
assert len(summary.items) == 1
item = summary.items[0]
assert item.material_name == "Material A"
assert item.consumption_kg == (len(minutes) - 1) * 10
assert summary.total_consumption_kg == rows[-1].cumulative_consumption_kg - 100
assert item.baseline_timestamp == rows[0].timestamp
assert item.end_timestamp == rows[-1].timestamp
assert not item.percentage_sum_valid
assert not item.baseline_missing
assert summary == aggregate(reversed(rows), channel=True)
@pytest.mark.parametrize(
"names,minutes",
[
(("Material A", None, "Material B"), (0, 1, 2)),
(("Material A", None, None), (0, 1, 2)),
((None, None, "Material A"), (0, 1, 2)),
(("Material A", None, "Material A"), (0, 1, 25)),
(("Material A", None, "Material A"), (0, 5, 10.01)),
],
)
def test_ambiguous_unbounded_or_long_identity_gaps_stay_unknown(names, minutes):
rows = [
channel_sample(minute, 100 + index * 10, name=name)
for index, (minute, name) in enumerate(zip(minutes, names))
]
summary = aggregate(rows, channel=True)
unknown = next(item for item in summary.items if item.material_name is None)
assert unknown.consumption_kg == (20 if names[-1] is None else 10)
assert unknown.material_mapping_status == "UNAVAILABLE"
assert summary.total_consumption_kg == 20
@pytest.mark.parametrize(
"field,value", [("material_number", "M2"), ("material_mapping_status", "OTHER")]
)
def test_bridging_requires_exact_normalized_identity(field, value):
rows = [
channel_sample(0, 100, number="M1"),
channel_sample(0.5, 105, number="M1"),
channel_sample(1, 115, name=None),
replace(channel_sample(2, 120, number="M1"), **{field: value}),
]
summary = aggregate(rows, channel=True)
assert len(summary.items) == 3
assert summary.items[1].material_name is None
assert summary.items[1].consumption_kg == 10
assert summary.total_consumption_kg == 20
@pytest.mark.parametrize("boundary", ["run", "order", "channel", "extruder"])
def test_bridging_never_crosses_context_boundaries(boundary):
changes = {
"run": {"run": "r2"},
"order": {"run": "r2", "order": "new-order"},
"channel": {"channel": "C2"},
"extruder": {"extruder": "Ex2"},
}[boundary]
rows = [
channel_sample(0, 100),
channel_sample(1, 110, name=None),
channel_sample(2, 500, **changes),
channel_sample(3, 520, **changes),
]
summary = aggregate(rows, channel=True)
unknown = next(item for item in summary.items if item.material_name is None)
assert unknown.consumption_kg == 10
assert summary.total_consumption_kg == 30
def test_short_bridge_preserves_missing_baseline_and_zero_filter():
rows = [channel_sample(1, 100), channel_sample(2, 100, name=None), channel_sample(3, 100)]
summary = aggregate(rows, channel=True)
assert len(summary.items) == 1
assert summary.items[0].baseline_missing
assert summary.total_consumption_kg == 0
assert aggregate(rows, channel=True, include_zero=False).items == ()
@pytest.mark.parametrize("channel", [False, True])
def test_orders_within_physical_run_conserve_counter_and_use_end_order(channel):
sample = channel_sample if channel else machine_sample
rows = [sample(i, value, order=order) for i, value, order in
[(0, 1000, "1032"), (1, 1010, "1032"),
(2, 1025, "1037"), (3, 1040, "1037")]]
summary = aggregate(rows, channel=channel)
assert [(i.production_order, i.consumption_kg) for i in summary.items] == [
("1032", 10), ("1037", 30)]
assert {i.run_id for i in summary.items} == {"r1"}
assert summary.total_consumption_kg == 40
assert aggregate([replace(r, production_order="OLD") for r in rows],
channel=channel).total_consumption_kg == 40
rows[2] = sample(2, 1005, order="1037")
with pytest.raises(ValueError, match="decreased/reset"):
aggregate(rows, channel=channel)
@pytest.mark.parametrize("orders", [("X", "Y", "Y"), ("X", "X", "Y"), ("X", "Y", "X")])
def test_channel_unknown_gap_cannot_bridge_order_boundary(orders):
rows = [channel_sample(0, 100, order=orders[0]),
channel_sample(1, 110, name=None, order=orders[1]),
channel_sample(2, 120, order=orders[2])]
summary = aggregate(rows, channel=True)
unknown = [i for i in summary.items if i.material_name is None]
assert len(unknown) == 1
assert unknown[0].production_order == orders[1]
assert unknown[0].consumption_kg == 10
assert summary.total_consumption_kg == 20
+264
View File
@@ -0,0 +1,264 @@
from dataclasses import FrozenInstanceError, replace
from datetime import UTC, datetime, timedelta
from unittest.mock import Mock
from zoneinfo import ZoneInfo
import pytest
from production_analytics.calculations.shift_production import aggregate_shift_production
from production_analytics.erp import ErpReadError, ProductionConfirmation
from production_analytics.service.shift_production import ShiftProductionService
BERLIN = ZoneInfo("Europe/Berlin")
START = datetime(2026, 9, 4, 6, tzinfo=BERLIN)
END = START + timedelta(hours=8)
ROW = ProductionConfirmation(
workplace="arbitrary-workplace",
production_order="order-1",
timestamp=START,
article_number="article-1",
article_description="4.85 x 40 m",
roll_number="roll-1",
production_quantity_m2=194.0,
feedback_quantity_m2=194.0,
raw_material_number=None,
raw_material_description=None,
batch_number=None,
raw_material_quantity=0.0,
tenant="tenant",
)
def summarize(rows, **kwargs):
return aggregate_shift_production(
rows,
**{
"workplace": ROW.workplace,
"start": START,
"end": END,
**kwargs,
},
)
def test_one_article_order_uses_feedback_area_and_tracks_times():
rows = [
ROW,
replace(
ROW,
timestamp=START + timedelta(hours=1),
roll_number="roll-2",
feedback_quantity_m2=1500.0,
production_quantity_m2=999.0,
),
]
summary = summarize(iter(reversed(rows)))
assert summary.total_produced_m2 == 1694.0
assert summary.total_roll_count == 2
assert len(summary.items) == 1
item = summary.items[0]
assert (item.production_order, item.article_number, item.article_description) == (
"order-1",
"article-1",
"4.85 x 40 m",
)
assert item.produced_m2 == 1694.0
assert item.roll_count == 2
assert item.first_confirmation_at is START
assert item.last_confirmation_at == START + timedelta(hours=1)
assert summary.start is START and summary.end is END
assert isinstance(summary.items, tuple)
with pytest.raises(FrozenInstanceError):
item.produced_m2 = 0
with pytest.raises(FrozenInstanceError):
summary.total_produced_m2 = 0
def test_articles_orders_and_descriptions_form_separate_groups():
rows = [
ROW,
replace(ROW, article_number="article-2", feedback_quantity_m2=2500.0),
replace(ROW, production_order="order-2", feedback_quantity_m2=1500.0),
replace(ROW, article_description="Different description", feedback_quantity_m2=100.0),
]
summary = summarize(rows)
assert len(summary.items) == 4
assert summary.total_produced_m2 == 4294.0
# The same roll number is distinct within each group, not across the shift.
assert summary.total_roll_count == 4
assert summary.total_produced_m2 == sum(item.produced_m2 for item in summary.items)
assert summary.total_roll_count == sum(item.roll_count for item in summary.items)
def test_raw_material_null_zero_and_negative_feedback_do_not_contribute():
rows = [
ROW,
*[
replace(
ROW,
feedback_quantity_m2=quantity,
production_quantity_m2=0,
raw_material_quantity=999,
roll_number="raw-roll",
)
for quantity in (None, 0.0, -10.0)
],
]
summary = summarize(rows)
assert summary.total_produced_m2 == 194.0
assert summary.total_roll_count == 1
def test_repeated_roll_numbers_deduplicate_only_roll_count():
rows = [ROW, ROW, replace(ROW, roll_number=" roll-1 "), replace(ROW, roll_number="roll-2")]
summary = summarize(rows)
assert summary.total_produced_m2 == 4 * 194.0
assert summary.total_roll_count == summary.items[0].roll_count == 2
@pytest.mark.parametrize("roll", [None, "", " "])
def test_missing_roll_number_still_contributes_area(roll):
summary = summarize([replace(ROW, roll_number=roll)])
assert summary.total_produced_m2 == 194.0
assert summary.total_roll_count == 0
def test_exact_workplace_and_half_open_boundaries():
summary = summarize(
[
replace(ROW, timestamp=START - timedelta(microseconds=1)),
ROW,
replace(ROW, timestamp=END - timedelta(microseconds=1), roll_number="last"),
replace(ROW, timestamp=END),
replace(ROW, workplace="different-workplace"),
],
workplace=" arbitrary-workplace ",
)
assert summary.workplace == ROW.workplace
assert summary.total_produced_m2 == 388.0
assert summary.total_roll_count == 2
assert summary.items[0].last_confirmation_at == END - timedelta(microseconds=1)
def test_empty_shift_and_material_only_shift():
for rows in ([], [replace(ROW, feedback_quantity_m2=0.0)]):
summary = summarize(rows)
assert summary.items == ()
assert summary.total_produced_m2 == 0.0
assert summary.total_roll_count == 0
def test_deterministic_order_with_nullable_article_identifiers():
rows = [
replace(ROW, production_order="z", timestamp=START + timedelta(minutes=1)),
replace(ROW, article_number="z"),
replace(ROW, article_number=None),
replace(ROW, article_number="", article_description=None),
replace(ROW, article_number="", article_description=""),
]
summary = summarize(rows)
assert summary == summarize(reversed(rows))
assert [(item.article_number, item.article_description) for item in summary.items[:4]] == [
(None, "4.85 x 40 m"),
("", None),
("", ""),
("z", "4.85 x 40 m"),
]
assert summary.items[-1].production_order == "z"
@pytest.mark.parametrize(
"kwargs",
[
{"start": START.replace(tzinfo=None)},
{"end": END.replace(tzinfo=None)},
{"start": None},
{"end": START},
{"end": START - timedelta(seconds=1)},
{"workplace": ""},
{"workplace": " "},
{"workplace": "bad\x00"},
],
)
def test_validation_precedes_gateway_read(kwargs):
gateway = Mock()
service = ShiftProductionService(gateway)
inputs = {"workplace": ROW.workplace, "start": START, "end": END, **kwargs}
with pytest.raises(ValueError):
aggregate_shift_production([], **inputs)
with pytest.raises(ValueError):
service.summarize(**inputs)
gateway.get_confirmations.assert_not_called()
def test_naive_confirmation_timestamp_is_rejected():
with pytest.raises(ValueError, match="confirmation timestamp"):
summarize([replace(ROW, timestamp=START.replace(tzinfo=None))])
@pytest.mark.parametrize("quantity", [float("nan"), float("inf"), True])
def test_invalid_feedback_quantity_rejected(quantity):
with pytest.raises(ValueError, match="finite"):
summarize([replace(ROW, feedback_quantity_m2=quantity)])
def test_service_reads_once_and_preserves_boundary_timezones():
gateway = Mock()
gateway.get_confirmations.return_value = [ROW]
summary = ShiftProductionService(gateway).summarize(
workplace=" arbitrary-workplace ",
start=START,
end=END,
)
gateway.get_confirmations.assert_called_once_with(workplace=ROW.workplace, start=START, end=END)
assert summary == summarize([ROW])
assert summary.start.tzinfo is summary.end.tzinfo is BERLIN
assert summary.items[0].first_confirmation_at.tzinfo is BERLIN
def test_service_passes_explicit_site_timezone_to_gateway():
malaysia = ZoneInfo("Asia/Kuala_Lumpur")
gateway = Mock()
gateway.get_confirmations.return_value = []
start = datetime(2026, 10, 19, 6, tzinfo=malaysia)
end = datetime(2026, 10, 19, 14, tzinfo=malaysia)
ShiftProductionService(gateway).summarize(
workplace="Malaysia", start=start, end=end, timezone=malaysia,
)
gateway.get_confirmations.assert_called_once_with(
workplace="Malaysia", start=start, end=end, timezone=malaysia,
)
def test_gateway_errors_propagate():
gateway = Mock()
gateway.get_confirmations.side_effect = ErpReadError("ERP production confirmation read failed")
with pytest.raises(ErpReadError, match="read failed"):
ShiftProductionService(gateway).summarize(workplace=ROW.workplace, start=START, end=END)
def test_dst_fold_order_and_window_compare_instants_without_changing_timestamps():
start = datetime(2026, 10, 25, 2, 15, tzinfo=BERLIN, fold=0)
end = datetime(2026, 10, 25, 2, 45, tzinfo=BERLIN, fold=1)
early = datetime(2026, 10, 25, 2, 30, tzinfo=BERLIN, fold=0)
late = early.replace(fold=1)
summary = summarize(
[
replace(ROW, timestamp=late),
replace(ROW, timestamp=early),
replace(ROW, timestamp=end),
],
start=start,
end=end,
)
assert summary.total_produced_m2 == 388.0
assert summary.items[0].first_confirmation_at is early
assert summary.items[0].last_confirmation_at is late
assert summary.start is start and summary.end is end
def test_aware_other_timezone_compares_same_instants_without_rewriting():
instant = START.astimezone(UTC)
summary = summarize([replace(ROW, timestamp=instant)])
assert summary.items[0].first_confirmation_at is instant
assert summary.start is START
+523
View File
@@ -0,0 +1,523 @@
from copy import deepcopy
from dataclasses import FrozenInstanceError
from datetime import UTC, date, datetime, timedelta
from pathlib import Path
from zoneinfo import ZoneInfo
import pytest
import yaml
from production_analytics.calculations.shift_downtime import (
ClippedShiftDowntimeEvent,
ShiftDowntimeEvent,
ShiftDowntimeReason,
ShiftDowntimeSummary,
)
from production_analytics.calculations.shift_material import ShiftMaterialItem, ShiftMaterialSummary
from production_analytics.calculations.shift_production import (
ShiftProductionItem,
ShiftProductionSummary,
)
from production_analytics.calculations.shift_report import (
most_recent_completed_shift,
shift_report_window,
)
from production_analytics.calculations.shift_speed import aggregate_shift_speed
from production_analytics.service.shift_report import ShiftReportService
from production_analytics.service.shift_report_config import (
load_shift_report_config,
load_shift_report_machines,
)
CONFIG_PATH = Path(__file__).resolve().parents[1] / "config/shift-report-machines.yaml"
SHIFT_TIMEZONE = ZoneInfo("Europe/Berlin")
START, END = shift_report_window(date(2026, 10, 7), "early", SHIFT_TIMEZONE)
class Stub:
def __init__(self, name, result, calls):
self.name, self.result, self.calls = name, result, calls
self.error = None
def summarize(self, **kwargs):
self.calls.append((self.name, kwargs))
if self.error is not None:
raise self.error
return self.result
def composition(name="B1"):
machines = load_shift_report_machines(CONFIG_PATH)
config = machines[name]
calls = []
production = ShiftProductionSummary(
START, END, config.erp_workplace, 123, 1,
(ShiftProductionItem("order", "article", "description", 123, 1, START, START),),
)
reasons = tuple(
ShiftDowntimeReason(str(index), reason_name, "description", "group", "category",
duration, 1)
for index, (reason_name, duration) in enumerate(
[(None, 100), ("Stop", 90), (" ", 80), ("Other", 70)]
)
)
source = ShiftDowntimeEvent("event", config.machine_id, START,
START + timedelta(seconds=100), None, None, None, None, None, None)
event = ClippedShiftDowntimeEvent(source, START, source.source_end, 100)
downtime = ShiftDowntimeSummary(config.machine_id, START, END, 28800, 100, 28700,
(event,), reasons)
channel = config.material is not None and config.material.mode == "channel"
item = ShiftMaterialItem(
source="channel_material_consumption_snapshots" if channel
else "material_consumption_snapshots",
calculation_id=config.material.calculation_ids[0] if config.material else "unused",
machine_id=config.machine_id,
production_order="order", run_id="run", consumption_kg=42,
baseline_timestamp=START, end_timestamp=END - timedelta(seconds=1),
baseline_missing=False, extruder="Ex1" if channel else None,
doser_channel="C2" if channel else None, material_name=None,
material_mapping_status="UNAVAILABLE" if channel else None,
)
materials = ShiftMaterialSummary(config.machine_id, START, END, 42, (item,))
speed = aggregate_shift_speed([], config=config.speed, start=START, end=END)
stubs = {key: Stub(key, value, calls) for key, value in [
("production", production), ("downtime", downtime), ("materials", materials),
("channel_materials", materials), ("speed", speed),
]}
service = ShiftReportService(machines=machines, **stubs)
return service, stubs, calls, config
@pytest.mark.parametrize("name,workplace,mode,ids", [
("B1", "BENTO 1", "materials",
("bento1-fresh-bentonite-consumption", "bento1-spreader3-consumption")),
("E1", "1568705", "channel_materials", ("e1-channel-material-consumption",)),
("K7", "K7", "materials", ("k7-fiber-consumption",)),
])
def test_machine_composition(name, workplace, mode, ids):
service, stubs, calls, config = composition(name)
report = service.build(machine_name=name, start=START, end=END)
assert calls == [
("production", {"workplace": workplace, "start": START, "end": END,
"timezone": SHIFT_TIMEZONE}),
("downtime", {"machine_id": config.machine_id, "start": START, "end": END}),
(mode, {"machine_id": config.machine_id, "calculation_ids": ids,
"start": START, "end": END}),
("speed", {"config": config.speed, "start": START, "end": END}),
]
assert report.machine_name == name and report.machine_id == config.machine_id
assert report.production is stubs["production"].result
assert report.downtime is stubs["downtime"].result
assert report.materials is stubs[mode].result
assert report.speed is stubs["speed"].result
assert report.materials.items[0].consumption_kg == 42
assert report.materials.items[0].material_name is None
if name == "E1":
assert report.materials.items[0].extruder == "Ex1"
assert report.materials.items[0].doser_channel == "C2"
assert report.materials.items[0].material_mapping_status == "UNAVAILABLE"
assert report.downtime.non_downtime_seconds == 28700
assert report.downtime_event_count == 1
assert report.production.items[0].article_description == "description"
with pytest.raises(FrozenInstanceError):
report.machine_name = "other"
def test_order_kpis_enrich_each_production_row_without_changing_shift_totals():
from dataclasses import replace
from production_analytics.service.production_order import ProductionOrderShiftKpi
service, stubs, _, _ = composition("K7")
first = stubs["production"].result.items[0]
second = replace(first, production_order="other", produced_m2=24)
stubs["production"].result = replace(
stubs["production"].result,
items=(first, second), total_produced_m2=147, total_roll_count=2,
)
class OrderKpis:
def __init__(self):
self.calls = []
def for_shift(self, **kwargs):
self.calls.append(kwargs)
return {
"order": ProductionOrderShiftKpi((), 10.24, 3317.58),
"other": ProductionOrderShiftKpi((), 8.5, 1863.36),
}
order_kpis = OrderKpis()
service.order_kpis = order_kpis
report = service.build(machine_name="K7", start=START, end=END)
assert order_kpis.calls == [{"machine_name": "K7", "start": START, "end": END,
"orders": ("order", "other"),
"allocated_shift_materials": None}]
assert [(item.average_speed_m_min, item.material_consumption_kg)
for item in report.production.items] == [(10.24, 3317.58), (8.5, 1863.36)]
assert report.production.total_produced_m2 == 147
assert report.materials is stubs["materials"].result
assert report.speed is stubs["speed"].result
@pytest.mark.parametrize("name", ["Gitter 1", "Gitter 2", "Gitter 3", "Gitter 4", "K5"])
def test_boolean_speed_machines_appear_in_report_without_material(name):
service, stubs, calls, config = composition(name)
report = service.build(machine_name=name, start=START, end=END)
assert [stage for stage, _ in calls] == ["production", "downtime", "speed"]
assert calls[-1][1]["config"] is config.speed
assert report.speed is stubs["speed"].result
assert report.materials is None
def test_sites_and_existing_machine_capabilities():
config = load_shift_report_config(CONFIG_PATH)
assert {key: site.display_name for key, site in config.sites.items()} == {
"espelkamp": "Espelkamp", "adorf": "Adorf", "malaysia": "Malaysia",
}
assert set(config.machines) == {
"B1", "E1", "K7", "K3/4", "E4", "Gitter 1", "Gitter 2",
"Gitter 3", "Gitter 4", "K5", "Secumat 1/2", "Secumat 3",
"Bento 2", "K1", "K6",
}
assert all(config.machines[name].site == "espelkamp" for name in ("B1", "E1", "K7"))
assert all(vars_for_capabilities(machine) == (True, True, True, True)
for name, machine in config.machines.items() if name in ("B1", "E1", "K7"))
assert config.machines["K7"].material.allocation == "erp_fiber_share"
assert config.machines["B1"].material.allocation == "none"
assert config.sites["espelkamp"].timezone is SHIFT_TIMEZONE
assert config.sites["adorf"].timezone is SHIFT_TIMEZONE
assert config.sites["malaysia"].timezone.key == "Asia/Kuala_Lumpur"
assert all(config.machines[name].timezone is SHIFT_TIMEZONE
for name in ("B1", "E1", "K7"))
with pytest.raises(TypeError):
config.sites["new"] = config.sites["adorf"]
def vars_for_capabilities(machine):
value = machine.capabilities
return value.production, value.downtime, value.material, value.speed
def test_new_production_machines_have_valid_sites_and_capabilities():
machines = load_shift_report_config(CONFIG_PATH).machines
expected = {
"K3/4": ("espelkamp", "K3/4", None),
"E4": ("espelkamp", "1568700", "646ebfa0-e97d-4970-b9f4-da94492aecc3"),
"Gitter 1": ("adorf", "GITTERANL", "35612735-03cc-4496-a72e-3c3e2216c720"),
"Gitter 2": ("adorf", "GITTER II", "5e89db10-ef0e-4224-866c-eee12bc3d27c"),
"Gitter 3": ("adorf", "GITTERIII", "ec3baac3-ccc1-4d1e-9b57-3f5ab2daa567"),
"Gitter 4": ("adorf", "GITTER IV", "ffa5de99-66a2-44bd-b039-9b4275bc5f9e"),
"K5": ("adorf", "K5", "8c094b9d-32d2-4ddf-b56a-2cd11a09eebf"),
"Secumat 1/2": ("adorf", "SECEXTRU", "16c0a111-3049-41d5-9e19-42ee0e047757"),
"Secumat 3": ("adorf", "SEC3", "0c207a7c-7813-4cff-90ba-6a0148919d38"),
"Bento 2": ("malaysia", "BENTO 2", "6201f3de-b940-45d7-930c-1481c5ae9e1d"),
"K1": ("malaysia", "K1", "40f1f58b-21fc-490a-8343-d1888938f11b"),
"K6": ("malaysia", "K6", "5e778f87-2d0f-47ac-a3ce-0c0dd9957918"),
}
assert len(machines) == 15
assert set(machines) - {"B1", "E1", "K7"} == set(expected)
downtime_enabled = {
"E4", "Gitter 1", "Gitter 2", "Gitter 3", "Gitter 4",
"K5", "Secumat 1/2", "Secumat 3",
}
for name, (site, workplace, machine_id) in expected.items():
machine = machines[name]
assert (machine.display_name, machine.site, machine.erp_workplace,
machine.machine_id) == (name, site, workplace, machine_id)
speed_enabled = name in {"Gitter 1", "Gitter 2", "Gitter 3", "Gitter 4", "K5"}
assert vars_for_capabilities(machine) == (True, name in downtime_enabled, False,
speed_enabled)
assert machine.material is None
assert (machine.speed is not None) == speed_enabled
assert machine.timezone.key == ("Asia/Kuala_Lumpur" if site == "malaysia"
else "Europe/Berlin")
ids = [machine.machine_id for machine in machines.values() if machine.machine_id]
assert len(ids) == len(set(ids)) == 14
@pytest.mark.parametrize("downtime", [False, True])
def test_partial_capabilities_skip_disabled_sources_and_render_unavailable(
downtime,
):
from dataclasses import replace
from production_analytics.presentation.shift_report import TextBlock, present_report
from production_analytics.service.shift_report_config import ShiftReportCapabilities
service, stubs, calls, config = composition()
partial = replace(config,
capabilities=ShiftReportCapabilities(True, downtime, False, False),
material=None, speed=None)
service.machines = {"Synthetic": partial}
report = service.build(machine_name="Synthetic", start=START, end=END)
expected = ["production", "downtime"] if downtime else ["production"]
assert [name for name, _ in calls] == expected
assert report.production is stubs["production"].result
assert report.downtime is (stubs["downtime"].result if downtime else None)
assert report.materials is None and report.speed is None
assert report.downtime_event_count == (1 if downtime else 0)
blocks = present_report(report)
unavailable = [b for b in blocks if isinstance(b, TextBlock)
and b.text == "Für diese Maschine nicht verfügbar."]
assert len(unavailable) == (1 if downtime else 2)
def test_downtime_only_machine_does_not_query_production():
from dataclasses import replace
from production_analytics.service.shift_report_config import ShiftReportCapabilities
service, stubs, calls, config = composition()
service.machines = {"DowntimeOnly": replace(
config, capabilities=ShiftReportCapabilities(False, True, False, False),
material=None, speed=None,
)}
report = service.build(machine_name="DowntimeOnly", start=START, end=END)
assert [name for name, _ in calls] == ["downtime"]
assert report.production is None and report.downtime is stubs["downtime"].result
@pytest.mark.parametrize("explicit_null", [False, True])
def test_production_only_machine_without_enlyze_id_loads_and_builds(tmp_path, explicit_null):
document = deepcopy(yaml.safe_load(CONFIG_PATH.read_text()))
document["machines"] = {"K3/4": {
"display_name": "K3/4", "site": "espelkamp", "erp_workplace": "K3/4",
"capabilities": {"production": True, "downtime": False,
"material": False, "speed": False},
}}
if explicit_null:
document["machines"]["K3/4"]["machine_id"] = None
path = tmp_path / "machines.yaml"
path.write_text(yaml.safe_dump(document))
machine = load_shift_report_config(path).machines["K3/4"]
assert machine.machine_id is None and machine.timezone is SHIFT_TIMEZONE
service, stubs, calls, _ = composition()
service.machines = {"K3/4": machine}
report = service.build(machine_name="K3/4", start=START, end=END)
assert report.machine_id is None and report.timezone is SHIFT_TIMEZONE
assert report.production is stubs["production"].result
assert report.downtime is report.materials is report.speed is None
assert [name for name, _ in calls] == ["production"]
def test_malaysia_report_carries_site_timezone_to_production_and_presentation():
from dataclasses import replace
from production_analytics.presentation.shift_report import TextBlock, present_report
from production_analytics.service.shift_report_config import ShiftReportCapabilities
malaysia = ZoneInfo("Asia/Kuala_Lumpur")
service, _, calls, config = composition()
service.machines = {"Synthetic": replace(
config, site="malaysia", timezone=malaysia, machine_id=None,
capabilities=ShiftReportCapabilities(True, False, False, False),
material=None, speed=None,
)}
start, end = shift_report_window(date(2026, 10, 19), "late", malaysia)
report = service.build(machine_name="Synthetic", start=start.astimezone(UTC),
end=end.astimezone(UTC))
assert report.timezone is malaysia
assert report.start == start and report.end == end
assert calls == [("production", {"workplace": config.erp_workplace,
"start": start, "end": end, "timezone": malaysia})]
texts = [block.text for block in present_report(report) if isinstance(block, TextBlock)]
assert "Zeitzone: Asia/Kuala_Lumpur" in texts
assert any("Schichtbeginn: 19.10.2026 14:00:00" in value for value in texts)
def test_top_three_and_fallback_preserve_reason_metadata_and_order():
service, stubs, _, _ = composition()
report = service.build(machine_name="B1", start=START, end=END)
assert len(report.downtime_reasons) == 4
assert len(report.top_downtime_reasons) == 3
assert [reason.display_name for reason in report.top_downtime_reasons] == [
"Ohne Stillstandsgrund", "Stop", "Ohne Stillstandsgrund",
]
for index, view in enumerate(report.top_downtime_reasons):
assert view.reason is stubs["downtime"].result.reasons[index]
assert view.reason.duration_seconds == [100, 90, 80][index]
assert view.reason.reason_description == "description"
assert report.downtime.reasons[0].reason_name is None
with pytest.raises(FrozenInstanceError):
report.top_downtime_reasons[0].display_name = "changed"
def test_legitimate_empty_sources_are_kept():
service, stubs, _, config = composition()
stubs["production"].result = ShiftProductionSummary(START, END, config.erp_workplace, 0, 0, ())
stubs["downtime"].result = ShiftDowntimeSummary(config.machine_id, START, END, 28800,
0, 28800, (), ())
stubs["materials"].result = ShiftMaterialSummary(config.machine_id, START, END, 0, ())
report = service.build(machine_name="B1", start=START, end=END)
assert report.production.items == () and report.production.total_produced_m2 == 0
assert report.materials.items == () and report.materials.total_consumption_kg == 0
assert report.speed.average_line_speed_m_min is None
assert report.top_downtime_reasons == ()
assert report.downtime_event_count == 0
@pytest.mark.parametrize("name,stage", [
("B1", "production"), ("B1", "downtime"), ("B1", "materials"),
("E1", "channel_materials"), ("K7", "speed"),
])
def test_mandatory_failures_propagate_without_reading_later_sources(name, stage):
service, stubs, calls, _ = composition(name)
error = RuntimeError("source failed")
stubs[stage].error = error
with pytest.raises(RuntimeError) as caught:
service.build(machine_name=name, start=START, end=END)
assert caught.value is error
assert calls[-1][0] == stage
sequence = ["production", "downtime",
"channel_materials" if name == "E1" else "materials", "speed"]
assert [call[0] for call in calls] == sequence[:sequence.index(stage) + 1]
@pytest.mark.parametrize("start,end", [
(START.replace(tzinfo=None), END), (START, END.replace(tzinfo=None)),
(START, START), (END, START),
])
def test_invalid_window_precedes_source_calls(start, end):
service, _, calls, _ = composition()
with pytest.raises(ValueError):
service.build(machine_name="B1", start=start, end=end)
assert calls == []
def test_unknown_machine_precedes_source_calls():
service, _, calls, _ = composition()
with pytest.raises(ValueError, match="Unknown"):
service.build(machine_name="unknown", start=START, end=END)
assert calls == []
def test_utc_input_is_normalized_to_berlin_without_changing_instants():
service, _, calls, _ = composition()
report = service.build(machine_name="B1", start=START.astimezone(UTC), end=END.astimezone(UTC))
assert report.start.tzinfo.key == "Europe/Berlin"
assert report.start == START and report.end == END
assert all(call[1]["start"].tzinfo.key == "Europe/Berlin" for call in calls)
@pytest.mark.parametrize("shift,hours", [
("early", (6, 14)), ("late", (14, 22)), ("night", (22, 6)),
])
def test_shift_windows(shift, hours):
start, end = shift_report_window(date(2026, 10, 7), shift, SHIFT_TIMEZONE)
assert (start.hour, end.hour) == hours
expected_end_day = date(2026, 10, 8) if shift == "night" else start.date()
assert end.date() == expected_end_day
assert (end.astimezone(UTC) - start.astimezone(UTC)).total_seconds() == 28800
@pytest.mark.parametrize("day,hours", [(date(2026, 3, 28), 7), (date(2026, 10, 24), 9)])
def test_night_shift_dst_elapsed_duration(day, hours):
start, end = shift_report_window(day, "night", SHIFT_TIMEZONE)
assert (end.astimezone(UTC) - start.astimezone(UTC)).total_seconds() == hours * 3600
@pytest.mark.parametrize("shift,start_hour,end_hour", [
("early", 6, 14), ("late", 14, 22), ("night", 22, 6),
])
def test_malaysia_shift_windows_use_local_wall_clock(shift, start_hour, end_hour):
malaysia = ZoneInfo("Asia/Kuala_Lumpur")
start, end = shift_report_window(date(2026, 10, 19), shift, malaysia)
assert start.tzinfo is end.tzinfo is malaysia
assert (start.hour, end.hour) == (start_hour, end_hour)
assert (end.astimezone(UTC) - start.astimezone(UTC)).total_seconds() == 28800
def test_same_instant_has_different_site_completed_shifts():
now = datetime(2026, 10, 19, 11, tzinfo=UTC)
assert most_recent_completed_shift(now, SHIFT_TIMEZONE) == (date(2026, 10, 18), "night")
assert most_recent_completed_shift(now, ZoneInfo("Asia/Kuala_Lumpur")) == (
date(2026, 10, 19), "early")
@pytest.mark.parametrize("mutation", [
lambda d: d["machines"]["B1"].pop("erp_workplace"),
lambda d: d["machines"]["B1"].update(unknown=True),
lambda d: d["machines"]["B1"]["material"].update(mode="erp"),
lambda d: d["machines"]["B1"]["material"].update(calculation_ids=[]),
lambda d: d["machines"]["B1"]["material"].update(calculation_ids="calc"),
lambda d: d["machines"]["B1"]["material"].update(calculation_ids=["calc", "calc"]),
lambda d: d["machines"]["B1"]["material"].update(calculation_ids=[None]),
lambda d: d["machines"]["B1"]["material"].update(extra=True),
lambda d: d["machines"]["B1"]["speed"].pop("signal_ref"),
lambda d: d["machines"]["B1"]["speed"].update(extra=True),
lambda d: d["machines"]["B1"]["speed"].update(signal=" "),
lambda d: d["machines"]["B1"]["speed"].update(unit="rpm"),
lambda d: d["machines"]["B1"]["speed"].update(production_gate_m_min=float("nan")),
lambda d: d["machines"]["E1"].update(machine_id=d["machines"]["B1"]["machine_id"]),
lambda d: d["machines"]["B1"].update(erp_workplace=1568705),
lambda d: d.update(extra=True),
lambda d: d["machines"]["B1"].update(site="unknown"),
lambda d: d["machines"]["B1"].update(site=[]),
lambda d: d["machines"]["B1"].pop("capabilities"),
lambda d: d["machines"]["B1"]["capabilities"].update(material=False),
lambda d: d["machines"]["B1"].pop("material"),
lambda d: d["machines"]["B1"]["capabilities"].update(speed=False),
lambda d: d["machines"]["B1"].pop("speed"),
lambda d: d["machines"]["B1"]["capabilities"].update(production="true"),
lambda d: d["machines"]["B1"].update(display_name=" "),
lambda d: d["sites"]["espelkamp"].update(display_name=""),
lambda d: d["sites"]["espelkamp"].update(extra=True),
lambda d: d["machines"]["B1"]["material"].update(allocation="unknown"),
lambda d: d["sites"]["malaysia"].update(timezone="Mars/Base"),
lambda d: d["sites"]["malaysia"].update(timezone=""),
lambda d: d["sites"]["malaysia"].pop("timezone"),
lambda d: d["machines"]["B1"].pop("machine_id"),
lambda d: d["machines"]["B1"].update(machine_id=None),
lambda d: d["machines"]["B1"]["capabilities"].update(
production=False, downtime=False, material=False, speed=False),
])
def test_strict_configuration(tmp_path, mutation):
document = deepcopy(yaml.safe_load(CONFIG_PATH.read_text()))
mutation(document)
path = tmp_path / "machines.yaml"
path.write_text(yaml.safe_dump(document))
with pytest.raises(ValueError):
load_shift_report_machines(path)
def test_duplicate_yaml_keys_rejected(tmp_path):
path = tmp_path / "machines.yaml"
path.write_text("machines: {}\nmachines: {}\n")
with pytest.raises(ValueError, match="unique"):
load_shift_report_machines(path)
def test_duplicate_site_key_rejected(tmp_path):
document = CONFIG_PATH.read_text().replace(
" adorf:\n display_name: Adorf", " espelkamp:\n display_name: Adorf"
)
path = tmp_path / "machines.yaml"
path.write_text(document)
with pytest.raises(ValueError, match="unique"):
load_shift_report_config(path)
def test_duplicate_machine_key_rejected(tmp_path):
document = CONFIG_PATH.read_text().replace(" E1:\n", " B1:\n")
path = tmp_path / "machines.yaml"
path.write_text(document)
with pytest.raises(ValueError, match="unique"):
load_shift_report_config(path)
@pytest.mark.parametrize("capability", ["downtime", "material", "speed"])
def test_machine_id_required_for_nonproduction_capabilities(tmp_path, capability):
document = deepcopy(yaml.safe_load(CONFIG_PATH.read_text()))
machine = document["machines"]["B1"]
machine["capabilities"] = {name: name == capability
for name in ("production", "downtime", "material", "speed")}
machine.pop("machine_id")
if capability != "material":
machine.pop("material")
if capability != "speed":
machine.pop("speed")
path = tmp_path / "machines.yaml"
path.write_text(yaml.safe_dump(document))
with pytest.raises(ValueError):
load_shift_report_config(path)
+135
View File
@@ -0,0 +1,135 @@
from dataclasses import replace
from pathlib import Path
from types import SimpleNamespace
import pytest
from test_shift_report import END, START, composition
from production_analytics.cli import __main__ as cli
from production_analytics.presentation import shift_report as presenter
from production_analytics.service import shift_report_runtime as runtime
def arguments(*extra):
return [
"report",
"shift",
"--machine",
"E1",
"--start",
START.isoformat(),
"--end",
END.isoformat(),
"--output",
"/tmp/shift.pdf",
*extra,
]
@pytest.mark.parametrize(
"extra,message",
[
(["--machine", "UNKNOWN"], "Unknown shift-report machine"),
(["--start", "2026-10-07T06:00:00"], "timezone"),
(["--start", "invalid"], "Invalid isoformat"),
(["--end", START.isoformat()], "end must follow start"),
(["--end", "2026-10-06T06:00:00+02:00"], "end must follow start"),
],
)
def test_validation_before_settings_or_source_access(monkeypatch, capsys, extra, message):
def unexpected(*args, **kwargs):
pytest.fail("Invalid arguments reached runtime setup")
monkeypatch.setattr(cli, "_runtime_environment", unexpected)
assert cli.main(arguments(*extra)) == 2
assert message in capsys.readouterr().err
def test_start_end_and_output_are_required():
with pytest.raises(SystemExit) as caught:
cli.main(["report", "shift", "--machine", "E1"])
assert caught.value.code == 2
def test_cli_builds_one_report_and_passes_output(monkeypatch, capsys):
service, _, _, _ = composition("E1")
value = service.build(machine_name="E1", start=START, end=END)
calls = []
def environment(*paths):
calls.append(paths)
return {"settings": "supplied"}
def build(machines, env):
assert set(machines) == {
"B1", "E1", "K7", "K3/4", "E4", "Gitter 1", "Gitter 2",
"Gitter 3", "Gitter 4", "K5", "Secumat 1/2", "Secumat 3",
"Bento 2", "K1", "K6",
}
assert env == {"settings": "supplied"}
def report(**kwargs):
calls.append(kwargs)
return value
return SimpleNamespace(build=report)
monkeypatch.setattr(cli, "_runtime_environment", environment)
monkeypatch.setattr(runtime, "build_shift_report_service", build)
monkeypatch.setattr(
presenter, "write_pdf", lambda report, output: calls.append((report, output))
)
assert cli.main(arguments()) == 0
assert calls == [
(Path("secrets/enlyze.env"), Path("secrets/erp.env"), Path("secrets/postgres.env")),
{"machine_name": "E1", "start": START, "end": END},
(value, Path("/tmp/shift.pdf")),
]
assert capsys.readouterr().out.strip() == "/tmp/shift.pdf"
def test_runtime_wires_existing_readers_without_connecting(monkeypatch):
machines = composition("E1")[0].machines
tokens = {"postgres": object(), "erp": object(), "enlyze": object()}
for settings, token in (
(runtime.PostgresSettings, tokens["postgres"]),
(runtime.ErpSettings, tokens["erp"]),
(runtime.ExplorationSettings, tokens["enlyze"]),
):
monkeypatch.setattr(settings, "from_environment", lambda env, token=token: token)
service = runtime.build_shift_report_service(machines, {})
assert service.production.gateway._settings is tokens["erp"]
assert service.downtime.repository.settings is tokens["postgres"]
assert service.materials.repository.settings is tokens["postgres"]
assert service.channel_materials.repository.settings is tokens["postgres"]
assert isinstance(service.speed.gateway, runtime.EnlyzeApiGateway)
assert set(service.material_allocators) == {"K7"}
def test_allocator_selection_uses_strategy_for_any_machine_name(monkeypatch):
machines = dict(composition("K7")[0].machines)
k7 = machines.pop("K7")
machines["OtherMachine"] = replace(k7, machine_id="other-id", speed=None,
capabilities=replace(k7.capabilities, speed=False))
machines["B1"] = replace(machines["B1"], material=replace(
machines["B1"].material, allocation="none"))
for settings in (runtime.PostgresSettings, runtime.ErpSettings,
runtime.ExplorationSettings):
monkeypatch.setattr(settings, "from_environment", lambda env: object())
service = runtime.build_shift_report_service(machines, {})
assert set(service.material_allocators) == {"OtherMachine"}
assert isinstance(service.material_allocators["OtherMachine"],
runtime.K7FiberAllocationService)
def test_source_failure_is_safe_and_does_not_render(monkeypatch, capsys):
def fail(**kwargs):
raise RuntimeError("secret source details")
monkeypatch.setattr(cli, "_runtime_environment", lambda *args: {})
monkeypatch.setattr(
runtime, "build_shift_report_service", lambda *args: SimpleNamespace(build=fail)
)
monkeypatch.setattr(presenter, "write_pdf", lambda *args: pytest.fail("Rendered failed read"))
assert cli.main(arguments()) == 1
assert capsys.readouterr().err == "Report failed: RuntimeError\n"
+123
View File
@@ -0,0 +1,123 @@
from dataclasses import replace
from datetime import date, datetime
from html import escape
from zoneinfo import ZoneInfo
import pytest
from test_shift_report_pdf import material_report
from production_analytics.presentation.shift_report import MaterialPieBlock, present_report
from production_analytics.presentation.shift_report_html import render_page
SHIFT_TIMEZONE = ZoneInfo("Europe/Berlin")
def page(value):
return render_page(
machines={value.machine_name: None},
labels={"early": "Frühschicht"},
day=date(2026, 10, 14),
shift="early",
machine=value.machine_name,
report=value,
generated_at=datetime.now(SHIFT_TIMEZONE),
error=None,
)
def test_shift_report_mode_navigation():
html = page(material_report((10,)))
assert '<nav class="mode-nav" aria-label="Bereich wählen">' in html
assert '<a href="/" aria-current="page">Schichtbericht</a>' in html
assert '<a href="/orders">Fertigungsauftrag</a>' in html
assert html.split("</style>", 1)[1].count('aria-current="page"') == 1
assert ".mode-nav a:focus-visible" in html
def test_production_rows_show_attributed_kpis_and_link_fa_to_detail():
value = material_report((10,))
item = replace(value.production.items[0], production_order="FA A/1",
average_speed_m_min=10.24, material_consumption_kg=3317.58)
html = page(replace(value, production=replace(value.production, items=(item,))))
assert '<a class="fa-link" href="/order?production_order=FA+A%2F1">FA A/1</a>' in html
assert '<th scope="col">Ø Geschwindigkeit</th>' in html
assert '<td>10,24 m/min</td>' in html
assert '<td>3.317,58 kg</td>' in html
assert '<th scope="col">Details</th>' not in html
assert "Durchschnittliche Liniengeschwindigkeit im Lauf" not in html
assert "<h2>Liniengeschwindigkeit</h2>" not in html
def test_production_kpis_distinguish_unavailable_from_zero():
value = material_report((10,))
item = replace(value.production.items[0], average_speed_m_min=None,
material_consumption_kg=0)
html = page(replace(value, production=replace(value.production, items=(item,))))
assert '<td>—</td><td>0,00 kg</td>' in html
def test_multiple_materials_chart_and_table():
html = page(material_report((10, 30)))
assert '<figure class="material-chart">' in html
assert '<svg viewBox="0 0 120 120"' in html
assert "Material-0: 10,00 kg (25,00 %)" in html
assert "Material-1: 30,00 kg (75,00 %)" in html
assert '<th scope="col">Materialname</th>' in html
assert "<td>Material-0</td>" in html and "<td>30,00 kg</td>" in html
def test_zero_entries_omitted_and_one_material_supported():
value = material_report((0, 12, 0))
html = page(value)
assert "Material-0" not in html and "Material-2" not in html
assert "Material-1: 12,00 kg (100,00 %)" in html
assert html.count("<circle ") == 1
# Existing PDF presentation still omits single-material charts.
assert not any(isinstance(block, MaterialPieBlock) for block in present_report(value))
@pytest.mark.parametrize("quantities", [(), (0, 0), (-2,)])
def test_no_positive_materials_no_chart(quantities):
html = page(material_report(quantities))
assert '<figure class="material-chart">' not in html
assert "<svg " not in html and "<circle " not in html
if not any(quantities):
assert "Keine Materialverbrauchsdaten vorhanden." in html
def test_sensitive_names_are_text_not_code():
value = material_report((10, 20))
name = '</script><script>alert("x")</script>&\' ${evil} \u2028'
items = tuple(
replace(item, material_name=name, material_number=f"M{index}")
for index, item in enumerate(value.materials.items)
)
html = page(replace(value, materials=replace(value.materials, items=items)))
assert "<script>" not in html and "</script>" not in html
assert escape(name + " (M0)") in html
assert escape(name + " (M1)") in html
assert "<td>" + escape(name) + "</td>" in html
@pytest.mark.parametrize("machine", ["B1", "E1", "K7"])
def test_chart_uses_shared_consolidated_material_totals(machine):
value = material_report((10, 20, 30))
items = tuple(
replace(
item,
material_name="Harz",
material_number="M1",
production_order=f"order-{index}",
erp_booking_share=0.5 if machine == "K7" else None,
)
for index, item in enumerate(value.materials.items)
)
value = replace(value, machine_name=machine, materials=replace(value.materials, items=items))
html = page(value)
assert "Harz: 60,00 kg (100,00 %)" in html
assert html.count("<circle ") == 1
if machine == "K7":
# The order-specific table is preserved alongside the material-level pie.
for index in range(3):
assert f"<td>order-{index}</td>" in html
assert "ERP-Anteil" in html
+341
View File
@@ -0,0 +1,341 @@
from dataclasses import replace
from datetime import UTC, datetime
import pytest
from test_shift_report import END, START, composition
from production_analytics.presentation.shift_report import (
MaterialPieBlock,
TableBlock,
TextBlock,
present_report,
render_pdf,
write_pdf,
)
def report(name="E1"):
service, _, _, _ = composition(name)
return service.build(machine_name=name, start=START, end=END)
def content(value):
return "\n".join(
block.text
if isinstance(block, TextBlock)
else "\n".join(" | ".join(row) for row in (block.headers, *block.rows))
for block in present_report(value)
if isinstance(block, (TextBlock, TableBlock))
)
def test_stable_model_required_labels_and_supplied_quantities():
value = report()
assert present_report(value) == present_report(value)
text = content(value)
for label in (
"Schichtbericht",
"Maschine: E1",
"Schichtbeginn",
"Schichtende",
"Produktion",
"Produktionsauftrag",
"Artikelnummer",
"Artikelbeschreibung",
"Rollen gesamt: 1",
"Gesamtmenge: 123,00 m²",
"Stillstand gesamt",
"Zeit ohne erfassten Stillstand",
"Materialverbrauch",
"42,00 kg",
"order",
"article",
"description",
):
assert label in text
assert "Produktionszeit" not in text
assert "Liniengeschwindigkeit im Lauf" not in text
assert "Durchschnittliche Liniengeschwindigkeit" not in text
def test_production_pdf_table_contains_attributed_kpis_as_plain_text():
value = report("K7")
first = replace(value.production.items[0], production_order="12026001032",
average_speed_m_min=10.24, material_consumption_kg=3317.58)
second = replace(first, production_order="12026001037",
average_speed_m_min=None, material_consumption_kg=0)
value = replace(value, production=replace(value.production, items=(first, second)))
table = next(block for block in present_report(value)
if isinstance(block, TableBlock) and "Ø Geschwindigkeit" in block.headers)
assert table.rows[0][-2:] == ("10,24 m/min", "3.317,58 kg")
assert table.rows[1][-2:] == ("—", "0,00 kg")
assert table.rows[0][0] == "12026001032"
assert "Materialverbrauch gesamt: 42,00 kg" in content(value)
assert "Liniengeschwindigkeit im Lauf" not in content(value)
assert render_pdf(value).startswith(b"%PDF-")
def test_top_three_preserve_order_and_durations():
tables = [block for block in present_report(report()) if isinstance(block, TableBlock)]
reasons = next(block for block in tables if block.headers == ("Stillstandsgrund", "Dauer"))
assert reasons.rows == (
("Ohne Stillstandsgrund", "0 h 01 min 40,0 s"),
("Stop", "0 h 01 min 30,0 s"),
("Ohne Stillstandsgrund", "0 h 01 min 20,0 s"),
)
assert "Other" not in content(report())
def test_material_summary_names_numbers_and_unknown_label():
value = report()
assert "Materialzuordnung fehlt" in content(value)
assert "Ex1" not in content(value)
item = replace(value.materials.items[0], material_number="M123", material_name="Harz & Öl")
text = content(replace(value, materials=replace(value.materials, items=(item,))))
assert "M123" in text
assert "Harz & Öl" in text
def test_empty_sections_and_zero_totals():
value = report()
value = replace(
value,
production=replace(value.production, items=(), total_produced_m2=0, total_roll_count=0),
downtime=replace(value.downtime, events=(), reasons=(), total_downtime_seconds=0),
materials=replace(value.materials, items=(), total_consumption_kg=0),
)
text = content(value)
for message in (
"Keine Produktionsdaten vorhanden.",
"Keine Stillstandsgründe vorhanden.",
"Keine Stillstandsereignisse vorhanden.",
"Keine Materialverbrauchsdaten vorhanden.",
"Gesamtmenge: 0,00 m²",
"Rollen gesamt: 0",
):
assert message in text
@pytest.mark.parametrize(
"start,end,expected",
[
(
datetime(2026, 1, 1, 5, tzinfo=UTC),
datetime(2026, 1, 1, 13, tzinfo=UTC),
("01.01.2026 06:00:00 CET (+0100)", "01.01.2026 14:00:00 CET (+0100)"),
),
(
datetime(2026, 10, 25, 0, 30, tzinfo=UTC),
datetime(2026, 10, 25, 1, 30, tzinfo=UTC),
("25.10.2026 02:30:00 CEST (+0200)", "25.10.2026 02:30:00 CET (+0100)"),
),
],
)
def test_berlin_display_including_dst_fold(start, end, expected):
text = content(replace(report(), start=start, end=end))
assert all(timestamp in text for timestamp in expected)
def test_pdf_is_repeatable_a4_and_written_to_requested_path(tmp_path):
pytest.importorskip("reportlab")
value = report()
payload = render_pdf(value)
assert payload == render_pdf(value)
assert payload.startswith(b"%PDF-")
assert b"/MediaBox [ 0 0 595.2756 841.8898 ]" in payload
output = tmp_path / "nested" / "shift.pdf"
write_pdf(value, output)
assert output.read_bytes() == payload
def test_pdf_paginates_long_reports_and_escapes_source_markup():
pytest.importorskip("reportlab")
value = report()
item = replace(value.production.items[0], article_description="<tag> & description " * 5)
value = replace(value, production=replace(value.production, items=(item,) * 60))
payload = render_pdf(value)
assert payload.count(b"/Type /Page\n") > 1
@pytest.mark.parametrize("name", ["B1", "E1", "K7"])
def test_every_machine_renders_supplied_values_without_correction(name):
value = report(name)
value = replace(value, production=replace(value.production, total_produced_m2=1234.56))
text = content(value)
assert f"Maschine: {name}" in text
assert "Gesamtmenge: 1.234,56 m²" in text
assert "123,00 m²" in text
assert "Materialverbrauch gesamt: 42,00 kg" in text
def material_report(quantities):
value = report()
template = value.materials.items[0]
items = tuple(
replace(
template,
calculation_id=f"calculation-{index}",
doser_channel=f"C{index + 1}",
consumption_kg=quantity,
material_name=f"Material-{index}",
)
for index, quantity in enumerate(quantities)
)
return replace(
value, materials=replace(value.materials, items=items, total_consumption_kg=sum(quantities))
)
def test_material_zero_filter_preserves_report_and_total():
value = material_report((0, 10, 0.001, -2))
original = value.materials
text = content(value)
assert "Material-0" not in text
assert "Material-1" in text
assert "Material-2" in text # Exactly zero, not rounded-to-zero filtering.
assert "Material-3" in text
assert "Materialverbrauch gesamt: 8,00 kg" in text
assert value.materials is original
assert len(value.materials.items) == 4
chart = next(block for block in present_report(value) if isinstance(block, MaterialPieBlock))
assert chart.consumption_kg == (10, 0.001)
assert chart.labels == ("Material-1", "Material-2")
@pytest.mark.parametrize("quantities", [(), (0, 0), (0, 12)])
def test_material_chart_requires_two_positive_items(quantities):
value = material_report(quantities)
assert not any(isinstance(block, MaterialPieBlock) for block in present_report(value))
if not any(quantities):
assert "Keine Materialverbrauchsdaten vorhanden." in content(value)
assert not any(
isinstance(block, TableBlock) and block.headers[0] == "Materialname"
for block in present_report(value)
)
assert render_pdf(value).startswith(b"%PDF-")
def test_material_chart_labels_and_repeatable_pdf():
value = material_report((10, 20, 30, 40))
items = list(value.materials.items)
items[0] = replace(items[0], material_name="Harz & Öl")
items[1] = replace(items[1], extruder=None, doser_channel=None, material_name="Polymer")
items[2] = replace(
items[2], extruder=None, doser_channel=None, material_number="M123", material_name=None
)
items[3] = replace(items[3], extruder=None, doser_channel=None, material_name=None)
value = replace(value, materials=replace(value.materials, items=tuple(items)))
blocks = present_report(value)
chart = next(block for block in blocks if isinstance(block, MaterialPieBlock))
assert chart.labels == ("Materialzuordnung fehlt", "M123", "Harz & Öl", "Polymer")
assert chart.consumption_kg == (40, 30, 10, 20)
assert blocks == present_report(value)
assert render_pdf(value) == render_pdf(value)
assert "Materialverbrauch gesamt: 100,00 kg" in content(value)
def test_material_chart_long_legend_paginates():
value = material_report((1,) * 80)
items = tuple(
replace(item, material_name=f"{index:02d} " + "Long material name <tag> & resin " * 3)
for index, item in enumerate(value.materials.items)
)
value = replace(value, materials=replace(value.materials, items=items))
assert render_pdf(value).count(b"/Type /Page\n") > 1
def material_table(value):
return next(
block
for block in present_report(value)
if isinstance(block, TableBlock) and block.headers[0] == "Materialname"
)
def test_material_summary_combines_channels_unknowns_and_uses_same_pie_totals():
value = material_report((10, 20, 5, 15, 30, 0))
items = tuple(
replace(
item,
extruder="Ex1" if index % 2 else "Ex2",
doser_channel="C7",
material_name=("Resin" if index < 2 else "Additive" if index == 4 else None),
)
for index, item in enumerate(value.materials.items)
)
value = replace(value, materials=replace(value.materials, items=items))
original = value.materials
assert material_table(value).rows == (
("Materialzuordnung fehlt", "–", "20,00 kg"),
("Additive", "–", "30,00 kg"),
("Resin", "–", "30,00 kg"),
)
chart = next(block for block in present_report(value) if isinstance(block, MaterialPieBlock))
assert chart.labels == ("Materialzuordnung fehlt", "Additive", "Resin")
assert chart.consumption_kg == (20, 30, 30)
assert sum(chart.consumption_kg) == value.materials.total_consumption_kg == 80
assert "Materialverbrauch gesamt: 80,00 kg" in content(value)
assert value.materials is original
assert value.materials.items == items
assert "Ex1" not in content(value) and "C7" not in content(value)
reversed_value = replace(
value, materials=replace(value.materials, items=tuple(reversed(items)))
)
assert present_report(value) == present_report(reversed_value)
assert render_pdf(value) == render_pdf(reversed_value)
def test_same_name_with_different_numbers_remains_distinct_and_legend_disambiguates():
value = material_report((10, 20))
items = tuple(
replace(item, material_name="Resin", material_number=f"M{index}")
for index, item in enumerate(value.materials.items)
)
value = replace(value, materials=replace(value.materials, items=items))
assert material_table(value).rows == (("Resin", "M0", "10,00 kg"), ("Resin", "M1", "20,00 kg"))
chart = next(block for block in present_report(value) if isinstance(block, MaterialPieBlock))
assert chart.labels == ("Resin (M0)", "Resin (M1)")
def test_historical_e1_unknown_channels_become_single_material_category():
from test_shift_material import aggregate, channel_sample
deltas = (
0,
4890.271,
4890.271,
1772.723,
0,
0,
672.412,
7596.677,
822.973,
2481.581,
1266.113,
0,
0,
493.784,
)
rows = [
channel_sample(
minute, counter, extruder=f"Ex{index // 7 + 1}", channel=f"C{index % 7 + 1}", name=None
)
for index, delta in enumerate(deltas)
for minute, counter in ((-1, 5000), (479, 5000 + delta))
]
summary = aggregate(rows, channel=True)
value = replace(report(), materials=summary)
assert len(summary.items) == 14
assert summary.total_consumption_kg == pytest.approx(24886.805)
assert material_table(value).rows == (("Materialzuordnung fehlt", "–", "24.886,81 kg"),)
assert not any(isinstance(block, MaterialPieBlock) for block in present_report(value))
def test_same_known_material_across_channels_has_one_row_and_no_pie():
value = material_report((10, 20, 0))
items = tuple(
replace(item, material_name="Resin", material_number="M1") for item in value.materials.items
)
value = replace(value, materials=replace(value.materials, items=items))
assert material_table(value).rows == (("Resin", "M1", "30,00 kg"),)
assert not any(isinstance(block, MaterialPieBlock) for block in present_report(value))
+255
View File
@@ -0,0 +1,255 @@
from dataclasses import replace
from datetime import UTC, date, datetime
from types import SimpleNamespace
from urllib.parse import urlencode
from wsgiref.util import setup_testing_defaults
from zoneinfo import ZoneInfo
import pytest
from test_shift_report_pdf import report
from production_analytics import web
from production_analytics.calculations.shift_report import (
most_recent_completed_shift,
shift_report_window,
)
from production_analytics.service.shift_report_config import (
load_shift_report_config,
load_shift_report_machines,
)
SHIFT_TIMEZONE = ZoneInfo("Europe/Berlin")
@pytest.mark.parametrize(
"hour,minute,day,shift",
[
(5, 0, 13, "late"),
(6, 0, 13, "night"),
(10, 0, 13, "night"),
(14, 0, 14, "early"),
(15, 46, 14, "early"),
(21, 59, 14, "early"),
(22, 0, 14, "late"),
(23, 0, 14, "late"),
(0, 0, 13, "late"),
],
)
def test_completed_shift(hour, minute, day, shift):
now = datetime(2026, 10, 14, hour, minute, tzinfo=SHIFT_TIMEZONE)
assert most_recent_completed_shift(now, SHIFT_TIMEZONE) == (date(2026, 10, day), shift)
start, end = shift_report_window(*most_recent_completed_shift(now, SHIFT_TIMEZONE),
SHIFT_TIMEZONE)
assert start.astimezone(UTC) < end.astimezone(UTC) <= now.astimezone(UTC)
@pytest.mark.parametrize("day,hours", [(date(2026, 3, 28), 7), (date(2026, 10, 24), 9)])
def test_dst_night(day, hours):
start, end = shift_report_window(day, "night", SHIFT_TIMEZONE)
assert (end.astimezone(UTC) - start.astimezone(UTC)).total_seconds() == hours * 3600
assert start.hour == 22 and end.hour == 6
assert most_recent_completed_shift(end, SHIFT_TIMEZONE) == (day, "night")
# Both occurrences of the autumn fold remain inside the running night shift.
for fold in (0, 1):
now = end.replace(hour=2, fold=fold)
assert most_recent_completed_shift(now, SHIFT_TIMEZONE) == (day, "late")
def test_clock_requires_timezone_and_accepts_utc():
with pytest.raises(ValueError):
most_recent_completed_shift(datetime(2026, 1, 1), SHIFT_TIMEZONE)
assert most_recent_completed_shift(datetime(2026, 10, 14, 12, tzinfo=UTC),
SHIFT_TIMEZONE) == (
date(2026, 10, 14),
"early",
)
def request(app, **params):
env = {}
setup_testing_defaults(env)
env["QUERY_STRING"] = urlencode(params)
response = []
payload = b"".join(app(env, lambda status, headers: response.append((status, dict(headers)))))
return *response[0], payload
@pytest.fixture
def application():
machines = load_shift_report_machines("config/shift-report-machines.yaml")
calls = []
value = report()
def build(**kwargs):
calls.append(kwargs)
return replace(
value, machine_name=kwargs["machine_name"], start=kwargs["start"], end=kwargs["end"]
)
app = web.create_app(
machines,
lambda: SimpleNamespace(build=build),
clock=lambda: datetime(2026, 10, 14, 15, 46, tzinfo=SHIFT_TIMEZONE),
)
return app, calls
def test_default_and_render(application):
app, calls = application
status, headers, body = request(app)
assert status == "200 OK"
assert calls == [
dict(
machine_name="B1",
start=shift_report_window(date(2026, 10, 14), "early", SHIFT_TIMEZONE)[0],
end=shift_report_window(date(2026, 10, 14), "early", SHIFT_TIMEZONE)[1],
)
]
text = body.decode()
for expected in (
"123,00 m²",
"42,00 kg",
"description",
"Ohne Stillstandsgrund",
"Datenstand: 14.10.2026 15:46:00 CEST",
"Europe/Berlin",
"Als PDF exportieren",
):
assert expected in text
assert "Durchschnittliche Liniengeschwindigkeit im Lauf" not in text
assert headers["Cache-Control"] == "no-store"
def test_explicit_and_fresh_each_request(application):
app, calls = application
for _ in range(2):
assert request(app, date="2026-03-28", shift="night", machine="K7")[0] == "200 OK"
start, end = shift_report_window(date(2026, 3, 28), "night", SHIFT_TIMEZONE)
assert calls == [dict(machine_name="K7", start=start, end=end)] * 2
@pytest.mark.parametrize(
"params",
[
dict(machine="invalid"),
dict(shift="invalid"),
dict(date="bad"),
dict(date="9999-12-31", shift="night"),
],
)
def test_invalid_selection(application, params):
app, calls = application
status, _, body = request(app, **params)
assert status == "400 Bad Request"
assert "Ungültige Auswahl" in body.decode()
assert not calls
def test_failure_safe(application):
machines = load_shift_report_machines("config/shift-report-machines.yaml")
def fail():
raise RuntimeError("password=secret database.internal")
status, _, body = request(web.create_app(machines, fail))
assert status == "503 Service Unavailable"
assert "konnte nicht erstellt werden" in body.decode()
assert b"secret" not in body and b"database.internal" not in body
def test_pdf_uses_one_fresh_service_model(application, monkeypatch):
app, calls = application
rendered = []
def pdf(value):
rendered.append(value)
return b"%PDF-fake"
monkeypatch.setattr(web, "render_pdf", pdf)
status, headers, body = request(
app, date="2026-10-13", shift="night", machine="E1", format="pdf"
)
assert status == "200 OK" and headers["Content-Type"] == "application/pdf"
assert body == b"%PDF-fake"
assert len(calls) == len(rendered) == 1
assert rendered[0].machine_name == calls[0]["machine_name"]
assert (rendered[0].start, rendered[0].end) == shift_report_window(
date(2026, 10, 13), "night", SHIFT_TIMEZONE)
def test_source_markup_escaped():
from production_analytics.presentation.shift_report_html import render_page
value = report()
item = replace(value.production.items[0], article_description="<script>alert('x')</script>")
value = replace(value, production=replace(value.production, items=(item,)))
page = render_page(
machines={"E1": None},
labels=web.SHIFT_LABELS,
day=date(2026, 10, 14),
shift="early",
machine="E1",
report=value,
generated_at=datetime.now(SHIFT_TIMEZONE),
error=None,
)
assert "<script>" not in page and "&lt;script&gt;" in page
def test_site_metadata_reaches_web_presentation(monkeypatch):
config = load_shift_report_config("config/shift-report-machines.yaml")
received = []
def render_page(**kwargs):
received.append(kwargs["sites"])
return "page"
monkeypatch.setattr(web, "render_page", render_page)
app = web.create_app(config.machines, lambda: SimpleNamespace(build=lambda **kwargs: report()),
sites=config.sites)
assert request(app)[2] == b"page"
assert received[0]["malaysia"].display_name == "Malaysia"
def test_default_shift_uses_selected_machine_site_timezone():
config = load_shift_report_config("config/shift-report-machines.yaml")
malaysia = config.sites["malaysia"].timezone
machine = replace(config.machines["B1"], display_name="Synthetic Malaysia",
site="malaysia", timezone=malaysia, machine_id=None,
capabilities=replace(config.machines["B1"].capabilities,
downtime=False, material=False, speed=False),
material=None, speed=None)
machines = {"B1": config.machines["B1"], "Synthetic": machine}
calls = []
def build(**kwargs):
calls.append(kwargs)
selected = machines[kwargs["machine_name"]]
return replace(report(), machine_name=kwargs["machine_name"],
machine_id=selected.machine_id, timezone=selected.timezone,
start=kwargs["start"], end=kwargs["end"])
app = web.create_app(machines, lambda: SimpleNamespace(build=build),
clock=lambda: datetime(2026, 10, 19, 11, tzinfo=UTC))
assert request(app)[0] == "200 OK"
assert calls[-1]["machine_name"] == "B1"
assert (calls[-1]["start"], calls[-1]["end"]) == shift_report_window(
date(2026, 10, 18), "night", SHIFT_TIMEZONE)
status, _, body = request(app, machine="Synthetic")
assert status == "200 OK"
assert calls[-1]["machine_name"] == "Synthetic"
assert (calls[-1]["start"], calls[-1]["end"]) == shift_report_window(
date(2026, 10, 19), "early", malaysia)
assert b"Asia/Kuala_Lumpur" in body
assert request(app, machine="Synthetic", date="2026-10-18", shift="late")[0] == "200 OK"
assert (calls[-1]["start"], calls[-1]["end"]) == shift_report_window(
date(2026, 10, 18), "late", malaysia)
malaysia_first = web.create_app(
{"Synthetic": machine, "B1": config.machines["B1"]},
lambda: SimpleNamespace(build=build),
clock=lambda: datetime(2026, 10, 19, 11, tzinfo=UTC),
)
assert request(malaysia_first)[0] == "200 OK"
assert calls[-1]["machine_name"] == "Synthetic"
assert (calls[-1]["start"], calls[-1]["end"]) == shift_report_window(
date(2026, 10, 19), "early", malaysia)
+416
View File
@@ -0,0 +1,416 @@
from copy import deepcopy
from dataclasses import FrozenInstanceError, replace
from datetime import UTC, datetime, timedelta
from pathlib import Path
from unittest.mock import Mock
from zoneinfo import ZoneInfo
import pytest
import yaml
from production_analytics.calculations.shift_speed import (
NumericDwellGate,
ShiftSpeedConfig,
ShiftSpeedSample,
aggregate_shift_speed,
)
from production_analytics.enlyze.gateway import EnlyzeApiGateway
from production_analytics.service.shift_report_config import load_shift_report_machines
from production_analytics.service.shift_speed import ShiftSpeedService
START = datetime(2026, 10, 7, 6, tzinfo=ZoneInfo("Europe/Berlin"))
END = START + timedelta(hours=8)
CONFIG = ShiftSpeedConfig("machine", "speed", 0.5)
CONFIG_PATH = Path(__file__).resolve().parents[1] / "config/shift-report-machines.yaml"
def summarize(values, **kwargs):
return aggregate_shift_speed(
[ShiftSpeedSample(START + timedelta(seconds=index), value)
for index, value in enumerate(values)],
config=CONFIG, start=START, end=END, **kwargs,
)
def test_active_filtering_counts_and_statistics():
summary = summarize([0, -1, 0.2, 0.5, 1, 2, 6, None, float("nan"),
float("inf"), -float("inf"), "3", True, 10**1000])
assert summary.sample_count == 7
assert summary.active_sample_count == 3
assert summary.inactive_sample_count == 4
assert summary.invalid_sample_count == 7
assert summary.average_line_speed_m_min == 3
assert summary.minimum_active_speed_m_min == 1
assert summary.maximum_active_speed_m_min == 6
assert summary.machine_id == CONFIG.machine_id
assert summary.speed_signal_ref == CONFIG.speed_signal_ref
assert summary.production_gate_m_min == 0.5
assert summary.unit == "m/min"
with pytest.raises(FrozenInstanceError):
summary.sample_count = 1
with pytest.raises(FrozenInstanceError):
CONFIG.production_gate_m_min = 0
@pytest.mark.parametrize("values", [[], [None, float("nan")], [-1, 0, 0.5]])
def test_no_active_samples(values):
summary = summarize(values)
assert summary.active_sample_count == 0
assert summary.average_line_speed_m_min is None
assert summary.minimum_active_speed_m_min is None
assert summary.maximum_active_speed_m_min is None
def test_sample_mean_is_not_time_weighted():
samples = [ShiftSpeedSample(START, 1), ShiftSpeedSample(END - timedelta(seconds=1), 9)]
summary = aggregate_shift_speed(samples, config=CONFIG, start=START, end=END)
assert summary.average_line_speed_m_min == 5
def test_exact_boundaries_and_missing_timestamps():
samples = [
ShiftSpeedSample(START - timedelta(microseconds=1), 100),
ShiftSpeedSample(START, 2),
ShiftSpeedSample(END - timedelta(microseconds=1), 4),
ShiftSpeedSample(END, 200),
ShiftSpeedSample(END + timedelta(seconds=1), None),
ShiftSpeedSample(None, 10),
ShiftSpeedSample(START.replace(tzinfo=None), 10),
]
summary = aggregate_shift_speed(samples, config=CONFIG, start=START, end=END)
assert summary.average_line_speed_m_min == 3
assert summary.sample_count == 2
assert summary.invalid_sample_count == 2
@pytest.mark.parametrize("start,end", [
(START.replace(tzinfo=None), END), (START, END.replace(tzinfo=None)),
(START, START), (END, START),
])
def test_invalid_windows_fail_before_gateway(start, end):
gateway = Mock()
with pytest.raises(ValueError):
ShiftSpeedService(gateway).summarize(config=CONFIG, start=start, end=end)
gateway.get_speed_samples.assert_not_called()
with pytest.raises(ValueError):
aggregate_shift_speed([], config=CONFIG, start=start, end=end)
client = Mock()
with pytest.raises(ValueError):
EnlyzeApiGateway(client).get_speed_samples(
machine_id="machine", speed_signal_ref="speed", start=start, end=end,
)
client.post_json.assert_not_called()
def test_dst_fold_compares_elapsed_instants():
berlin = ZoneInfo("Europe/Berlin")
start = datetime(2026, 10, 25, 2, 30, tzinfo=berlin, fold=0)
end = start.replace(fold=1)
samples = [ShiftSpeedSample(start, 2),
ShiftSpeedSample(datetime(2026, 10, 25, 1, 20, tzinfo=UTC), 4),
ShiftSpeedSample(end, 100)]
summary = aggregate_shift_speed(samples, config=CONFIG, start=start, end=end)
assert summary.average_line_speed_m_min == 3
assert summary.active_sample_count == 2
@pytest.mark.parametrize("gate", [-1, None, True, "0.5", float("nan"), float("inf")])
def test_invalid_gate_rejected(gate):
with pytest.raises(ValueError):
replace(CONFIG, production_gate_m_min=gate)
def test_zero_gate_excludes_zero_and_negative():
summary = aggregate_shift_speed(
[ShiftSpeedSample(START, value) for value in [-1, 0, 1]],
config=replace(CONFIG, production_gate_m_min=0), start=START, end=END,
)
assert summary.active_sample_count == 1
assert summary.average_line_speed_m_min == 1
def test_boolean_gate_uses_status_instead_of_numeric_threshold():
config = replace(CONFIG, production_gate_m_min=None,
running_signal_ref="status", running_when=False)
samples = [ShiftSpeedSample(START + timedelta(seconds=i), speed, status)
for i, (speed, status) in enumerate([
(0, False), (0.2, False), (8, True), (4, False),
(6, None), (7, 0), (9, "false"), (None, False),
])]
summary = aggregate_shift_speed(samples, config=config, start=START, end=END)
assert (summary.sample_count, summary.active_sample_count,
summary.inactive_sample_count, summary.invalid_sample_count) == (4, 3, 1, 4)
assert summary.average_line_speed_m_min == pytest.approx(4.2 / 3)
assert summary.minimum_active_speed_m_min == 0
assert summary.maximum_active_speed_m_min == 4
def test_boolean_gate_defaults_to_true_and_unweighted_mean():
config = replace(CONFIG, production_gate_m_min=None, running_signal_ref="status")
samples = [ShiftSpeedSample(START, 1, True),
ShiftSpeedSample(END - timedelta(seconds=1), 9, True),
ShiftSpeedSample(START, 100, False)]
summary = aggregate_shift_speed(samples, config=config, start=START, end=END)
assert summary.average_line_speed_m_min == 5
assert summary.inactive_sample_count == 1
DWELL = NumericDwellGate("gate", 50, "below", 150)
def dwell_summary(rows, gate=DWELL):
config = replace(CONFIG, production_gate_m_min=None, numeric_dwell_gate=gate)
samples = [ShiftSpeedSample(START + timedelta(seconds=second), speed,
gate_value=value)
for second, speed, value in rows]
return aggregate_shift_speed(samples, config=config, start=START, end=END)
@pytest.mark.parametrize("duration,expected_inactive", [(149, 0), (150, 2), (230, 2)])
def test_dwell_duration_includes_first_crossing(duration, expected_inactive):
summary = dwell_summary([(-1, 1, 50), (0, 2, 49), (duration - 1, 4, 49),
(duration, 8, 50)])
assert summary.inactive_sample_count == expected_inactive
assert summary.active_sample_count == 3 - expected_inactive
assert summary.average_line_speed_m_min == (8 if expected_inactive else 14 / 3)
def test_separate_short_excursions_do_not_merge_and_equality_is_active():
summary = dwell_summary([(-10, 1, 50), (0, 2, 49), (80, 3, 50),
(100, 4, 49), (200, 5, 50)])
assert summary.active_sample_count == 4
assert summary.inactive_sample_count == 0
assert summary.average_line_speed_m_min == 3.5
def test_irregular_timestamps_use_elapsed_time_and_arithmetic_mean():
summary = dwell_summary([(-5, 1, 50), (0, 2, 49), (7, 4, 49),
(149, 6, 49), (150, 8, 50), (200, 10, 50)])
assert summary.inactive_sample_count == 3
assert summary.average_line_speed_m_min == 9
@pytest.mark.parametrize("bad", [None, float("nan"), float("inf"), "49", True])
def test_invalid_dwell_gate_breaks_interval_and_excludes_speed(bad):
summary = dwell_summary([(-1, 1, 50), (0, 2, 49), (50, 3, bad),
(100, 4, 49), (200, 5, 50)])
assert summary.active_sample_count == 1
assert summary.invalid_sample_count == 3
assert summary.average_line_speed_m_min == 5
def test_open_short_dwell_interval_is_unknown_at_window_boundary():
summary = dwell_summary([(0, 2, 49), (10, 4, 49)])
assert summary.sample_count == 0
assert summary.invalid_sample_count == 2
def test_dwell_uses_both_sides_of_window_for_classification():
summary = dwell_summary([(-150, 1, 49), (0, 2, 49), (30, 4, 50),
(END.timestamp() - START.timestamp() - 1, 6, 49),
(END.timestamp() - START.timestamp() + 149, 8, 50)])
assert summary.inactive_sample_count == 2
assert summary.active_sample_count == 1
assert summary.average_line_speed_m_min == 4
@pytest.mark.parametrize("changes", [
{"running_signal_ref": ""}, {"running_signal_ref": "speed"},
{"running_signal_ref": 123}, {"running_when": 0},
{"production_gate_m_min": None},
])
def test_invalid_boolean_configuration_rejected(changes):
with pytest.raises(ValueError):
replace(CONFIG, **changes)
def test_large_finite_speeds_do_not_overflow_mean():
assert summarize([1e308, 1e308]).average_line_speed_m_min == 1e308
def test_service_composes_gateway_and_propagates_read_failure():
gateway = Mock()
gateway.get_speed_samples.return_value = [ShiftSpeedSample(START, 2)]
service = ShiftSpeedService(gateway)
assert service.summarize(config=CONFIG, start=START, end=END).average_line_speed_m_min == 2
gateway.get_speed_samples.assert_called_once_with(
machine_id="machine", speed_signal_ref="speed", start=START, end=END,
)
gateway.get_speed_samples.side_effect = RuntimeError("read failed")
with pytest.raises(RuntimeError, match="read failed"):
service.summarize(config=CONFIG, start=START, end=END)
def page(records, cursor=None, columns=None):
return Mock(body={"data": {"columns": columns or ["time", "speed"], "records": records},
"metadata": {"next_cursor": cursor}})
def test_gateway_pagination_column_order_and_unavailable_samples():
client = Mock()
client.post_json.side_effect = [
page([[2, START.isoformat()], [None, START.isoformat()]], "next", ["speed", "time"]),
page([[START.isoformat(), 4], [START.isoformat(), float("nan")],
["invalid-time", 3], None, [START.isoformat()]]),
]
summary = ShiftSpeedService(EnlyzeApiGateway(client)).summarize(
config=CONFIG, start=START, end=END,
)
assert summary.average_line_speed_m_min == 3
assert summary.sample_count == 2
assert summary.invalid_sample_count == 5
body = {"machine": "machine", "start": START.astimezone(UTC).isoformat(),
"end": END.astimezone(UTC).isoformat(), "variables": [{"uuid": "speed"}]}
assert client.post_json.call_args_list[0].args == ("/v2/timeseries", body)
assert client.post_json.call_args_list[1].args == ("/v2/timeseries", {**body, "cursor": "next"})
def test_gateway_two_variable_response_and_single_request():
client = Mock()
client.post_json.return_value = page([
[False, 0.2, START.isoformat()], [True, 10, START.isoformat()],
[None, 20, START.isoformat()], [START.isoformat()],
], columns=["status", "speed", "time"])
config = replace(CONFIG, production_gate_m_min=None,
running_signal_ref="status", running_when=False)
summary = ShiftSpeedService(EnlyzeApiGateway(client)).summarize(
config=config, start=START, end=END)
assert summary.average_line_speed_m_min == 0.2
assert (summary.active_sample_count, summary.inactive_sample_count,
summary.invalid_sample_count) == (1, 1, 2)
assert client.post_json.call_count == 1
assert client.post_json.call_args.args[1]["variables"] == [
{"uuid": "speed"}, {"uuid": "status"}]
def test_gateway_requires_status_column_when_configured():
client = Mock()
client.post_json.return_value = page([], columns=["time", "speed"])
with pytest.raises(ValueError, match="required columns"):
EnlyzeApiGateway(client).get_speed_samples(
machine_id="machine", speed_signal_ref="speed", running_signal_ref="status",
start=START, end=END)
def test_dwell_gateway_requests_both_signals_with_expanded_window():
client = Mock()
client.post_json.return_value = page([
[50, START.isoformat(), 1],
[49, (START + timedelta(seconds=10)).isoformat(), 2],
[49, (START + timedelta(seconds=160)).isoformat(), 4],
[50, (START + timedelta(seconds=170)).isoformat(), 8],
], columns=["gate", "time", "speed"])
config = replace(CONFIG, production_gate_m_min=None, numeric_dwell_gate=DWELL)
summary = ShiftSpeedService(EnlyzeApiGateway(client)).summarize(
config=config, start=START, end=END)
assert summary.average_line_speed_m_min == 4.5
assert summary.inactive_sample_count == 2
assert client.post_json.call_count == 1
body = client.post_json.call_args.args[1]
assert body["variables"] == [{"uuid": "speed"}, {"uuid": "gate"}]
assert body["start"] == (START - timedelta(seconds=150)).astimezone(UTC).isoformat()
assert body["end"] == (END + timedelta(seconds=150)).astimezone(UTC).isoformat()
@pytest.mark.parametrize("body", [
{"data": {"columns": ["time"], "records": []}},
{"data": {"columns": ["time", "speed", "speed"], "records": []}},
{"data": {"columns": ["time", "speed"], "records": None}},
{"data": {"columns": ["time", "speed"], "records": []}, "metadata": {}},
])
def test_gateway_structural_errors_fail_read(body):
client = Mock()
client.post_json.return_value = Mock(body=body)
with pytest.raises(ValueError, match="Invalid speed timeseries response"):
EnlyzeApiGateway(client).get_speed_samples(
machine_id="machine", speed_signal_ref="speed", start=START, end=END,
)
def test_gateway_repeated_cursor_rejected():
client = Mock()
client.post_json.side_effect = [page([], "same"), page([], "same")]
with pytest.raises(ValueError, match="already been followed"):
EnlyzeApiGateway(client).get_speed_samples(
machine_id="machine", speed_signal_ref="speed", start=START, end=END,
)
assert client.post_json.call_count == 2
@pytest.mark.parametrize("name,machine,signal,gate", [
("B1", "5f42a4f6-9ca0-4f6f-9786-40d50a35b230", "fef41976-1103-4090-b780-eaeecc02fdfa", 0.3),
("E1", "8302e3d1-b1e5-42f1-8540-615eb6c73e08", "488e28a9-79a6-44c4-9cc2-c021bb2108ec", 0.5),
("K7", "c220f95c-a65e-4cb7-99b7-0626d6c7508c", "823867bb-f5d2-40eb-b875-657155addfd0", 0.5),
])
def test_validated_machine_configuration(name, machine, signal, gate):
config = load_shift_report_machines(CONFIG_PATH)[name].speed
assert config.machine_id == machine
assert config.speed_signal_ref == signal
assert config.production_gate_m_min == gate
assert config.unit == "m/min"
assert config.signal
@pytest.mark.parametrize("name,speed,gate,threshold", [
("Gitter 1", "33abccf8-8dee-4b40-b0ce-63c3c0fd2cd9",
"620511e3-a46b-47c4-8514-f2d4bde29e2b", 50),
("Gitter 2", "d3acefd8-1013-4b59-a235-fa265fd85fae",
"1ae8fb5d-1d25-414a-9181-d35b6cdde507", 27000),
("Gitter 3", "88641764-6fd1-4733-a054-80fa43a62470",
"f78bd11f-b2a8-4454-86a0-c8de576799c2", 31000),
("Gitter 4", "1d7660d4-10f4-4466-b1fd-076f9fd504fe",
"5685fb13-861d-4e95-8a98-e39d4fc3e059", 2),
])
def test_dwell_machine_configuration(name, speed, gate, threshold):
machine = load_shift_report_machines(CONFIG_PATH)[name]
assert machine.capabilities.speed and not machine.capabilities.material
assert machine.speed.speed_signal_ref == speed
assert machine.speed.numeric_dwell_gate.signal_ref == gate
assert machine.speed.numeric_dwell_gate.threshold == threshold
assert machine.speed.numeric_dwell_gate.comparison == "below"
assert machine.speed.numeric_dwell_gate.minimum_duration_seconds == 150
assert machine.speed.running_signal_ref is None
assert machine.speed.production_gate_m_min is None
def test_k5_boolean_machine_configuration():
config = load_shift_report_machines(CONFIG_PATH)["K5"].speed
assert config.speed_signal_ref == "c3ae3002-b75c-4d7c-bb33-f10265fcf428"
assert config.running_signal_ref == "507b1225-2992-4dd1-8412-34969466722f"
assert config.running_when is False
assert config.numeric_dwell_gate is None
summary = aggregate_shift_speed([
ShiftSpeedSample(START, 1, False),
ShiftSpeedSample(START + timedelta(seconds=1), 9, True),
ShiftSpeedSample(START + timedelta(seconds=2), 10, None),
], config=config, start=START, end=END)
assert summary.average_line_speed_m_min == 1
assert (summary.active_sample_count, summary.inactive_sample_count,
summary.invalid_sample_count) == (1, 1, 1)
@pytest.mark.parametrize("change", [
{"running_signal_ref": "status"}, {"running_when": False},
{"production_gate_m_min": 0.5}, {"unexpected": True},
{"numeric_dwell_gate": {"signal_ref": "gate"}},
{"numeric_dwell_gate": {"signal_ref": "gate", "threshold": 50,
"comparison": "below", "minimum_duration_seconds": 0}},
{"numeric_dwell_gate": {"signal_ref": "gate", "threshold": float("nan"),
"comparison": "below", "minimum_duration_seconds": 150}},
])
def test_dwell_yaml_validation(tmp_path, change):
document = deepcopy(yaml.safe_load(CONFIG_PATH.read_text()))
document["machines"]["Gitter 2"]["speed"].update(change)
path = tmp_path / "machines.yaml"
path.write_text(yaml.safe_dump(document))
with pytest.raises(ValueError):
load_shift_report_machines(path)
@pytest.mark.parametrize("document", ["machines: {}", "other: {}", "machines: []",
"machines:\n B1: {}", "machines:\n B1: null"])
def test_invalid_configuration(tmp_path, document):
path = tmp_path / "machines.yaml"
path.write_text(document)
with pytest.raises(ValueError):
load_shift_report_machines(path)