diff --git a/.gitignore b/.gitignore
index ff02673..c101613 100644
--- a/.gitignore
+++ b/.gitignore
@@ -32,3 +32,5 @@ activate.sh
# Live polling checkpoints
data/state/
+
+data/backup-spreader3/
diff --git a/README.md b/README.md
index bd9045e..af46644 100644
--- a/README.md
+++ b/README.md
@@ -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).
diff --git a/config/bento1-material-consumption.yaml b/config/bento1-material-consumption.yaml
index 3661d2a..a29e219 100644
--- a/config/bento1-material-consumption.yaml
+++ b/config/bento1-material-consumption.yaml
@@ -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
diff --git a/config/bento1-spreader3-material-consumption.yaml b/config/bento1-spreader3-material-consumption.yaml
index e8f49a8..99114ca 100644
--- a/config/bento1-spreader3-material-consumption.yaml
+++ b/config/bento1-spreader3-material-consumption.yaml
@@ -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
diff --git a/config/e4-downtime.yaml b/config/e4-downtime.yaml
new file mode 100644
index 0000000..08d6f56
--- /dev/null
+++ b/config/e4-downtime.yaml
@@ -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
diff --git a/config/gitter1-downtime.yaml b/config/gitter1-downtime.yaml
new file mode 100644
index 0000000..fca38d6
--- /dev/null
+++ b/config/gitter1-downtime.yaml
@@ -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
diff --git a/config/gitter2-downtime.yaml b/config/gitter2-downtime.yaml
new file mode 100644
index 0000000..b7a6cc5
--- /dev/null
+++ b/config/gitter2-downtime.yaml
@@ -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
diff --git a/config/gitter3-downtime.yaml b/config/gitter3-downtime.yaml
new file mode 100644
index 0000000..052e18d
--- /dev/null
+++ b/config/gitter3-downtime.yaml
@@ -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
diff --git a/config/gitter4-downtime.yaml b/config/gitter4-downtime.yaml
new file mode 100644
index 0000000..7a4bf29
--- /dev/null
+++ b/config/gitter4-downtime.yaml
@@ -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
diff --git a/config/historical-order-formats.yaml b/config/historical-order-formats.yaml
new file mode 100644
index 0000000..b938f96
--- /dev/null
+++ b/config/historical-order-formats.yaml
@@ -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}'
diff --git a/config/k5-downtime.yaml b/config/k5-downtime.yaml
new file mode 100644
index 0000000..9af0ded
--- /dev/null
+++ b/config/k5-downtime.yaml
@@ -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
diff --git a/config/secumat12-downtime.yaml b/config/secumat12-downtime.yaml
new file mode 100644
index 0000000..865d513
--- /dev/null
+++ b/config/secumat12-downtime.yaml
@@ -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
diff --git a/config/secumat3-downtime.yaml b/config/secumat3-downtime.yaml
new file mode 100644
index 0000000..535cea2
--- /dev/null
+++ b/config/secumat3-downtime.yaml
@@ -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
diff --git a/config/shift-report-machines.yaml b/config/shift-report-machines.yaml
index f5a0547..0346c11 100644
--- a/config/shift-report-machines.yaml
+++ b/config/shift-report-machines.yaml
@@ -1,7 +1,24 @@
+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:
@@ -13,8 +30,15 @@ machines:
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:
@@ -25,14 +49,184 @@ machines:
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
diff --git a/db/historical_assignment_audit.sql b/db/historical_assignment_audit.sql
new file mode 100644
index 0000000..0e1eaaa
--- /dev/null
+++ b/db/historical_assignment_audit.sql
@@ -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);
diff --git a/db/schema.sql b/db/schema.sql
index 67fdafe..60306b8 100644
--- a/db/schema.sql
+++ b/db/schema.sql
@@ -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);
diff --git a/deploy/systemd/README-downtime.md b/deploy/systemd/README-downtime.md
new file mode 100644
index 0000000..cc0d396
--- /dev/null
+++ b/deploy/systemd/README-downtime.md
@@ -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`.
diff --git a/deploy/systemd/production-analytics-downtime-e4.service b/deploy/systemd/production-analytics-downtime-e4.service
new file mode 100644
index 0000000..6a55cbd
--- /dev/null
+++ b/deploy/systemd/production-analytics-downtime-e4.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
diff --git a/deploy/systemd/production-analytics-downtime-gitter1.service b/deploy/systemd/production-analytics-downtime-gitter1.service
new file mode 100644
index 0000000..e149249
--- /dev/null
+++ b/deploy/systemd/production-analytics-downtime-gitter1.service
@@ -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
diff --git a/deploy/systemd/production-analytics-downtime-gitter2.service b/deploy/systemd/production-analytics-downtime-gitter2.service
new file mode 100644
index 0000000..c5ee8cb
--- /dev/null
+++ b/deploy/systemd/production-analytics-downtime-gitter2.service
@@ -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
diff --git a/deploy/systemd/production-analytics-downtime-gitter3.service b/deploy/systemd/production-analytics-downtime-gitter3.service
new file mode 100644
index 0000000..50be58b
--- /dev/null
+++ b/deploy/systemd/production-analytics-downtime-gitter3.service
@@ -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
diff --git a/deploy/systemd/production-analytics-downtime-gitter4.service b/deploy/systemd/production-analytics-downtime-gitter4.service
new file mode 100644
index 0000000..0550c9f
--- /dev/null
+++ b/deploy/systemd/production-analytics-downtime-gitter4.service
@@ -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
diff --git a/deploy/systemd/production-analytics-downtime-k5.service b/deploy/systemd/production-analytics-downtime-k5.service
new file mode 100644
index 0000000..71c2c2a
--- /dev/null
+++ b/deploy/systemd/production-analytics-downtime-k5.service
@@ -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
diff --git a/deploy/systemd/production-analytics-downtime-secumat12.service b/deploy/systemd/production-analytics-downtime-secumat12.service
new file mode 100644
index 0000000..265c5bd
--- /dev/null
+++ b/deploy/systemd/production-analytics-downtime-secumat12.service
@@ -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
diff --git a/deploy/systemd/production-analytics-downtime-secumat3.service b/deploy/systemd/production-analytics-downtime-secumat3.service
new file mode 100644
index 0000000..b7c99f2
--- /dev/null
+++ b/deploy/systemd/production-analytics-downtime-secumat3.service
@@ -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
diff --git a/deploy/systemd/production-analytics-historical-reconcile.service b/deploy/systemd/production-analytics-historical-reconcile.service
new file mode 100644
index 0000000..23d15f5
--- /dev/null
+++ b/deploy/systemd/production-analytics-historical-reconcile.service
@@ -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
diff --git a/deploy/systemd/production-analytics-historical-reconcile.timer b/deploy/systemd/production-analytics-historical-reconcile.timer
new file mode 100644
index 0000000..b25ad07
--- /dev/null
+++ b/deploy/systemd/production-analytics-historical-reconcile.timer
@@ -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
diff --git a/docs/historical-reconciliation.md b/docs/historical-reconciliation.md
new file mode 100644
index 0000000..79eba5c
--- /dev/null
+++ b/docs/historical-reconciliation.md
@@ -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.
diff --git a/docs/shift-report.md b/docs/shift-report.md
index 58f65fc..8ee45fa 100644
--- a/docs/shift-report.md
+++ b/docs/shift-report.md
@@ -4,17 +4,35 @@
speed services sequentially. It performs no database or HTTP reads itself and
adds no quantity or interval aggregation. Its frozen `ShiftReport` reuses all
four immutable summary models directly, preserving source metadata and items
-for later PDF or SSR rendering. Neither renderer is implemented here.
+for PDF output and the live web UI. Presentation lives separately in
+`presentation.shift_report`; report composition remains output-independent.
## Configuration and API
`config/shift-report-machines.yaml` is self-contained for composition:
```yaml
+sites:
+ espelkamp:
+ display_name: Espelkamp
+ timezone: Europe/Berlin
+ adorf:
+ display_name: Adorf
+ timezone: Europe/Berlin
+ malaysia:
+ display_name: Malaysia
+ timezone: Asia/Kuala_Lumpur
machines:
B1:
+ display_name: B1
+ site: espelkamp
machine_id: 5f42a4f6-9ca0-4f6f-9786-40d50a35b230
erp_workplace: BENTO 1
+ capabilities:
+ production: true
+ downtime: true
+ material: true
+ speed: true
material:
mode: cumulative
calculation_ids:
@@ -27,9 +45,20 @@ machines:
production_gate_m_min: 0.3
```
+Every machine requires a display name, configured site, ERP workplace, and all four
+boolean capability flags; at least one capability must be enabled. A machine ID is
+required for downtime, material, or speed, but may be absent for production-only
+machines. Material and speed configuration are required
+exactly when their capability is enabled. Material modes remain `cumulative` and
+`channel`; optional `allocation` is `none` (default) or `erp_fiber_share`. K7 selects
+the latter through configuration. `load_shift_report_config()` exposes immutable
+site and machine mappings; `load_shift_report_machines()` retains the machine-only
+view used by historical reconciliation.
+
The loader returns `ShiftReportMachineConfig` values with frozen material and
speed configurations. Speed-only consumers now use `machines[name].speed`.
-Missing/unknown fields, duplicate YAML keys or machine IDs, unsupported material
+Missing/unknown fields, duplicate YAML keys or non-null machine IDs, invalid site
+timezones, unsupported material
modes, empty/duplicate calculation IDs, and invalid speed metadata are rejected.
No unrelated YAML configuration is loaded at runtime.
@@ -45,16 +74,16 @@ service = ShiftReportService(
channel_materials=channel_material_service,
speed=speed_service,
)
-start, end = shift_report_window(day, "early")
+start, end = shift_report_window(day, "early", machines["B1"].timezone)
report = service.build(machine_name="B1", start=start, end=end)
```
`shift_report_window` lives in `calculations.shift_report`; the loader and
service live in `service.shift_report_config` and `service.shift_report`.
-The day is the shift's start date in Europe/Berlin. Early is 06:00–14:00, late is
+The day is the shift's start date in the machine site's timezone. Early is 06:00–14:00, late is
14:00–22:00, and night is 22:00–06:00 on the following day. Night shifts can have
seven or nine elapsed hours at DST transitions. Explicit windows are validated
-as aware, positive-duration instants and normalized to Berlin for all service
+as aware, positive-duration instants and normalized to the site timezone for all service
calls. All source services retain their `[start, end)` semantics.
## Source semantics
@@ -62,6 +91,9 @@ calls. All source services retain their `[start, end)` semantics.
Production uses the existing finished-goods ERP service with workplaces B1:
`BENTO 1`, E1: `1568705`, and K7: `K7`. Its order/article groups, m², roll counts,
and first/last confirmation timestamps remain available in `report.production`.
+The ERP SQL query uses naive site-local `[start, end)` timestamps, and returned
+confirmations are attached to the configured IANA timezone. Historical
+reconciliation retains its Europe/Berlin default.
`report.downtime.non_downtime_seconds` is the elapsed shift duration minus the
union of downtime intervals. It is a time complement and does not measure actual
@@ -84,8 +116,108 @@ Speed is the arithmetic sample mean strictly above the configured production
gate: average speed while running, not average speed over the full shift.
Counts, gate, and active min/max are preserved in `report.speed`.
-Every source is mandatory. Exceptions propagate immediately and later services
-are not called. An empty successful summary remains an empty summary; a failed
+Every enabled source is mandatory. Disabled sections are `None` in the report and
+render as unavailable; no source is queried for them. Exceptions propagate
+immediately and later services are not called. An empty successful summary remains
+an empty summary; a failed
read is never replaced with zeros. No cross-source matching of runs or orders is
introduced, and sequential reads are not a transactionally consistent snapshot
across ERP, PostgreSQL, and ENLYZE.
+
+## Generate an explicit shift PDF
+
+Install the project with `pip install -e '.[dev]'`. Shift PDFs use the declared
+`reportlab>=4.2,<5` dependency: a direct PDF writer without an external browser
+or native HTML rendering stack. The older monthly energy report remains separate.
+
+Run from the repository root, with access to the existing read-only sources:
+
+```bash
+production-analytics report shift --machine E1 \
+ --start '2026-10-07T06:00:00+02:00' \
+ --end '2026-10-07T14:00:00+02:00' \
+ --output data/reports/E1_2026-10-07_early.pdf
+```
+
+The PDF is written exactly to `--output`, relative to the working directory for
+relative paths. Parent directories are created, and an existing file is replaced
+only after rendering succeeds. No sidecar HTML is written. B1, E1, and K7 are
+configured in `config/shift-report-machines.yaml`; override with `--config`.
+Start and end are mandatory ISO 8601 timestamps with offsets (or `Z`); the end
+must follow the start. There is no implicit current-shift selection.
+
+Settings are read from the process environment, overlaid by these dotenv files:
+
+- `secrets/enlyze.env` (`--secrets-file`): `ENLYZE_BASE_URL`, `ENLYZE_API_KEY`,
+ optional `ENLYZE_HTTP_TIMEOUT_SECONDS`.
+- `secrets/erp.env` (`--erp-secrets-file`): `ERP_DB_HOST`, `ERP_DB_PORT`,
+ `ERP_DB_NAME`, `ERP_DB_USER`, `ERP_DB_PASSWORD`.
+- `secrets/postgres.env` (`--db-secrets-file`): `POSTGRES_HOST`, `POSTGRES_PORT`,
+ `POSTGRES_DB`, `POSTGRES_USER`, `POSTGRES_PASSWORD`.
+
+PostgreSQL must already contain the existing downtime and material snapshots;
+this command performs no collection or polling. ERP supplies production and
+ENLYZE supplies speed through the existing readers. Source failures fail the
+command; empty successful summaries receive explicit German empty-state text.
+Validation/configuration errors return exit code 2; other failures return 1.
+
+The A4 slip includes production, supplied totals, downtime with the top three
+reasons, material consumption including channel identities, and running speed.
+Numbers use German separators with two decimal places. Durations retain hours,
+minutes, and tenths of seconds. Times display the report site's timezone and
+numeric offsets, including across daylight-saving transitions. Missing material
+names are explicitly marked `Nicht verfügbar`; no identity is inferred. B1
+source assignments are rendered unchanged, and energy is excluded.
+
+`present_report(report)` returns an immutable, deterministic presentation model;
+`render_pdf(report)` returns PDF bytes and `write_pdf(report, output)` writes them.
+Only the supplied `ShiftReport` is consumed. Fixed ReportLab invariant metadata,
+styles, fonts, and no generated-at clock make PDF bytes repeatable for the same
+input and installed ReportLab version. Bytes are not promised identical across
+library versions. Long reports paginate with repeated table headers and page
+numbers. The domain report is also the input for the live web presenter.
+
+
+## Live web interface
+
+The website is the primary working interface; PDF is an export/archive artifact.
+Run from the repository root:
+
+```bash
+.venv/bin/python -m production_analytics.web --port 8087
+```
+
+Open . 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.
diff --git a/docs/shift-speed.md b/docs/shift-speed.md
index a946420..aa995d6 100644
--- a/docs/shift-speed.md
+++ b/docs/shift-speed.md
@@ -1,59 +1,61 @@
# Shift running-speed KPI
-`average_line_speed_m_min` is the arithmetic mean of finite speed samples
-strictly above the configured production gate within `[start, end)`. Samples
-have equal weight regardless of spacing. Inactive time does not contribute to
-this KPI. No interpolation, carry-forward, or time weighting is applied.
+`average_line_speed_m_min` is the arithmetic mean of active, finite production-speed
+samples in `[start, end)`. Each active sample has equal weight. The calculation does
+not interpolate or weight speed by elapsed time.
-The immutable summary includes signal, unit, gate, window, finite sample count,
-active/inactive counts, active average/minimum/maximum, and invalid sample count.
-`sample_count` counts finite numeric in-window values and equals active plus
-inactive counts. Zero, negative, and values equal to or below the gate are
-inactive. Null, non-numeric, boolean, NaN, and infinite values are invalid and
-excluded from all finite/active statistics. Invalid/missing timestamps are also
-counted separately as unavailable because window membership cannot be verified.
-Absent source rows are not synthesized or counted. Without active samples,
-average, minimum, and maximum are all `None`.
+## Activity gates
-Window timestamps must be timezone aware and have positive elapsed duration.
-All boundary comparisons use UTC instants, including DST folds.
+The `speed` block has exactly one activity method:
-## Configuration and service API
+- **Simple numeric:** `production_gate_m_min` selects speed samples strictly above
+ the threshold. B1, E1 and K7 retain this behavior.
+- **Boolean:** `running_signal_ref` and optional `running_when` (default `true`)
+ select samples whose status is exactly that Boolean. K5 uses `running_when: false`
+ because its status signal is true when stopped.
+- **Numeric dwell:** `numeric_dwell_gate` has `signal_ref`, finite `threshold`,
+ `comparison` (`below` or `above`), and positive integer
+ `minimum_duration_seconds`. Gitter 1–4 use `below` and 150 seconds. Their
+ production-speed signal holds its last value while stopped, and their PLC
+ Boolean status did not reliably indicate downtime. The numeric gate follows
+ the configured ENLYZE threshold and minimum duration concept.
-Machine-specific UUIDs, signal labels, units, and gates live in
-`config/shift-report-machines.yaml`. It also contains the ERP workplace and material source references needed for
-report composition; existing material-calculation definitions are not duplicated. The configured gates are
-B1: 0.3 m/min; E1: 0.5 m/min; K7: 0.5 m/min. The config loader validates required
-fields, non-empty identifiers, unique machine IDs, m/min units, and finite
-non-negative gates. It returns frozen report machine configurations by name, each with a nested
-`ShiftSpeedConfig` in `.speed`.
+For `below`, only a gate value strictly less than the threshold satisfies the
+condition. An equal value ends a below-threshold run. Rows are ordered by their
+UTC timestamps; a condition reading remains the observed state until the next
+reading. A continuous below-threshold run qualifies when the elapsed time from
+its first below-threshold timestamp to the first non-below reading is at least
+the minimum duration. If it qualifies, **all** speed samples in that run are
+inactive, including those before the minimum duration elapsed. A short run
+bracketed by non-below readings stays active. The same rules apply to `above`.
+The interval ending at the non-satisfying reading excludes that reading.
-```python
-from datetime import datetime
-from zoneinfo import ZoneInfo
+The service requests speed and the gate signal together from `/v2/timeseries`.
+For a dwell gate it extends the read window by one minimum duration on each side;
+only production-speed samples in the original report window enter the KPI. This
+lets a qualifying run crossing a report boundary be classified when the source
+provides enough surrounding readings. An unclosed short run, or a short run
+without a preceding non-satisfying reading, has unknown duration and is excluded
+conservatively. An invalid or non-finite gate reading breaks continuity and its
+speed row is excluded. A missing required gate column fails the read. No absent
+rows are synthesized; the result depends on the timestamps returned by ENLYZE,
+which deserves validation against live boundary cases.
-from production_analytics.enlyze.gateway import EnlyzeApiGateway
-from production_analytics.service.shift_report_config import load_shift_report_machines
-from production_analytics.service.shift_speed import ShiftSpeedService
+Invalid speed values (including Boolean, null, non-numeric, NaN, and infinity)
+are excluded in every mode. Invalid timestamps are also excluded. In Boolean
+mode, missing or non-Boolean status is excluded. `sample_count` is the sum of
+active and inactive valid speed samples; excluded samples increment
+`invalid_sample_count`. If no active samples remain, average, minimum and maximum
+are `None`.
-machines = load_shift_report_machines("config/shift-report-machines.yaml")
-service = ShiftSpeedService(EnlyzeApiGateway(client)) # Existing ExplorationClient
-summary = service.summarize(
- config=machines["K7"].speed,
- start=datetime(2026, 10, 7, 6, tzinfo=ZoneInfo("Europe/Berlin")),
- end=datetime(2026, 10, 7, 14, tzinfo=ZoneInfo("Europe/Berlin")),
-)
-```
+Machine UUIDs and gate settings live in `config/shift-report-machines.yaml`.
+The loader validates the gate fields and rejects overlapping Boolean and dwell
+gates. `ShiftSpeedService.summarize()` composes the gateway read with the pure
+`aggregate_shift_speed()` calculation. The calculation accepts
+`ShiftSpeedSample(timestamp, value, running, gate_value)` records. Structural
+timeseries and pagination errors fail the read instead of returning a partial KPI.
-`aggregate_shift_speed(samples, config=..., start=..., end=...)` is the pure
-calculation API, accepting `ShiftSpeedSample(timestamp, value)` objects.
-`EnlyzeApiGateway.get_speed_samples(machine_id=..., speed_signal_ref=...,
-start=..., end=...)` requests just the configured signal from `/v2/timeseries`,
-using the existing client and cursor semantics. It tolerates unavailable sample
-values/timestamps; structural response and pagination errors fail the read,
-preventing a partial successful summary. No snapshots are persisted.
-
-## Supplied live reference
+## Supplied legacy reference
For 2026-10-07 06:00–14:00 Europe/Berlin:
@@ -63,6 +65,4 @@ For 2026-10-07 06:00–14:00 Europe/Berlin:
| E1 | 2880 | 2782 | 7.933009468249328 |
| K7 | 2880 | 2667 | 10.078945039942955 |
-These are the supplied validation values, not a new live read performed during
-implementation. Tests cover filtering, statistics, boundary/DST behavior,
-configuration, service composition, and gateway pagination with mocked responses.
+These are supplied validation values, not a new live read.
diff --git a/pyproject.toml b/pyproject.toml
index b81cd83..72fe0e8 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -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"]
diff --git a/src/production_analytics/calculations/config.py b/src/production_analytics/calculations/config.py
index 0ddbc67..904cdf5 100644
--- a/src/production_analytics/calculations/config.py
+++ b/src/production_analytics/calculations/config.py
@@ -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:
diff --git a/src/production_analytics/calculations/fiber_allocation.py b/src/production_analytics/calculations/fiber_allocation.py
new file mode 100644
index 0000000..5efbe6b
--- /dev/null
+++ b/src/production_analytics/calculations/fiber_allocation.py
@@ -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
+ )
diff --git a/src/production_analytics/calculations/shift_downtime.py b/src/production_analytics/calculations/shift_downtime.py
index dd44aea..7de838d 100644
--- a/src/production_analytics/calculations/shift_downtime.py
+++ b/src/production_analytics/calculations/shift_downtime.py
@@ -1,4 +1,4 @@
-"""Machine-independent shift downtime from raw source intervals."""
+"""Machine-independent shift downtime from effective attribution intervals."""
from collections import defaultdict
from collections.abc import Iterable
@@ -18,6 +18,8 @@ class ShiftDowntimeEvent:
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"):
@@ -25,6 +27,10 @@ class ShiftDowntimeEvent:
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):
@@ -85,12 +91,12 @@ def validate_downtime_window(*, machine_id: str, start: datetime, end: datetime)
def aggregate_shift_downtime(
events: Iterable[ShiftDowntimeEvent], *, machine_id: str, start: datetime, end: datetime
) -> ShiftDowntimeSummary:
- """Clip source intervals to [start, end); open events end at the shift end.
+ """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.
- No production-order attribution fields participate in this calculation.
+ 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)
@@ -98,12 +104,16 @@ def aggregate_shift_downtime(
for event in events:
if event.machine_id != machine_id:
continue
- event_start = event.source_start.astimezone(UTC)
- event_end = upper if event.source_end is None else event.source_end.astimezone(UTC)
+ 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 event.source_start
- clipped_end = end if event.source_end is None or event_end > upper else event.source_end
+ 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))
diff --git a/src/production_analytics/calculations/shift_material.py b/src/production_analytics/calculations/shift_material.py
index ac82939..d7b2ba0 100644
--- a/src/production_analytics/calculations/shift_material.py
+++ b/src/production_analytics/calculations/shift_material.py
@@ -1,11 +1,13 @@
-"""Shift deltas from cumulative counters; no material identity is inferred."""
+"""Shift counter deltas with bounded, matching-identity channel gap bridging."""
from collections import defaultdict
from collections.abc import Iterable
-from dataclasses import dataclass
-from datetime import UTC, datetime
+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:
@@ -50,6 +52,7 @@ class ShiftMaterialItem:
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)
@@ -103,6 +106,7 @@ def aggregate_shift_material(
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
@@ -115,21 +119,24 @@ def aggregate_shift_material(
items = []
for rows in streams.values():
for run in _runs(rows, start, channel=False):
- first, last = run[0], run[-1]
_check_deltas(run, channel=False)
- items.append(
- ShiftMaterialItem(
- source="material_consumption_snapshots",
- calculation_id=first.calculation_id,
- machine_id=machine_id,
- production_order=first.production_order,
- run_id=first.run_id,
- consumption_kg=last.consumption_kg - first.consumption_kg,
- baseline_timestamp=first.timestamp,
- end_timestamp=last.timestamp,
- baseline_missing=_instant(first.timestamp) > _instant(start),
+ 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)
@@ -144,9 +151,9 @@ def aggregate_shift_channel_material(
) -> ShiftMaterialSummary:
"""For A -> B, attribute B.counter - A.counter to B's stored material identity.
- Null/blank names remain null: no last-known carry-forward. Consecutive intervals
- with the same number/name/status form one material segment. A -> null -> A
- remains three segments. Counters and run boundaries follow the generic rules.
+ 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
@@ -166,26 +173,22 @@ def aggregate_shift_channel_material(
for previous, current in intervals:
identity = _identity(current)
delta = current.cumulative_consumption_kg - previous.cumulative_consumption_kg
- if segments and segments[-1].identity == identity:
- segment = segments[-1]
- segment.last = current
- segment.deltas.append(delta)
- segment.quality = segment.quality and current.percentage_sum_valid
- else:
- segments.append(
- _ChannelSegment(
- identity, previous, current, [delta], current.percentage_sum_valid
- )
+ 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
- items.append(
+ segment_items.append(
ShiftMaterialItem(
source="channel_material_consumption_snapshots",
calculation_id=first.calculation_id,
machine_id=machine_id,
- production_order=first.production_order,
+ production_order=last.production_order,
run_id=first.run_id,
consumption_kg=fsum(segment.deltas),
baseline_timestamp=first.timestamp,
@@ -199,9 +202,84 @@ def aggregate_shift_channel_material(
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:])):
@@ -214,21 +292,16 @@ def _runs(rows, start, *, channel):
active -= 1
selected = ordered[active:]
runs = []
- seen = set()
for row in selected:
_identifier(row.run_id, "run_id")
_identifier(row.production_order, "production_order")
if not runs or runs[-1][-1].run_id != row.run_id:
- if row.run_id in seen:
- raise ValueError("Run reappeared after a different run in the same stream")
- seen.add(row.run_id)
runs.append([])
- if runs[-1] and runs[-1][-1].production_order != row.production_order:
- raise ValueError("Production order changed within a run")
runs[-1].append(row)
for run in runs:
valid = [
- row for row in run
+ 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)]
diff --git a/src/production_analytics/calculations/shift_report.py b/src/production_analytics/calculations/shift_report.py
index 1427404..fd77cc6 100644
--- a/src/production_analytics/calculations/shift_report.py
+++ b/src/production_analytics/calculations/shift_report.py
@@ -13,8 +13,6 @@ from production_analytics.calculations.shift_material import ShiftMaterialSummar
from production_analytics.calculations.shift_production import ShiftProductionSummary
from production_analytics.calculations.shift_speed import ShiftSpeedSummary
-SHIFT_TIMEZONE = ZoneInfo("Europe/Berlin")
-
@dataclass(frozen=True, slots=True)
class ShiftReportDowntimeReason:
@@ -25,17 +23,20 @@ class ShiftReportDowntimeReason:
@dataclass(frozen=True, slots=True)
class ShiftReport:
machine_name: str
- machine_id: str
+ machine_id: str | None
start: datetime
end: datetime
- production: ShiftProductionSummary
- downtime: ShiftDowntimeSummary
- materials: ShiftMaterialSummary
- speed: ShiftSpeedSummary
+ 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)
+ return len(self.downtime.events) if self.downtime is not None else 0
@property
def downtime_reasons(self) -> tuple[ShiftReportDowntimeReason, ...]:
@@ -46,7 +47,7 @@ class ShiftReport:
if reason.reason_name and reason.reason_name.strip()
else "Ohne Stillstandsgrund",
)
- for reason in self.downtime.reasons
+ for reason in (self.downtime.reasons if self.downtime is not None else ())
)
@property
@@ -56,21 +57,42 @@ class ShiftReport:
def shift_report_window(
- day: date, shift: Literal["early", "late", "night"],
+ day: date, shift: Literal["early", "late", "night"], timezone: ZoneInfo,
) -> tuple[datetime, datetime]:
- """Berlin wall-clock shifts; day denotes the shift's start date.
+ """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=SHIFT_TIMEZONE),
- datetime.combine(end_day, time(end_hour), tzinfo=SHIFT_TIMEZONE),
+ datetime.combine(day, time(start_hour), tzinfo=timezone),
+ datetime.combine(end_day, time(end_hour), tzinfo=timezone),
)
+
+
+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"
diff --git a/src/production_analytics/calculations/shift_speed.py b/src/production_analytics/calculations/shift_speed.py
index c1e29a6..20a7c24 100644
--- a/src/production_analytics/calculations/shift_speed.py
+++ b/src/production_analytics/calculations/shift_speed.py
@@ -7,22 +7,68 @@ 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
+ 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 gate is None or gate < 0:
+ 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):
@@ -33,6 +79,8 @@ class ShiftSpeedConfig:
class ShiftSpeedSample:
timestamp: datetime | None
value: object
+ running: object = None
+ gate_value: object = None
@dataclass(frozen=True, slots=True)
@@ -42,7 +90,7 @@ class ShiftSpeedSummary:
end: datetime
speed_signal_ref: str
unit: str
- production_gate_m_min: float
+ production_gate_m_min: float | None
sample_count: int
active_sample_count: int
inactive_sample_count: int
@@ -61,7 +109,7 @@ def aggregate_shift_speed(
samples: Iterable[ShiftSpeedSample], *, config: ShiftSpeedConfig,
start: datetime, end: datetime,
) -> ShiftSpeedSummary:
- """Count finite in-window samples; active iff value is strictly above gate.
+ """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
@@ -70,6 +118,9 @@ def aggregate_shift_speed(
"""
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:
@@ -84,8 +135,20 @@ def aggregate_shift_speed(
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 value > config.production_gate_m_min:
+ 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,
@@ -100,6 +163,47 @@ def aggregate_shift_speed(
)
+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
diff --git a/src/production_analytics/cli/__main__.py b/src/production_analytics/cli/__main__.py
index 466fe0a..1c8d325 100644
--- a/src/production_analytics/cli/__main__.py
+++ b/src/production_analytics/cli/__main__.py
@@ -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
diff --git a/src/production_analytics/enlyze/gateway.py b/src/production_analytics/enlyze/gateway.py
index 4b4fd0b..a4977a1 100644
--- a/src/production_analytics/enlyze/gateway.py
+++ b/src/production_analytics/enlyze/gateway.py
@@ -156,8 +156,10 @@ class EnlyzeApiGateway:
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 one bounded signal using the existing timeseries cursor contract.
+ """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
@@ -167,11 +169,25 @@ class EnlyzeApiGateway:
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": [{"uuid": speed_signal_ref}],
+ "variables": variables,
}
samples = []
cursors: set[str] = set()
@@ -181,14 +197,22 @@ class EnlyzeApiGateway:
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 ("time", speed_signal_ref)
+ 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))
@@ -197,7 +221,11 @@ class EnlyzeApiGateway:
timestamp = _parse_timestamp(record[time_index])
except (TypeError, ValueError):
timestamp = None
- samples.append(ShiftSpeedSample(timestamp, record[speed_index]))
+ 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
diff --git a/src/production_analytics/erp/__init__.py b/src/production_analytics/erp/__init__.py
index 3eb9187..e26db00 100644
--- a/src/production_analytics/erp/__init__.py
+++ b/src/production_analytics/erp/__init__.py
@@ -2,6 +2,7 @@
from production_analytics.erp.gateway import (
CurrentWorkplaceStatus,
+ ErpFiberBookingGateway,
ErpProductionConfirmationGateway,
ErpReadError,
ErpSettings,
@@ -11,6 +12,7 @@ from production_analytics.erp.gateway import (
__all__ = [
"CurrentWorkplaceStatus",
+ "ErpFiberBookingGateway",
"ErpProductionConfirmationGateway",
"ErpReadError",
"ErpSettings",
diff --git a/src/production_analytics/erp/gateway.py b/src/production_analytics/erp/gateway.py
index 3cb5c9f..9854279 100644
--- a/src/production_analytics/erp/gateway.py
+++ b/src/production_analytics/erp/gateway.py
@@ -10,6 +10,7 @@ from zoneinfo import ZoneInfo
import pymssql
+from production_analytics.calculations.fiber_allocation import FiberBooking
from production_analytics.enlyze.exploration import ConfigurationError, load_secret_file
@@ -23,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:
@@ -41,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", ""),
@@ -49,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:
@@ -98,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,))
@@ -118,15 +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].replace(tzinfo=_PLANT_TIMEZONE)
- if row[4].utcoffset() is None else row[4]
+ 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]),
+ 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:
@@ -203,8 +216,12 @@ class ErpProductionConfirmationGateway:
self._settings = settings
def get_confirmations(
- self, *, workplace: str, start: datetime, end: datetime
+ 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)):
@@ -212,15 +229,19 @@ class ErpProductionConfirmationGateway:
raise ValueError(f"{name} must be a timezone-aware datetime")
if end.astimezone(UTC) <= start.astimezone(UTC):
raise ValueError("end must follow start")
- local_start = start.astimezone(_PLANT_TIMEZONE).replace(tzinfo=None)
- local_end = end.astimezone(_PLANT_TIMEZONE).replace(tzinfo=None)
+ 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,
+ 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(
@@ -230,18 +251,18 @@ class ErpProductionConfirmationGateway:
except Exception:
raise ErpReadError("ERP production confirmation read failed") from None
try:
- return [_production_confirmation(row) for row in rows]
+ return [_production_confirmation(row, timezone) for row in rows]
except Exception:
raise ErpReadError("ERP production confirmation returned an invalid row") from None
-def _production_confirmation(row: tuple[object, ...]) -> ProductionConfirmation:
+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=_PLANT_TIMEZONE, fold=0),
+ 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),
@@ -253,3 +274,53 @@ def _production_confirmation(row: tuple[object, ...]) -> ProductionConfirmation:
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
diff --git a/src/production_analytics/presentation/__init__.py b/src/production_analytics/presentation/__init__.py
new file mode 100644
index 0000000..e4bf040
--- /dev/null
+++ b/src/production_analytics/presentation/__init__.py
@@ -0,0 +1 @@
+"""Output presenters independent of report composition and source access."""
diff --git a/src/production_analytics/presentation/shift_report.py b/src/production_analytics/presentation/shift_report.py
new file mode 100644
index 0000000..fd6f598
--- /dev/null
+++ b/src/production_analytics/presentation/shift_report.py
@@ -0,0 +1,315 @@
+"""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"),
+ [
+ (
+ 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),
+ )
+ for item in report.production.items
+ ],
+ [36, 30, 62, 30, 20],
+ )
+ 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))
+ )
+ text("Liniengeschwindigkeit", "Heading2")
+ if report.speed is None:
+ text("Für diese Maschine nicht verfügbar.")
+ else:
+ speed = report.speed.average_line_speed_m_min
+ text(
+ "Durchschnittliche Liniengeschwindigkeit im Lauf: "
+ + (f"{_number(speed)} m/min" if speed is not None
+ else "Nicht verfügbar (keine Laufdaten).")
+ )
+
+ 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", " "), 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)
diff --git a/src/production_analytics/presentation/shift_report_html.py b/src/production_analytics/presentation/shift_report_html.py
new file mode 100644
index 0000000..88601a6
--- /dev/null
+++ b/src/production_analytics/presentation/shift_report_html.py
@@ -0,0 +1,130 @@
+"""HTML formatting of the shared report presentation; no data-source access."""
+
+from html import escape
+from math import fsum
+
+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''
+ f"{escape(description)}"
+ )
+ legend.append(
+ f'