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'
  • {escape(description)}
  • ' + ) + offset += percent + return ( + '
    Verbrauchsanteile nach Material
    ' + '' + "Verbrauchsanteile nach Material; Werte in der Legende" + + "".join(slices) + + '
    ' + ) + + +def render_page(*, machines, labels, day, shift, machine, report, generated_at, error, + sites=None): + machine_labels = ((key, getattr(config, "display_name", key)) + for key, config in machines.items()) + def options(values, selected): + return "".join( + f'" + for key, label in values + ) + + body = "" + if error: + body = f'' + if report is not None: + body += ( + f'

    Datenstand: {generated_at:%d.%m.%Y %H:%M:%S %Z} ' + f"({report.timezone.key}). Quellen können nachträglich korrigiert werden.

    " + ) + material_open = False + details_open = False + for block in present_report(report, include_single_material_chart=True): + if isinstance(block, TextBlock): + if material_open and block.style == "Heading2": + body += ("" if details_open else "") + "" + material_open = details_open = False + if block.text == "Materialverbrauch" and block.style == "Heading2": + body += ( + '

    Materialverbrauch

    ' + '
    ' + ) + material_open = details_open = True + continue + tag = {"Title": "h1", "Heading2": "h2", "Heading3": "h3"}.get(block.style, "p") + body += f"<{tag}>{escape(block.text)}" + elif isinstance(block, TableBlock): + body += '
    ' + body += "".join(f'' for cell in block.headers) + body += "" + for row in block.rows: + body += "" + "".join(f"" for cell in row) + "" + body += "
    {escape(cell)}
    {escape(cell)}
    " + elif isinstance(block, MaterialPieBlock): + body += "
    " + _material_chart(block) + details_open = False + if material_open: + body += ("
    " if details_open else "") + "
    " + return f''' + + +Live-Schichtberichte

    Live-Schichtberichte

    +
    + + + + + +
    {body}
    ''' diff --git a/src/production_analytics/service/fiber_allocation.py b/src/production_analytics/service/fiber_allocation.py new file mode 100644 index 0000000..a58f822 --- /dev/null +++ b/src/production_analytics/service/fiber_allocation.py @@ -0,0 +1,35 @@ +"""Explicit K7 order adapter; generic measured material calculation stays ERP-free.""" + +import re +from dataclasses import replace +from typing import Protocol + +from production_analytics.calculations.fiber_allocation import ( + FiberBooking, + allocate_fiber_materials, +) +from production_analytics.calculations.shift_material import ShiftMaterialSummary + + +class FiberBookingReader(Protocol): + def get_fiber_bookings(self, production_order: str) -> list[FiberBooking]: ... + + +class K7FiberAllocationService: + def __init__(self, reader: FiberBookingReader) -> None: + self.reader = reader + + def allocate(self, measured: ShiftMaterialSummary) -> ShiftMaterialSummary: + bookings = {} + items = [] + for item in measured.items: + match = re.fullmatch(r"(?:K 7-)?([0-9]+)", item.production_order.strip()) + if match is None: + items.append(item) + continue + order = match[1] + if order not in bookings: + bookings[order] = self.reader.get_fiber_bookings(order) + items.extend(allocate_fiber_materials(item, bookings[order], erp_order=order)) + # Keep the measured shift total, rather than replacing it with an ERP total. + return replace(measured, items=tuple(items)) diff --git a/src/production_analytics/service/historical_reconcile.py b/src/production_analytics/service/historical_reconcile.py new file mode 100644 index 0000000..1788107 --- /dev/null +++ b/src/production_analytics/service/historical_reconcile.py @@ -0,0 +1,98 @@ +"""Conservative historical attribution decisions and orchestration, without SQL.""" + +from dataclasses import dataclass +from datetime import datetime, time, timedelta +from zoneinfo import ZoneInfo + +from production_analytics.context import build_enlyze_production_order + +BERLIN = ZoneInfo("Europe/Berlin") + + +def reconciliation_window(now: datetime, lookback_days: int = 3): + """Previous N complete Berlin calendar days, as a half-open interval.""" + if now.utcoffset() is None or isinstance(lookback_days, bool) or lookback_days < 1: + raise ValueError("An aware clock and positive lookback-days are required") + end = datetime.combine(now.astimezone(BERLIN).date(), time(), BERLIN) + return end - timedelta(days=lookback_days), end + + +@dataclass(frozen=True) +class HistoricalRecord: + table: str + identity: tuple + machine_id: str + timestamp: datetime + production_order: str + run_id: str + + +@dataclass(frozen=True) +class Decision: + record: HistoricalRecord + order: str | None + reason: str + desired_run_id: str | None = None + + +def decide(record, runs, confirmations, workplace, format_template): + """Keep physical counter/run identities; never infer boundaries from ERP points.""" + candidates = [r for r in runs if r.machine_id == record.machine_id + and r.start.timestamp() <= record.timestamp.timestamp() + and (r.end is None or record.timestamp.timestamp() < r.end.timestamp())] + if len(candidates) != 1 or candidates[0].end is None: + return Decision(record, None, "unresolved: missing or overlapping closed ENLYZE runs") + run = candidates[0] + orders = {build_enlyze_production_order(c.production_order, format_template) + for c in confirmations if c.workplace == workplace and c.is_finished_goods + and run.start.timestamp() < c.timestamp.timestamp() < run.end.timestamp()} + if orders != {run.production_order}: + return Decision(record, None, "unresolved: ERP evidence missing or conflicts with ENLYZE") + return Decision(record, run.production_order, + f"closed ENLYZE run {run.uuid} [{run.start.isoformat()}, " + f"{run.end.isoformat()}) corroborated by ERP order {run.production_order}", + run.uuid) + + +def reconcile_machine(repository, source, erp, config, template, start, end, dry_run=False): + records = repository.read(config.machine_id, start, end) + runs = source.get_production_runs(config.machine_id) + # Query complete overlapping runs so partial-window evidence cannot conceal conflicts. + relevant = [r for r in runs if r.end is not None + and r.start.timestamp() < end.timestamp() and r.end.timestamp() > start.timestamp()] + evidence_start = min([start, *(r.start for r in relevant)], key=datetime.timestamp) + evidence_end = max([end, *(r.end for r in relevant)], key=datetime.timestamp) + confirmations = erp.get_confirmations( + workplace=config.erp_workplace, start=evidence_start, end=evidence_end, + ) + decisions = [decide(r, runs, confirmations, config.erp_workplace, template) for r in records] + # Require complete, unambiguous evidence, allowing orders within a physical run. + decisions = repository.guard_runs(decisions) + applied = repository.apply(decisions) if not dry_run else 0 + return decisions, applied + + +def grouped_counts(decisions): + """Count physical identities and contiguous attribution segments, not snapshot rows.""" + groups = {} + for d in decisions: + r = d.record + key = (r.table, r.machine_id, r.identity[0], r.run_id) + groups.setdefault(key, []).append(d) + proposed_runs = unresolved_runs = corrected_segments = unresolved_segments = 0 + for peers in groups.values(): + proposed_runs += any(d.order is not None and d.order != d.record.production_order + for d in peers) + unresolved_runs += any(d.order is None for d in peers) + streams = {} + for d in peers: + streams.setdefault(d.record.identity[3:], []).append(d) + for stream in streams.values(): + previous = object() + for d in sorted(stream, key=lambda d: d.record.timestamp.timestamp()): + state = (d.order, d.order is not None and d.order != d.record.production_order) + if state != previous: + unresolved_segments += d.order is None + corrected_segments += state[1] + previous = state + return (len(groups), proposed_runs, corrected_segments, unresolved_runs, unresolved_segments) diff --git a/src/production_analytics/service/historical_runtime.py b/src/production_analytics/service/historical_runtime.py new file mode 100644 index 0000000..c91c75e --- /dev/null +++ b/src/production_analytics/service/historical_runtime.py @@ -0,0 +1,116 @@ +"""Nightly reconciliation composition and operator output.""" + +from datetime import datetime + +import yaml + +from production_analytics.context import build_enlyze_production_order +from production_analytics.enlyze.exploration import ExplorationClient, ExplorationSettings +from production_analytics.enlyze.gateway import EnlyzeApiGateway +from production_analytics.erp import ErpProductionConfirmationGateway, ErpSettings +from production_analytics.service.historical_reconcile import ( + BERLIN, + grouped_counts, + reconcile_machine, + reconciliation_window, +) +from production_analytics.service.postgres_historical_reconcile import PostgresHistoricalRepository +from production_analytics.service.postgres_material import PostgresSettings +from production_analytics.service.shift_report_config import ( + _StrictLoader, + load_shift_report_machines, +) + + +def _summarize_decisions(name, decisions, dry_run, verbose): + """Print run and source stream summaries from existing decisions.""" + corrections = {} + unresolved = {} + for decision in decisions: + record = decision.record + if decision.order is None: + if verbose: + print(f"Unresolved {name} {record.identity}: {decision.reason}") + # Keep distinct physical runs and source streams separate, even when + # they share the same unresolved reason. + key = (decision.reason, record.table, record.identity[0], record.run_id, + record.identity[3:]) + groups = unresolved + elif decision.order != record.production_order: + if verbose: + print(f"{'Proposed' if dry_run else 'Corrected'} {name} " + f"{record.table} {record.identity}: " + f"{record.production_order} -> {decision.order}; {decision.reason}") + prefix = "closed ENLYZE run " + run_uuid = (decision.reason[len(prefix):].split(" [", 1)[0] + if decision.reason.startswith(prefix) else "unknown") + key = (record.production_order, decision.order, run_uuid) + groups = corrections + else: + continue + if key not in groups: + groups[key] = [0, record.timestamp, record.timestamp] + group = groups[key] + group[0] += 1 + group[1] = min(group[1], record.timestamp) + group[2] = max(group[2], record.timestamp) + + action = "proposed" if dry_run else "corrected" + for (old, new, run_uuid), (count, _first, _last) in corrections.items(): + print(f"{name} | {action}: {old} -> {new} | ENLYZE run {run_uuid} | " + f"{count} records") + for (reason, table, calculation, run_id, stream), (count, first, last) in unresolved.items(): + source = f"{table}/{calculation}" + if stream: + source += "/" + "/".join(map(str, stream)) + print(f"{name} | {reason} | physical run {run_id} | source {source} | " + f"{count} records | {first.isoformat()} -> {last.isoformat()}") + + +def run(args, environment): + start, end = reconciliation_window(datetime.now(BERLIN), args.lookback_days) + machines = {name: config for name, config in load_shift_report_machines(args.config).items() + if config.capabilities.material} + with args.order_formats.open(encoding="utf-8") as stream: + formats = yaml.load(stream, Loader=_StrictLoader) + if not isinstance(formats, dict) or set(formats) != set(machines): + raise ValueError("Order formats must map every material machine name exactly once") + for template in formats.values(): + if not isinstance(template, str): + raise ValueError("Order formats must be strings") + build_enlyze_production_order("1", template) + repository = PostgresHistoricalRepository(PostgresSettings.from_environment(environment)) + source = EnlyzeApiGateway(ExplorationClient(ExplorationSettings.from_environment(environment))) + erp = ErpProductionConfirmationGateway(ErpSettings.from_environment(environment)) + print("Historical reconciliation" + (" (DRY RUN)" if args.dry_run else "")) + print(f"Window: {start.isoformat()} to {end.isoformat()} (exclusive)") + grouped = [0] * 5 + inspected = corrections = unresolved = unchanged = failures = 0 + for name, config in machines.items(): + try: + decisions, applied = reconcile_machine( + repository, source, erp, config, formats[name], start, end, args.dry_run, + ) + grouped = [a + b for a, b in zip(grouped, grouped_counts(decisions))] + inspected += len(decisions) + proposed = 0 + for d in decisions: + if d.order is None: + unresolved += 1 + elif d.order == d.record.production_order: + unchanged += 1 + else: + proposed += 1 + _summarize_decisions(name, decisions, args.dry_run, getattr(args, "verbose", False)) + corrections += proposed if args.dry_run else applied + except Exception as exc: + failures += 1 + print(f"FAILED {name}: {type(exc).__name__}: {exc}; machine transaction rolled back") + print(f"Machines checked: {len(machines)}\nRecords inspected: {inspected}") + print(f"Corrections {'proposed' if args.dry_run else 'applied'}: {corrections}") + print(f"Ambiguous/unresolved: {unresolved}\nUnchanged: {unchanged}\nFailures: {failures}") + print(f"Physical runs inspected: {grouped[0]}\nRuns with proposed corrections: {grouped[1]}") + label = "proposed" if args.dry_run else "corrected" + print(f"Order segments {label}: {grouped[2]}") + print(f"Unresolved runs: {grouped[3]}\nUnresolved segments: {grouped[4]}") + return 1 if failures else 0 diff --git a/src/production_analytics/service/material_context.py b/src/production_analytics/service/material_context.py index 6cc26aa..9a4dce7 100644 --- a/src/production_analytics/service/material_context.py +++ b/src/production_analytics/service/material_context.py @@ -1,18 +1,45 @@ """ERP nominal-width resolution for an explicitly matched production order.""" +import logging + +from production_analytics.calculations.config import finite_number from production_analytics.context import build_enlyze_production_order, extract_nominal_width_m -from production_analytics.erp import ErpWorkplaceStatusGateway +from production_analytics.erp import ErpReadError, ErpWorkplaceStatusGateway + +logger = logging.getLogger(__name__) class ErpNominalWidthProvider: def __init__( self, gateway: ErpWorkplaceStatusGateway, *, workplace: str, format_template: str, + fallback_nominal_width_m: float | None = None, ) -> None: self.gateway = gateway self.workplace = workplace self.format_template = format_template + self.fallback_nominal_width_m = ( + None if fallback_nominal_width_m is None else finite_number( + fallback_nominal_width_m, "fallback_nominal_width_m", positive=True, + ) + ) + self._warned_fallback_orders: set[str] = set() def __call__(self, production_order: str) -> float: + try: + return self._resolve_erp_width(production_order) + except (ValueError, ErpReadError) as exc: + if self.fallback_nominal_width_m is None: + raise + if production_order not in self._warned_fallback_orders: + logger.warning( + "ERP nominal-width resolution failed for ENLYZE production order %r: %s; " + "using fallback nominal width %s m", + production_order, exc, self.fallback_nominal_width_m, + ) + self._warned_fallback_orders.add(production_order) + return self.fallback_nominal_width_m + + def _resolve_erp_width(self, production_order: str) -> float: status = self.gateway.get_current_workplace_status(self.workplace) if (status is None or status.workplace.strip().casefold() != self.workplace.strip().casefold() diff --git a/src/production_analytics/service/material_runtime.py b/src/production_analytics/service/material_runtime.py index c5a86ed..5173724 100644 --- a/src/production_analytics/service/material_runtime.py +++ b/src/production_analytics/service/material_runtime.py @@ -86,6 +86,7 @@ def build_material_runner( ErpWorkplaceStatusGateway(ErpSettings.from_secret_file(erp_secrets_file)), workplace=calculation.erp_workplace, format_template=calculation.production_order_format, + fallback_nominal_width_m=calculation.fallback_nominal_width_m, ), ) if calculation.source_mode == "linear_signal_discharge": diff --git a/src/production_analytics/service/postgres_downtime.py b/src/production_analytics/service/postgres_downtime.py index b9117fd..ee431bc 100644 --- a/src/production_analytics/service/postgres_downtime.py +++ b/src/production_analytics/service/postgres_downtime.py @@ -34,18 +34,19 @@ class PostgresDowntimeRepository: def get_events( self, *, machine_id: str, start: datetime, end: datetime ) -> list[ShiftDowntimeEvent]: - """Read raw machine intervals intersecting [start, end), independent of orders.""" + """Read effective machine intervals intersecting [start, end).""" validate_downtime_window(machine_id=machine_id, start=start, end=end) try: with self._connect() as connection: rows = connection.execute( """SELECT external_id, machine_id, source_start, source_end, reason_id, reason_name, reason_description, reason_group, - category, comment + category, comment, attributed_start, attributed_end FROM production_downtime_events - WHERE machine_id = %s AND source_start < %s - AND (source_end IS NULL OR source_end > %s) - ORDER BY source_start, external_id""", + WHERE machine_id = %s AND COALESCE(attributed_start, source_start) < %s + AND (COALESCE(attributed_end, source_end) IS NULL + OR COALESCE(attributed_end, source_end) > %s) + ORDER BY COALESCE(attributed_start, source_start), external_id""", (machine_id, end, start), ).fetchall() except Exception: diff --git a/src/production_analytics/service/postgres_historical_reconcile.py b/src/production_analytics/service/postgres_historical_reconcile.py new file mode 100644 index 0000000..e798470 --- /dev/null +++ b/src/production_analytics/service/postgres_historical_reconcile.py @@ -0,0 +1,139 @@ +"""Transactional attribution-only updates with an atomic audit trail.""" + +from contextlib import nullcontext +from dataclasses import replace + +import psycopg +from psycopg import sql +from psycopg.types.json import Jsonb + +from production_analytics.service.historical_reconcile import HistoricalRecord + +TABLES = { + "material_consumption_snapshots": ("calculation_id", "machine_id", "timestamp"), + "material_application_snapshots": ("calculation_id", "machine_id", "timestamp"), + "channel_material_consumption_snapshots": ( + "calculation_id", "machine_id", "timestamp", "extruder", "doser_channel", + ), +} + + +class PostgresHistoricalRepository: + def __init__(self, settings): + self.settings = settings + + def connect(self): + s = self.settings + return psycopg.connect(host=s.host, port=s.port, dbname=s.dbname, user=s.user, + password=s.password, connect_timeout=10, + options="-c statement_timeout=30000") + + def read(self, machine_id, start, end): + result = [] + with self.connect() as connection: + for table, keys in TABLES.items(): + rows = connection.execute(sql.SQL( + "SELECT {}, production_order, run_id FROM {} " + "WHERE machine_id = %s AND timestamp >= %s AND timestamp < %s" + ).format(sql.SQL(', ').join(map(sql.Identifier, keys)), sql.Identifier(table)), + (machine_id, start, end)).fetchall() + result.extend(HistoricalRecord(table, tuple(row[:-2]), machine_id, row[2], + row[-2], row[-1]) for row in rows) + return result + + def guard_runs(self, decisions, connection=None): + """Reject partial run repairs, including historical rows outside the window.""" + groups = {} + for d in decisions: + r = d.record + groups.setdefault((r.table, r.machine_id, r.identity[0], r.run_id), []).append(d) + blocked = set() + context = self.connect() if connection is None else nullcontext(connection) + with context as connection: + for key, peers in groups.items(): + corrections = [d for d in peers if d.order is not None + and d.order != d.record.production_order] + if not corrections: + continue + table, machine, calculation, run = key + count = connection.execute(sql.SQL( + "SELECT count(*) FROM {} WHERE machine_id = %s " + "AND calculation_id = %s AND run_id = %s" + ).format(sql.Identifier(table)), (machine, calculation, run)).fetchone()[0] + if count != len(peers) or any(d.order is None for d in peers): + blocked.add(key) + return [replace(d, order=None, + reason="unresolved: partial or unresolved cumulative run") + if (d.record.table, d.record.machine_id, d.record.identity[0], + d.record.run_id) in blocked else d for d in decisions] + + def apply(self, decisions): + count = 0 + with self.connect() as connection: + # Serialize this job; concurrent changes fail rather than silently overwrite. + connection.execute("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE") + connection.execute("SELECT pg_advisory_xact_lock(704301)") + if self.guard_runs(decisions, connection) != decisions: + raise RuntimeError("Historical run changed concurrently; retry reconciliation") + for d in decisions: + r = d.record + if d.order is None or d.order == r.production_order: + continue + keys = TABLES[r.table] + predicate = sql.SQL(' AND ').join( + sql.SQL('{} = %s').format(sql.Identifier(k)) for k in keys) + action = "updated" + retained_run_id = None + if r.table == "material_application_snapshots": + source = connection.execute(sql.SQL( + "SELECT application_g_m2 FROM {} WHERE {} " + "AND production_order = %s AND run_id = %s FOR UPDATE" + ).format(sql.Identifier(r.table), predicate), + (*r.identity, r.production_order, r.run_id)).fetchone() + if source is None: + raise RuntimeError( + "Historical record changed concurrently; retry reconciliation" + ) + target = connection.execute( + """SELECT run_id, application_g_m2 IS NOT DISTINCT FROM %s + FROM material_application_snapshots + WHERE calculation_id = %s AND machine_id = %s + AND timestamp = %s AND production_order = %s FOR UPDATE""", + (source[0], *r.identity, d.order)).fetchone() + if target is not None: + if (not target[1] or d.desired_run_id is None + or target[0] != d.desired_run_id): + raise RuntimeError( + "Historical application collision has conflicting measurement " + "or unexpected target run; machine transaction rolled back" + ) + deleted = connection.execute(sql.SQL( + "DELETE FROM {} WHERE {} AND production_order = %s " + "AND run_id = %s RETURNING timestamp" + ).format(sql.Identifier(r.table), predicate), + (*r.identity, r.production_order, r.run_id)).fetchone() + if deleted is None: + raise RuntimeError( + "Historical record changed concurrently; retry reconciliation" + ) + action = "deduplicated" + retained_run_id = target[0] + if action == "updated": + changed = connection.execute(sql.SQL( + "UPDATE {} SET production_order = %s WHERE {} " + "AND production_order = %s AND run_id = %s RETURNING timestamp" + ).format(sql.Identifier(r.table), predicate), + (d.order, *r.identity, r.production_order, r.run_id)).fetchone() + if changed is None: + raise RuntimeError( + "Historical record changed concurrently; retry reconciliation" + ) + connection.execute( + """INSERT INTO historical_assignment_audit + (machine_id, source_table, record_identity, previous_order, new_order, + run_id, reason, action, retained_run_id) + VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)""", + (r.machine_id, r.table, Jsonb(dict(zip(keys, map(str, r.identity)))), + r.production_order, d.order, r.run_id, d.reason, action, retained_run_id)) + count += 1 + return count diff --git a/src/production_analytics/service/shift_production.py b/src/production_analytics/service/shift_production.py index 87f151d..c447869 100644 --- a/src/production_analytics/service/shift_production.py +++ b/src/production_analytics/service/shift_production.py @@ -2,6 +2,7 @@ from datetime import datetime from typing import Protocol +from zoneinfo import ZoneInfo from production_analytics.calculations.shift_production import ( ShiftProductionSummary, @@ -13,7 +14,8 @@ from production_analytics.erp import ProductionConfirmation class ProductionConfirmationReader(Protocol): def get_confirmations( - self, *, workplace: str, start: datetime, end: datetime + self, *, workplace: str, start: datetime, end: datetime, + timezone: ZoneInfo | None = None, ) -> list[ProductionConfirmation]: ... @@ -22,8 +24,12 @@ class ShiftProductionService: self.gateway = gateway def summarize( - self, *, workplace: str, start: datetime, end: datetime + self, *, workplace: str, start: datetime, end: datetime, + timezone: ZoneInfo | None = None, ) -> ShiftProductionSummary: workplace = validate_shift_window(workplace=workplace, start=start, end=end) - confirmations = self.gateway.get_confirmations(workplace=workplace, start=start, end=end) + kwargs = {"workplace": workplace, "start": start, "end": end} + if timezone is not None: + kwargs["timezone"] = timezone + confirmations = self.gateway.get_confirmations(**kwargs) return aggregate_shift_production(confirmations, workplace=workplace, start=start, end=end) diff --git a/src/production_analytics/service/shift_report.py b/src/production_analytics/service/shift_report.py index 9f6026d..ab016b5 100644 --- a/src/production_analytics/service/shift_report.py +++ b/src/production_analytics/service/shift_report.py @@ -3,8 +3,10 @@ from collections.abc import Mapping from datetime import datetime from types import MappingProxyType +from typing import Protocol -from production_analytics.calculations.shift_report import SHIFT_TIMEZONE, ShiftReport +from production_analytics.calculations.shift_material import ShiftMaterialSummary +from production_analytics.calculations.shift_report import ShiftReport from production_analytics.calculations.shift_speed import validate_speed_window from production_analytics.service.shift_downtime import ShiftDowntimeService from production_analytics.service.shift_material import ( @@ -16,12 +18,21 @@ from production_analytics.service.shift_report_config import ShiftReportMachineC from production_analytics.service.shift_speed import ShiftSpeedService +class ShiftMaterialAllocator(Protocol): + def allocate(self, measured: ShiftMaterialSummary) -> ShiftMaterialSummary: ... + + class ShiftReportService: def __init__( - self, *, machines: Mapping[str, ShiftReportMachineConfig], - production: ShiftProductionService, downtime: ShiftDowntimeService, - materials: ShiftMaterialService, channel_materials: ShiftChannelMaterialService, + self, + *, + machines: Mapping[str, ShiftReportMachineConfig], + production: ShiftProductionService, + downtime: ShiftDowntimeService, + materials: ShiftMaterialService, + channel_materials: ShiftChannelMaterialService, speed: ShiftSpeedService, + material_allocators: Mapping[str, ShiftMaterialAllocator] | None = None, ) -> None: self.machines = MappingProxyType(dict(machines)) self.production = production @@ -29,26 +40,47 @@ class ShiftReportService: self.materials = materials self.channel_materials = channel_materials self.speed = speed + self.material_allocators = MappingProxyType(dict(material_allocators or {})) def build(self, *, machine_name: str, start: datetime, end: datetime) -> ShiftReport: validate_speed_window(start, end) if not isinstance(machine_name, str) or machine_name not in self.machines: raise ValueError("Unknown shift-report machine") config = self.machines[machine_name] - start, end = start.astimezone(SHIFT_TIMEZONE), end.astimezone(SHIFT_TIMEZONE) + start, end = start.astimezone(config.timezone), end.astimezone(config.timezone) production = self.production.summarize( - workplace=config.erp_workplace, start=start, end=end, - ) - downtime = self.downtime.summarize(machine_id=config.machine_id, start=start, end=end) - material_service = ( - self.channel_materials if config.material.mode == "channel" else self.materials - ) - materials = material_service.summarize( - machine_id=config.machine_id, calculation_ids=config.material.calculation_ids, - start=start, end=end, - ) - speed = self.speed.summarize(config=config.speed, start=start, end=end) + workplace=config.erp_workplace, + start=start, + end=end, + timezone=config.timezone, + ) if config.capabilities.production else None + downtime = (self.downtime.summarize(machine_id=config.machine_id, start=start, end=end) + if config.capabilities.downtime else None) + materials = None + if config.material is not None: + material_service = ( + self.channel_materials if config.material.mode == "channel" else self.materials + ) + materials = material_service.summarize( + machine_id=config.machine_id, + calculation_ids=config.material.calculation_ids, + start=start, + end=end, + ) + if machine_name in self.material_allocators: + materials = self.material_allocators[machine_name].allocate(materials) + speed = (self.speed.summarize(config=config.speed, start=start, end=end) + if config.speed is not None else None) return ShiftReport( - machine_name=machine_name, machine_id=config.machine_id, start=start, end=end, - production=production, downtime=downtime, materials=materials, speed=speed, + machine_name=machine_name, + machine_id=config.machine_id, + display_name=config.display_name, + site=config.site, + timezone=config.timezone, + start=start, + end=end, + production=production, + downtime=downtime, + materials=materials, + speed=speed, ) diff --git a/src/production_analytics/service/shift_report_config.py b/src/production_analytics/service/shift_report_config.py index ba46b28..990e5db 100644 --- a/src/production_analytics/service/shift_report_config.py +++ b/src/production_analytics/service/shift_report_config.py @@ -1,22 +1,55 @@ """Strict, self-contained configuration for shift-report composition.""" +from collections.abc import Mapping from dataclasses import dataclass from pathlib import Path +from types import MappingProxyType from typing import Literal +from zoneinfo import ZoneInfo, ZoneInfoNotFoundError import yaml -from production_analytics.calculations.shift_speed import ShiftSpeedConfig +from production_analytics.calculations.shift_speed import NumericDwellGate, ShiftSpeedConfig + + +@dataclass(frozen=True, slots=True) +class ShiftReportSiteConfig: + display_name: str + timezone: ZoneInfo + + def __post_init__(self) -> None: + _text(self.display_name, "site.display_name") + if not isinstance(self.timezone, ZoneInfo): + raise ValueError("site.timezone must be a valid IANA timezone") + + +@dataclass(frozen=True, slots=True) +class ShiftReportCapabilities: + production: bool + downtime: bool + material: bool + speed: bool + + def __post_init__(self) -> None: + if any(type(value) is not bool for value in ( + self.production, self.downtime, self.material, self.speed, + )): + raise ValueError("capabilities must contain booleans") + if not any((self.production, self.downtime, self.material, self.speed)): + raise ValueError("at least one capability must be enabled") @dataclass(frozen=True, slots=True) class ShiftReportMaterialConfig: mode: Literal["cumulative", "channel"] calculation_ids: tuple[str, ...] + allocation: Literal["none", "erp_fiber_share"] = "none" def __post_init__(self) -> None: if self.mode not in ("cumulative", "channel"): raise ValueError("material.mode must be cumulative or channel") + if self.allocation not in ("none", "erp_fiber_share"): + raise ValueError("material.allocation must be none or erp_fiber_share") if not isinstance(self.calculation_ids, tuple) or not self.calculation_ids: raise ValueError("material.calculation_ids must be a non-empty tuple") for calculation_id in self.calculation_ids: @@ -27,19 +60,48 @@ class ShiftReportMaterialConfig: @dataclass(frozen=True, slots=True) class ShiftReportMachineConfig: - machine_id: str + display_name: str + site: str + machine_id: str | None erp_workplace: str - material: ShiftReportMaterialConfig - speed: ShiftSpeedConfig + capabilities: ShiftReportCapabilities + timezone: ZoneInfo + material: ShiftReportMaterialConfig | None = None + speed: ShiftSpeedConfig | None = None def __post_init__(self) -> None: - _text(self.machine_id, "machine_id") - _text(self.erp_workplace, "erp_workplace") - if not isinstance(self.material, ShiftReportMaterialConfig): + for name in ("display_name", "site", "erp_workplace"): + _text(getattr(self, name), name) + if not isinstance(self.timezone, ZoneInfo): + raise ValueError("machine timezone must be a valid IANA timezone") + if not isinstance(self.capabilities, ShiftReportCapabilities): + raise ValueError("capabilities must be a ShiftReportCapabilities") + if self.machine_id is not None: + _text(self.machine_id, "machine_id") + elif any((self.capabilities.downtime, self.capabilities.material, + self.capabilities.speed)): + raise ValueError("machine_id is required for downtime, material, or speed") + if self.capabilities.material != (self.material is not None): + raise ValueError("material configuration must match material capability") + if self.capabilities.speed != (self.speed is not None): + raise ValueError("speed configuration must match speed capability") + if self.material is not None and not isinstance(self.material, ShiftReportMaterialConfig): raise ValueError("material must be a ShiftReportMaterialConfig") - if not isinstance(self.speed, ShiftSpeedConfig) or self.speed.machine_id != self.machine_id: - raise ValueError("speed configuration must refer to the report machine") - _text(self.speed.signal, "speed.signal") + if self.speed is not None: + if (not isinstance(self.speed, ShiftSpeedConfig) + or self.speed.machine_id != self.machine_id): + raise ValueError("speed configuration must refer to the report machine") + _text(self.speed.signal, "speed.signal") + + +@dataclass(frozen=True, slots=True) +class ShiftReportConfig: + sites: Mapping[str, ShiftReportSiteConfig] + machines: Mapping[str, ShiftReportMachineConfig] + + def __post_init__(self) -> None: + object.__setattr__(self, "sites", MappingProxyType(dict(self.sites))) + object.__setattr__(self, "machines", MappingProxyType(dict(self.machines))) class _StrictLoader(yaml.SafeLoader): @@ -70,36 +132,100 @@ def _fields(value: object, expected: set[str], name: str) -> dict: return value -def load_shift_report_machines(path: str | Path) -> dict[str, ShiftReportMachineConfig]: +def load_shift_report_config(path: str | Path) -> ShiftReportConfig: try: with Path(path).open(encoding="utf-8") as stream: document = yaml.load(stream, Loader=_StrictLoader) except (OSError, UnicodeError, yaml.YAMLError) as exc: raise ValueError("Cannot read shift-report machine configuration") from exc - document = _fields(document, {"machines"}, "Shift-report configuration") + document = _fields(document, {"sites", "machines"}, "Shift-report configuration") + raw_sites = document["sites"] + if not isinstance(raw_sites, dict) or not raw_sites: + raise ValueError("sites must be a non-empty mapping") + sites = {} + for key, entry in raw_sites.items(): + _text(key, "site key") + entry = _fields(entry, {"display_name", "timezone"}, f"site {key}") + _text(entry["timezone"], "site.timezone") + try: + timezone = ZoneInfo(entry["timezone"]) + except (ZoneInfoNotFoundError, ValueError, TypeError) as exc: + raise ValueError("site.timezone must be a valid IANA timezone") from exc + sites[key] = ShiftReportSiteConfig(entry["display_name"], timezone) machines = document["machines"] if not isinstance(machines, dict) or not machines: raise ValueError("machines must be a non-empty mapping") result = {} for name, entry in machines.items(): _text(name, "machine name") - entry = _fields(entry, {"machine_id", "erp_workplace", "material", "speed"}, name) - material = _fields(entry["material"], {"mode", "calculation_ids"}, "material") - ids = material["calculation_ids"] - if not isinstance(ids, list): - raise ValueError("material.calculation_ids must be a list") - speed = _fields( - entry["speed"], {"signal_ref", "signal", "unit", "production_gate_m_min"}, "speed", - ) + required = {"display_name", "site", "erp_workplace", "capabilities"} + if not isinstance(entry, dict) or not required <= set(entry) or set(entry) - ( + required | {"machine_id", "material", "speed"} + ): + raise ValueError(f"{name} has missing or unknown fields") + capabilities = _fields(entry["capabilities"], + {"production", "downtime", "material", "speed"}, + "capabilities") + capabilities = ShiftReportCapabilities(**capabilities) + _text(entry["site"], "site") + if entry["site"] not in sites: + raise ValueError(f"{name} references an unknown site") + if capabilities.material != ("material" in entry): + raise ValueError("material configuration must match material capability") + if capabilities.speed != ("speed" in entry): + raise ValueError("speed configuration must match speed capability") + material = None + if capabilities.material: + material_entry = entry["material"] + if not isinstance(material_entry, dict) or not {"mode", "calculation_ids"} <= set( + material_entry + ) or set(material_entry) - {"mode", "calculation_ids", "allocation"}: + raise ValueError("material has missing or unknown fields") + ids = material_entry["calculation_ids"] + if not isinstance(ids, list): + raise ValueError("material.calculation_ids must be a list") + material = ShiftReportMaterialConfig( + material_entry["mode"], tuple(ids), material_entry.get("allocation", "none") + ) + speed = None + if capabilities.speed: + speed_entry = entry["speed"] + required_speed = {"signal_ref", "signal", "unit"} + optional_speed = {"production_gate_m_min", "running_signal_ref", "running_when", + "numeric_dwell_gate"} + if (not isinstance(speed_entry, dict) or not required_speed <= set(speed_entry) + or set(speed_entry) - (required_speed | optional_speed)): + raise ValueError("speed has missing or unknown fields") + if "running_when" in speed_entry and not speed_entry.get("running_signal_ref"): + raise ValueError("speed.running_when requires running_signal_ref") + dwell = None + if "numeric_dwell_gate" in speed_entry: + dwell_entry = _fields( + speed_entry["numeric_dwell_gate"], + {"signal_ref", "threshold", "comparison", "minimum_duration_seconds"}, + "numeric_dwell_gate", + ) + dwell = NumericDwellGate(**dwell_entry) + speed = ShiftSpeedConfig( + machine_id=entry.get("machine_id"), speed_signal_ref=speed_entry["signal_ref"], + signal=speed_entry["signal"], unit=speed_entry["unit"], + production_gate_m_min=speed_entry.get("production_gate_m_min"), + running_signal_ref=speed_entry.get("running_signal_ref"), + running_when=speed_entry.get("running_when", True), + numeric_dwell_gate=dwell, + ) result[name] = ShiftReportMachineConfig( - machine_id=entry["machine_id"], erp_workplace=entry["erp_workplace"], - material=ShiftReportMaterialConfig(material["mode"], tuple(ids)), - speed=ShiftSpeedConfig( - machine_id=entry["machine_id"], speed_signal_ref=speed["signal_ref"], - signal=speed["signal"], unit=speed["unit"], - production_gate_m_min=speed["production_gate_m_min"], - ), + display_name=entry["display_name"], site=entry["site"], + machine_id=entry.get("machine_id"), erp_workplace=entry["erp_workplace"], + capabilities=capabilities, timezone=sites[entry["site"]].timezone, + material=material, speed=speed, ) - if len({config.machine_id for config in result.values()}) != len(result): + ids = [config.machine_id for config in result.values() if config.machine_id is not None] + if len(set(ids)) != len(ids): raise ValueError("Shift-report machine IDs must be unique") - return result + return ShiftReportConfig(sites, result) + + +def load_shift_report_machines(path: str | Path) -> dict[str, ShiftReportMachineConfig]: + """Compatibility view used by report entry points and historical reconciliation.""" + return dict(load_shift_report_config(path).machines) diff --git a/src/production_analytics/service/shift_report_runtime.py b/src/production_analytics/service/shift_report_runtime.py new file mode 100644 index 0000000..dbeb945 --- /dev/null +++ b/src/production_analytics/service/shift_report_runtime.py @@ -0,0 +1,52 @@ +"""Construct read-only sources for one explicit shift report.""" + +from collections.abc import Mapping + +from production_analytics.enlyze.exploration import ExplorationClient, ExplorationSettings +from production_analytics.enlyze.gateway import EnlyzeApiGateway +from production_analytics.erp import ( + ErpFiberBookingGateway, + ErpProductionConfirmationGateway, + ErpSettings, +) +from production_analytics.service.fiber_allocation import K7FiberAllocationService +from production_analytics.service.postgres_downtime import PostgresDowntimeRepository +from production_analytics.service.postgres_material import PostgresSettings +from production_analytics.service.postgres_shift_material import ( + PostgresShiftChannelMaterialRepository, + PostgresShiftMaterialRepository, +) +from production_analytics.service.shift_downtime import ShiftDowntimeService +from production_analytics.service.shift_material import ( + ShiftChannelMaterialService, + ShiftMaterialService, +) +from production_analytics.service.shift_production import ShiftProductionService +from production_analytics.service.shift_report import ShiftReportService +from production_analytics.service.shift_report_config import ShiftReportMachineConfig +from production_analytics.service.shift_speed import ShiftSpeedService + + +def build_shift_report_service( + machines: Mapping[str, ShiftReportMachineConfig], + environment: Mapping[str, str], +) -> ShiftReportService: + postgres = PostgresSettings.from_environment(environment) + erp = ErpSettings.from_environment(environment) + enlyze = ExplorationSettings.from_environment(environment) + allocators = { + name: K7FiberAllocationService(ErpFiberBookingGateway(erp)) + for name, config in machines.items() + if config.material is not None and config.material.allocation == "erp_fiber_share" + } + return ShiftReportService( + machines=machines, + material_allocators=allocators, + production=ShiftProductionService(ErpProductionConfirmationGateway(erp)), + downtime=ShiftDowntimeService(PostgresDowntimeRepository(postgres)), + materials=ShiftMaterialService(PostgresShiftMaterialRepository(postgres)), + channel_materials=ShiftChannelMaterialService( + PostgresShiftChannelMaterialRepository(postgres) + ), + speed=ShiftSpeedService(EnlyzeApiGateway(ExplorationClient(enlyze))), + ) diff --git a/src/production_analytics/service/shift_speed.py b/src/production_analytics/service/shift_speed.py index 73d3481..26534af 100644 --- a/src/production_analytics/service/shift_speed.py +++ b/src/production_analytics/service/shift_speed.py @@ -1,6 +1,6 @@ """Compose bounded ENLYZE speed reads with the pure running-speed KPI.""" -from datetime import datetime +from datetime import UTC, datetime, timedelta from typing import Protocol from production_analytics.calculations.shift_speed import ( @@ -15,6 +15,8 @@ from production_analytics.calculations.shift_speed import ( class ShiftSpeedReader(Protocol): def get_speed_samples( self, *, machine_id: str, speed_signal_ref: str, start: datetime, end: datetime, + running_signal_ref: str | None = None, + numeric_gate_signal_ref: str | None = None, ) -> list[ShiftSpeedSample]: ... @@ -26,8 +28,14 @@ class ShiftSpeedService: self, *, config: ShiftSpeedConfig, start: datetime, end: datetime, ) -> ShiftSpeedSummary: validate_speed_window(start, end) - samples = self.gateway.get_speed_samples( - machine_id=config.machine_id, speed_signal_ref=config.speed_signal_ref, - start=start, end=end, - ) + kwargs = {"machine_id": config.machine_id, "speed_signal_ref": config.speed_signal_ref, + "start": start, "end": end} + if config.running_signal_ref is not None: + kwargs["running_signal_ref"] = config.running_signal_ref + if config.numeric_dwell_gate is not None: + kwargs["numeric_gate_signal_ref"] = config.numeric_dwell_gate.signal_ref + dwell = timedelta(seconds=config.numeric_dwell_gate.minimum_duration_seconds) + kwargs["start"] = start.astimezone(UTC) - dwell + kwargs["end"] = end.astimezone(UTC) + dwell + samples = self.gateway.get_speed_samples(**kwargs) return aggregate_shift_speed(samples, config=config, start=start, end=end) diff --git a/src/production_analytics/web.py b/src/production_analytics/web.py new file mode 100644 index 0000000..6604d19 --- /dev/null +++ b/src/production_analytics/web.py @@ -0,0 +1,140 @@ +"""Read-only live shift-report WSGI interface; no report cache or persistence.""" + +import argparse +import os +from collections.abc import Callable, Mapping +from datetime import UTC, datetime +from pathlib import Path +from urllib.parse import parse_qs +from wsgiref.simple_server import make_server + +from production_analytics.calculations.shift_report import ( + most_recent_completed_shift, + shift_report_window, +) +from production_analytics.presentation.shift_report import render_pdf +from production_analytics.presentation.shift_report_html import render_page +from production_analytics.service.shift_report_config import load_shift_report_config +from production_analytics.service.shift_report_runtime import build_shift_report_service + +SHIFT_LABELS = {"early": "Frühschicht", "late": "Spätschicht", "night": "Nachtschicht"} + + +def create_app(machines: Mapping, service_factory: Callable, *, sites: Mapping | None = None, + clock=None): + """Inject the configured service factory and clock without connecting at startup.""" + clock = clock or (lambda: datetime.now(UTC)) + + def app(environ, start_response): + headers = [("Cache-Control", "no-store"), ("X-Content-Type-Options", "nosniff")] + status = "200 OK" + content_type = "text/html; charset=utf-8" + now = clock() + machine = next(iter(machines)) + timezone = machines[machine].timezone + day, shift = most_recent_completed_shift(now, timezone) + error = None + report = None + generated_at = None + if environ.get("PATH_INFO", "/") != "/": + status, error = "404 Not Found", "Seite nicht gefunden." + elif environ.get("REQUEST_METHOD", "GET") != "GET": + status, error = "405 Method Not Allowed", "Diese Anfrage wird nicht unterstützt." + headers.append(("Allow", "GET")) + else: + try: + params = parse_qs( + environ.get("QUERY_STRING", ""), keep_blank_values=True, max_num_fields=10 + ) + if any(len(values) != 1 for values in params.values()): + raise ValueError + from datetime import date + + machine = params.get("machine", [machine])[0] + if machine not in machines: + raise ValueError + timezone = machines[machine].timezone + default_day, default_shift = most_recent_completed_shift(now, timezone) + day = date.fromisoformat(params.get("date", [default_day.isoformat()])[0]) + shift = params.get("shift", [default_shift])[0] + output = params.get("format", ["html"])[0] + if shift not in SHIFT_LABELS: + raise ValueError + if output not in ("html", "pdf"): + raise ValueError + start, end = shift_report_window(day, shift, timezone) + except (ValueError, OverflowError): + status = "400 Bad Request" + error = "Ungültige Auswahl. Bitte Datum, Schicht und Maschine prüfen." + else: + try: + report = service_factory().build(machine_name=machine, start=start, end=end) + generated_at = clock().astimezone(timezone) + if output == "pdf": + payload = render_pdf(report) + content_type = "application/pdf" + # Filename excludes externally configured machine names. + headers.append( + ( + "Content-Disposition", + f'attachment; filename="Schichtbericht-{day}-{shift}.pdf"', + ) + ) + else: + payload = None + except Exception: + status = "503 Service Unavailable" + error = ( + "Schichtbericht konnte nicht erstellt werden. " + "Bitte später erneut versuchen oder die Datenquellen prüfen lassen." + ) + report = None + if error or content_type != "application/pdf": + payload = render_page( + machines=machines, + sites=sites, + labels=SHIFT_LABELS, + day=day, + shift=shift, + machine=machine, + report=report, + generated_at=generated_at, + error=error, + ).encode("utf-8") + headers.extend([("Content-Type", content_type), ("Content-Length", str(len(payload)))]) + start_response(status, headers) + return [payload] + + return app + + +def main(argv=None): + from production_analytics.enlyze.exploration import load_secret_file + + parser = argparse.ArgumentParser(description="Live-Schichtberichte") + parser.add_argument("--host", default="127.0.0.1") + parser.add_argument( + "--port", type=int, default=int(os.environ.get("SHIFT_REPORT_PORT", "8087")) + ) + parser.add_argument("--config", type=Path, default=Path("config/shift-report-machines.yaml")) + parser.add_argument("--secrets-file", type=Path, default=Path("secrets/enlyze.env")) + parser.add_argument("--erp-secrets-file", type=Path, default=Path("secrets/erp.env")) + parser.add_argument("--db-secrets-file", type=Path, default=Path("secrets/postgres.env")) + args = parser.parse_args(argv) + config = load_shift_report_config(args.config) + machines = config.machines + + def service(): + environment = dict(os.environ) + for path in (args.secrets_file, args.erp_secrets_file, args.db_secrets_file): + environment.update(load_secret_file(path)) + return build_shift_report_service(machines, environment) + + app = create_app(machines, service, sites=config.sites) + with make_server(args.host, args.port, app) as server: + print(f"Schichtberichte: http://{args.host}:{args.port}/", flush=True) + server.serve_forever() + + +if __name__ == "__main__": + main() diff --git a/tests/test_area_material_consumption.py b/tests/test_area_material_consumption.py index e050e55..e15d2a2 100644 --- a/tests/test_area_material_consumption.py +++ b/tests/test_area_material_consumption.py @@ -16,6 +16,7 @@ from production_analytics.calculations.material_consumption import ( area_application_rate_kg_per_hour, ) from production_analytics.enlyze.gateway import EnlyzeApiGateway, EnlyzeProductionRun +from production_analytics.erp import ErpReadError from production_analytics.service.material_context import ErpNominalWidthProvider from production_analytics.service.material_polling import MaterialPollingService from production_analytics.service.material_state_store import JsonMaterialStateStore @@ -69,7 +70,7 @@ def test_missing_or_invalid_spreader_fails(bad): ) -def width_provider(): +def width_provider(fallback_nominal_width_m=None): erp = Mock() erp.get_current_workplace_status.return_value = SimpleNamespace( workplace='Bento 1', production_order='12026000814', article_number='180305', @@ -77,9 +78,111 @@ def width_provider(): ) return ErpNominalWidthProvider( erp, workplace='Bento 1', format_template='Bento 1-{production_order}', + fallback_nominal_width_m=fallback_nominal_width_m, ) +def test_erp_width_takes_priority_over_fallback(caplog): + provider = width_provider(5.0) + provider.gateway.get_current_workplace_status.return_value.article_description = '4,00 x 40 m' + assert provider('Bento 1-12026000814') == 4.0 + assert not caplog.records + + +@pytest.mark.parametrize('fallback', [None, 5.0]) +def test_combined_order_width_fallback(fallback, caplog): + provider = width_provider(fallback) + order = 'Bento 1-12026001005-Bento 1-12026001014' + if fallback is None: + with pytest.raises(ValueError, match='ERP context does not match the production order'): + provider(order) + assert not caplog.records + else: + assert provider(order) == 5.0 + assert len(caplog.records) == 1 + assert caplog.records[0].levelname == 'WARNING' + assert 'ERP nominal-width resolution failed' in caplog.text + assert order in caplog.text + assert 'fallback nominal width 5.0 m' in caplog.text + + +def test_fallback_warns_once_per_order_per_provider(caplog): + provider = width_provider(5.0) + first_order = 'Bento 1-12026001005-Bento 1-12026001014' + second_order = 'Bento 1-12026001015' + for order in (first_order, first_order, second_order, second_order, first_order): + assert provider(order) == 5.0 + assert len(caplog.records) == 2 + assert all(record.levelname == 'WARNING' for record in caplog.records) + assert first_order in caplog.records[0].getMessage() + assert second_order in caplog.records[1].getMessage() + + # A fresh provider has its own warning history. + assert width_provider(5.0)(first_order) == 5.0 + assert len(caplog.records) == 3 + + +def test_erp_resolution_still_runs_after_fallback(caplog): + provider = width_provider(5.0) + order = 'Bento 1-12026000814' + status = provider.gateway.get_current_workplace_status.return_value + status.article_description = None + assert provider(order) == 5.0 + status.article_description = '4,00 x 40 m' + assert provider(order) == 4.0 + status.article_description = None + assert provider(order) == 5.0 + assert len(caplog.records) == 1 + + +@pytest.mark.parametrize('failure', ['missing_status', 'missing_width', 'read_error']) +@pytest.mark.parametrize('fallback', [None, 5.0]) +def test_other_erp_width_failures(failure, fallback): + provider = width_provider(fallback) + gateway = provider.gateway + if failure == 'missing_status': + gateway.get_current_workplace_status.return_value = None + elif failure == 'missing_width': + gateway.get_current_workplace_status.return_value.article_description = None + else: + gateway.get_current_workplace_status.side_effect = ErpReadError('ERP read failed') + if fallback is None: + with pytest.raises(ErpReadError if failure == 'read_error' else ValueError): + provider('Bento 1-12026000814') + else: + assert provider('Bento 1-12026000814') == 5.0 + + +@pytest.mark.parametrize('value', [0, -1, float('nan'), float('inf'), -float('inf'), + True, '5.0', None, [], {}]) +def test_invalid_fallback_configuration(tmp_path, value): + with open('config/bento1-material-consumption.yaml') as stream: + document = yaml.safe_load(stream) + document['calculations'][0]['fallback_nominal_width_m'] = value + path = tmp_path / 'config.yaml' + path.write_text(yaml.safe_dump(document)) + with pytest.raises(CalculationConfigError, match='fallback_nominal_width_m'): + load_material_calculation(path) + + +@pytest.mark.parametrize('path', [ + 'config/bento1-material-consumption.yaml', + 'config/bento1-spreader3-material-consumption.yaml', +]) +def test_bento_fallback_configuration(path): + assert load_material_calculation(path).fallback_nominal_width_m == 5.0 + + +def test_direct_mass_rate_rejects_width_fallback(tmp_path): + with open('config/k7-material-consumption.yaml') as stream: + document = yaml.safe_load(stream) + document['calculations'][0]['fallback_nominal_width_m'] = 5.0 + path = tmp_path / 'config.yaml' + path.write_text(yaml.safe_dump(document)) + with pytest.raises(CalculationConfigError, match='width-based source mode'): + load_material_calculation(path) + + @pytest.mark.parametrize('configured,returned', [ ('Bento 1', 'BENTO 1'), ('Bento 1', ' \tBENTO 1\n'), @@ -195,6 +298,7 @@ def test_bento_rpm_bootstrap_and_persistent_resume(tmp_path, inter_run_gap_secon def test_k7_config_defaults_remain_direct(): config = load_material_calculation('config/k7-material-consumption.yaml') assert config.source_mode == 'direct_mass_rate' + assert config.fallback_nominal_width_m is None assert config.rotational_speed_signal_refs == () assert config.application_signal_refs == () assert config.gate_threshold == 0.5 diff --git a/tests/test_downtime_config.py b/tests/test_downtime_config.py new file mode 100644 index 0000000..f425d74 --- /dev/null +++ b/tests/test_downtime_config.py @@ -0,0 +1,95 @@ +"""Configured downtime runners share the existing machine and order contracts.""" + +from datetime import timedelta +from pathlib import Path + +import pytest + +from production_analytics.context import build_enlyze_production_order +from production_analytics.service import downtime_runtime +from production_analytics.service.downtime_runtime import load_downtime_config +from production_analytics.service.shift_report_config import load_shift_report_config + +ROOT = Path(__file__).resolve().parents[1] +NEW_RUNNERS = ( + ("e4", "E4", "12026001013", "E 4-12026001013"), + ("gitter1", "Gitter 1", "82026400869", "Gitter 1-82026400869"), + ("gitter2", "Gitter 2", "82026400909", "Gitter 2-82026400909"), + ("gitter3", "Gitter 3", "82026400900", "Gitter 3-82026400900"), + ("gitter4", "Gitter 4", "82026400876", "Gitter 4-82026400876"), + ("k5", "K5", "82026400921", "K 5-82026400921"), + ("secumat12", "Secumat 1/2", "82026400920", "Sec 1/2-82026400920"), + ("secumat3", "Secumat 3", "82026400912", "Sec 3-82026400912"), +) + + +@pytest.mark.parametrize("slug,name,erp_order,enlyze_order", NEW_RUNNERS) +def test_new_downtime_config_matches_report_machine_and_verified_order( + slug, name, erp_order, enlyze_order, +): + config = load_downtime_config(ROOT / "config" / f"{slug}-downtime.yaml") + report_config = load_shift_report_config(ROOT / "config" / "shift-report-machines.yaml") + machine = report_config.machines[name] + assert (config.machine_id, config.erp_workplace) == ( + machine.machine_id, machine.erp_workplace, + ) + assert build_enlyze_production_order(erp_order, config.production_order_format) == enlyze_order + assert (config.poll_interval_seconds, config.lookback_hours, + config.full_reconciliation_hours, config.completion_tolerance_m2) == ( + 300, 48, 24, 0.001, + ) + assert machine.capabilities.production and machine.capabilities.downtime + assert not machine.capabilities.material and machine.material is None + speed_enabled = name in {"Gitter 1", "Gitter 2", "Gitter 3", "Gitter 4", "K5"} + assert machine.capabilities.speed is speed_enabled + assert (machine.speed is not None) is speed_enabled + + unit = ROOT / "deploy" / "systemd" / f"production-analytics-downtime-{slug}.service" + text = unit.read_text(encoding="utf-8") + assert f"--config {ROOT / 'config' / f'{slug}-downtime.yaml'}" in text + assert "run downtime-reconcile" in text + assert "--secrets-file" in text and "--erp-secrets-file" in text + + +def test_existing_downtime_configs_and_capabilities_are_unchanged(): + machines = load_shift_report_config(ROOT / "config" / "shift-report-machines.yaml").machines + for slug, name in (("bento1", "B1"), ("e1", "E1"), ("k7", "K7")): + config = load_downtime_config(ROOT / "config" / f"{slug}-downtime.yaml") + assert config.machine_id == machines[name].machine_id + assert machines[name].capabilities.downtime + assert (config.poll_interval_seconds, config.lookback_hours, + config.full_reconciliation_hours, config.completion_tolerance_m2) == ( + 300, 48, 24, 0.001, + ) + + +@pytest.mark.parametrize("slug,name,erp_order,enlyze_order", NEW_RUNNERS) +def test_existing_generic_runtime_builds_each_new_runner( + monkeypatch, slug, name, erp_order, enlyze_order, +): + monkeypatch.setattr(downtime_runtime, "load_secret_file", lambda path: {}) + for settings in (downtime_runtime.ExplorationSettings, + downtime_runtime.ErpSettings, downtime_runtime.PostgresSettings): + monkeypatch.setattr(settings, "from_environment", lambda env: object()) + runner = downtime_runtime.build_downtime_runner( + ROOT / "config" / f"{slug}-downtime.yaml", + secrets_file=ROOT / "secrets" / "enlyze.env", + erp_secrets_file=ROOT / "secrets" / "erp.env", + ) + report_config = load_shift_report_config(ROOT / "config" / "shift-report-machines.yaml") + machine = report_config.machines[name] + assert runner.machine_id == runner.service.machine_id == machine.machine_id + assert runner.service.workplace == machine.erp_workplace + assert runner.interval == 300 + assert runner.service.lookback == timedelta(hours=48) + assert runner.service.full_reconciliation_interval == timedelta(hours=24) + assert runner.service.tolerance == 0.001 + assert build_enlyze_production_order( + erp_order, runner.service.production_order_format) == enlyze_order + + +def test_only_expected_machines_have_downtime_enabled(): + machines = load_shift_report_config(ROOT / "config" / "shift-report-machines.yaml").machines + assert {name for name, config in machines.items() if config.capabilities.downtime} == { + "B1", "E1", "K7", *(name for _, name, _, _ in NEW_RUNNERS), + } diff --git a/tests/test_erp_fiber_bookings.py b/tests/test_erp_fiber_bookings.py new file mode 100644 index 0000000..f447a0f --- /dev/null +++ b/tests/test_erp_fiber_bookings.py @@ -0,0 +1,76 @@ +import traceback +from decimal import Decimal +from unittest.mock import MagicMock + +import pytest +from test_erp_gateway import ENV + +from production_analytics.erp import ErpFiberBookingGateway, ErpReadError, ErpSettings + + +@pytest.fixture +def db(monkeypatch): + connect = MagicMock() + monkeypatch.setattr("production_analytics.erp.gateway.pymssql.connect", connect) + connection = connect.return_value.__enter__.return_value + cursor = connection.cursor.return_value.__enter__.return_value + cursor.fetchall.return_value = [("12026000994 ", "41070418 ", "Fiber ", Decimal("6877.80"))] + return connect, connection, cursor + + +def gateway(): + return ErpFiberBookingGateway(ErpSettings.from_environment(ENV)) + + +def test_order_query_is_parameterized_positive_and_not_shift_bounded(db): + connect, connection, cursor = db + rows = gateway().get_fiber_bookings("12026000994") + assert len(rows) == 1 + assert rows[0].production_order == "12026000994" + assert rows[0].material_number == "41070418" + assert rows[0].material_name == "Fiber" + assert rows[0].quantity_kg == 6877.8 + sql, parameters = cursor.execute.call_args.args + assert parameters == ("12026000994",) + assert "[Fertigungsauftragsnummer] = %s" in sql + assert "[Fasermenge] > 0" in sql + assert "NULLIF(LTRIM(RTRIM([Rohstoffnummer])), '') IS NOT NULL" in sql + assert "Zeitstempel" not in sql + assert "12026000994" not in sql + connect.assert_called_once_with( + server="localhost", + port=49601, + database="NV_DWH", + user=ENV["ERP_DB_USER"], + password=ENV["ERP_DB_PASSWORD"], + login_timeout=10, + timeout=10, + ) + connection.commit.assert_not_called() + connection.cursor.return_value.__exit__.assert_called_once() + connect.return_value.__exit__.assert_called_once() + + +def test_no_rows_returns_empty(db): + db[2].fetchall.return_value = [] + assert gateway().get_fiber_bookings("123") == [] + + +@pytest.mark.parametrize("order", [None, "", " ", "\x00"]) +def test_invalid_order_rejected_before_connect(db, order): + with pytest.raises(ValueError): + gateway().get_fiber_bookings(order) + db[0].assert_not_called() + + +def test_read_failure_does_not_expose_credentials(db): + db[2].execute.side_effect = RuntimeError(ENV["ERP_DB_PASSWORD"]) + with pytest.raises(ErpReadError, match="read failed") as caught: + gateway().get_fiber_bookings("123") + assert ENV["ERP_DB_PASSWORD"] not in "".join(traceback.format_exception(caught.value)) + + +def test_invalid_numeric_row_rejected(db): + db[2].fetchall.return_value = [("123", "M1", "Fiber", float("nan"))] + with pytest.raises(ErpReadError, match="invalid row"): + gateway().get_fiber_bookings("123") diff --git a/tests/test_erp_production_confirmation.py b/tests/test_erp_production_confirmation.py index b28c5a8..c535677 100644 --- a/tests/test_erp_production_confirmation.py +++ b/tests/test_erp_production_confirmation.py @@ -108,6 +108,39 @@ def test_exact_parameterized_workplace_and_half_open_window(db): assert "[Rückmeldemenge] >" not in sql +@pytest.mark.parametrize("timezone_name,expected_utc_hour", [ + ("Europe/Berlin", 6), ("Asia/Kuala_Lumpur", 0), +]) +def test_explicit_site_timezone_interprets_naive_sql_rows( + db, timezone_name, expected_utc_hour, +): + timezone = ZoneInfo(timezone_name) + start = datetime(2026, 10, 19, 6, tzinfo=timezone) + end = datetime(2026, 10, 19, 14, tzinfo=timezone) + local_row = datetime(2026, 10, 19, 8, 20) + db[2].fetchall.return_value = [(*ROW[:2], local_row, *ROW[3:])] + confirmation = read(start=start.astimezone(UTC), end=end.astimezone(UTC), + timezone=timezone)[0] + assert db[2].execute.call_args.args[1] == ( + "BENTO 1", datetime(2026, 10, 19, 6), datetime(2026, 10, 19, 14), + ) + assert confirmation.timestamp == local_row.replace(tzinfo=timezone) + assert confirmation.timestamp.tzinfo is timezone + assert confirmation.timestamp.astimezone(UTC).hour == expected_utc_hour + + +def test_malaysia_evening_confirmation_remains_local_evening(db): + malaysia = ZoneInfo("Asia/Kuala_Lumpur") + local_row = datetime(2026, 10, 19, 18) + db[2].fetchall.return_value = [(*ROW[:2], local_row, *ROW[3:])] + confirmation = read( + start=datetime(2026, 10, 19, 14, tzinfo=malaysia), + end=datetime(2026, 10, 19, 22, tzinfo=malaysia), timezone=malaysia, + )[0] + assert confirmation.timestamp.hour == 18 + assert confirmation.timestamp.astimezone(UTC) == datetime(2026, 10, 19, 10, tzinfo=UTC) + + def test_half_open_boundaries_with_query_simulation(db): rows = [ tuple([*ROW[:2], timestamp, *ROW[3:]]) diff --git a/tests/test_fiber_allocation.py b/tests/test_fiber_allocation.py new file mode 100644 index 0000000..b23caeb --- /dev/null +++ b/tests/test_fiber_allocation.py @@ -0,0 +1,250 @@ +from dataclasses import replace +from math import fsum +from unittest.mock import Mock + +import pytest +from test_shift_report import END, START, composition + +from production_analytics.calculations.fiber_allocation import ( + FiberBooking, + allocate_fiber_materials, +) +from production_analytics.calculations.shift_material import ShiftMaterialSummary +from production_analytics.presentation.shift_report import ( + MaterialPieBlock, + TableBlock, + present_report, + render_pdf, +) +from production_analytics.service.fiber_allocation import K7FiberAllocationService + +ORDER = "12026000994" +NAMES = ("PP 1A, weiß, 6,0, hf - 90- Drittland", "PP 1A, weiß, 6,0, hf - 90") +BOOKINGS = ( + FiberBooking(ORDER, "41070418", NAMES[0], 6878), + FiberBooking(ORDER, "41070419", NAMES[1], 3122), +) + + +def measured_item(order=f"K 7-{ORDER}", quantity=3468.77): + _, stubs, _, _ = composition("K7") + return replace( + stubs["materials"].result.items[0], production_order=order, consumption_kg=quantity + ) + + +def test_ratios_allocate_measured_mass_without_rounding(): + item = measured_item() + allocated = allocate_fiber_materials(item, BOOKINGS, erp_order=ORDER) + assert [value.material_number for value in allocated] == ["41070418", "41070419"] + assert [value.erp_booking_share for value in allocated] == pytest.approx([0.6878, 0.3122]) + assert [value.consumption_kg for value in allocated] == pytest.approx( + [2385.819006, 1082.950994] + ) + assert fsum(value.consumption_kg for value in allocated) == pytest.approx(item.consumption_kg) + assert allocated[0].consumption_kg != pytest.approx(item.consumption_kg * 0.69) + assert all(value.baseline_timestamp == item.baseline_timestamp for value in allocated) + assert all(value.end_timestamp == item.end_timestamp for value in allocated) + assert all(value.baseline_missing == item.baseline_missing for value in allocated) + assert item.material_number is None + + +def test_duplicate_bookings_aggregate_by_number_and_name(): + allocated = allocate_fiber_materials( + measured_item(), + [ + FiberBooking(ORDER, "M1", "Fiber", 20), + FiberBooking(ORDER, "M1", "Fiber", 30), + FiberBooking(ORDER, "M2", "Fiber", 50), + ], + erp_order=ORDER, + ) + assert len(allocated) == 2 + assert [item.material_number for item in allocated] == ["M1", "M2"] + assert [item.erp_booking_share for item in allocated] == [0.5, 0.5] + + +@pytest.mark.parametrize( + "bookings", + [ + [], + [FiberBooking(ORDER, "181900", "Product", 0)], + [ + FiberBooking(ORDER, "M1", "Fiber", -1), + FiberBooking(ORDER, "", "Fiber", 10), + FiberBooking(ORDER, None, "Fiber", 10), + FiberBooking(ORDER, "M1", "Fiber", None), + ], + ], +) +def test_no_usable_bookings_preserves_unassigned_measured_item(bookings): + item = measured_item() + assert allocate_fiber_materials(item, bookings, erp_order=ORDER) == (item,) + + +def test_invalid_rows_ignored_and_single_material_has_full_share(): + allocated = allocate_fiber_materials( + measured_item(), + [ + FiberBooking(ORDER, "M1", "Fiber", 25), + FiberBooking(ORDER, "M2", "Fiber", 0), + FiberBooking(ORDER, "M3", "Fiber", -10), + FiberBooking(ORDER, " ", "Fiber", 100), + FiberBooking(ORDER, "M4", "Fiber", float("nan")), + FiberBooking("other", "M5", "Fiber", 1000), + ], + erp_order=ORDER, + ) + assert len(allocated) == 1 + assert allocated[0].material_number == "M1" + assert allocated[0].erp_booking_share == 1 + assert allocated[0].consumption_kg == 3468.77 + + +def test_order_aware_service_preserves_totals_runs_and_caches_order_reads(): + reader = Mock() + reader.get_fiber_bookings.side_effect = lambda order: ( + BOOKINGS if order == ORDER else [FiberBooking(order, "M3", "Other fiber", 1)] + ) + items = ( + measured_item(quantity=100), + replace(measured_item(quantity=200), run_id="run2"), + measured_item("K 7-123", 400), + ) + measured = ShiftMaterialSummary(items[0].machine_id, START, END, 700, items) + allocated = K7FiberAllocationService(reader).allocate(measured) + assert allocated.total_consumption_kg == measured.total_consumption_kg + assert fsum(item.consumption_kg for item in allocated.items) == pytest.approx(700) + assert len(allocated.items) == 5 + assert allocated.items[-1].material_number == "M3" + assert allocated.items[-1].production_order == "K 7-123" + assert reader.get_fiber_bookings.call_count == 2 + assert measured.items == items + + +@pytest.mark.parametrize("order", ["K 7-123-K 7-456", "unknown", ""]) +def test_ambiguous_order_never_queries_or_invents_recipe(order): + reader = Mock() + item = measured_item(order) + measured = ShiftMaterialSummary(item.machine_id, START, END, item.consumption_kg, (item,)) + allocated = K7FiberAllocationService(reader).allocate(measured) + assert allocated.items == measured.items + reader.get_fiber_bookings.assert_not_called() + + +@pytest.mark.parametrize("machine", ["B1", "E1", "K7"]) +def test_report_wiring_applies_adapter_only_to_k7(machine): + service, stubs, _, _ = composition(machine) + reader = Mock() + reader.get_fiber_bookings.return_value = BOOKINGS + service.material_allocators = {"K7": K7FiberAllocationService(reader)} + stubs["materials"].result = ( + replace(stubs["materials"].result, items=(measured_item(quantity=42),)) + if machine == "K7" + else stubs["materials"].result + ) + value = service.build(machine_name=machine, start=START, end=END) + if machine == "K7": + assert len(value.materials.items) == 2 + reader.get_fiber_bookings.assert_called_once_with(ORDER) + else: + reader.get_fiber_bookings.assert_not_called() + assert ( + value.materials is stubs["channel_materials" if machine == "E1" else "materials"].result + ) + + +def test_same_allocation_behavior_for_differently_named_machine(): + service, stubs, _, config = composition("K7") + service.machines = {"Synthetic": config} + reader = Mock() + reader.get_fiber_bookings.return_value = BOOKINGS + service.material_allocators = {"Synthetic": K7FiberAllocationService(reader)} + item = measured_item(quantity=42) + stubs["materials"].result = replace(stubs["materials"].result, items=(item,)) + report = service.build(machine_name="Synthetic", start=START, end=END) + assert len(report.materials.items) == 2 + assert sum(part.consumption_kg for part in report.materials.items) == pytest.approx(42) + reader.get_fiber_bookings.assert_called_once_with(ORDER) + + +def test_pdf_displays_whole_shares_and_estimation_note(): + service, stubs, _, _ = composition("K7") + item = measured_item() + stubs["materials"].result = replace( + stubs["materials"].result, items=(item,), total_consumption_kg=item.consumption_kg + ) + reader = Mock() + reader.get_fiber_bookings.return_value = BOOKINGS + service.material_allocators = {"K7": K7FiberAllocationService(reader)} + report = service.build(machine_name="K7", start=START, end=END) + blocks = present_report(report) + table = next( + block for block in blocks if isinstance(block, TableBlock) and "ERP-Anteil" in block.headers + ) + rows = {row[2]: row for row in table.rows} + assert rows["41070418"][1:] == (NAMES[0], "41070418", "2.385,82 kg", "69%") + assert rows["41070419"][1:] == (NAMES[1], "41070419", "1.082,95 kg", "31%") + assert any( + getattr(block, "text", "") + == "Verbrauchsaufteilung geschätzt nach ERP-Buchungsverhältnis; Gesamtverbrauch aus ENLYZE." + for block in blocks + ) + chart = next(block for block in blocks if isinstance(block, MaterialPieBlock)) + assert fsum(chart.consumption_kg) == pytest.approx(3468.77) + + +def test_source_ratios_retain_precision_beyond_displayed_percentage(): + bookings = (replace(BOOKINGS[0], quantity_kg=6877.8), replace(BOOKINGS[1], quantity_kg=3122.2)) + allocated = allocate_fiber_materials(measured_item(), bookings, erp_order=ORDER) + assert [item.consumption_kg for item in allocated] == pytest.approx( + [2385.7496306, 1083.0203694] + ) + assert [f"{item.erp_booking_share * 100:.0f}%" for item in allocated] == ["69%", "31%"] + assert fsum(item.consumption_kg for item in allocated) == pytest.approx(3468.77) + + +def test_pdf_keeps_different_order_shares_separate_and_combines_material_pie(): + service, stubs, _, _ = composition("K7") + items = (measured_item(quantity=100), measured_item("K 7-123", 200)) + stubs["materials"].result = replace( + stubs["materials"].result, items=items, total_consumption_kg=300 + ) + reader = Mock() + reader.get_fiber_bookings.side_effect = lambda order: ( + BOOKINGS if order == ORDER else [replace(BOOKINGS[0], production_order=order)] + ) + service.material_allocators = {"K7": K7FiberAllocationService(reader)} + report = service.build(machine_name="K7", start=START, end=END) + blocks = present_report(report) + table = next( + block for block in blocks if isinstance(block, TableBlock) and "ERP-Anteil" in block.headers + ) + assert len(table.rows) == 3 + assert {(row[0], row[-1]) for row in table.rows} == { + (f"K 7-{ORDER}", "69%"), + (f"K 7-{ORDER}", "31%"), + ("K 7-123", "100%"), + } + chart = next(block for block in blocks if isinstance(block, MaterialPieBlock)) + assert len(chart.labels) == 2 + assert sorted(chart.consumption_kg) == pytest.approx([31.22, 268.78]) + assert render_pdf(report) == render_pdf(report) + + +def test_missing_erp_data_keeps_pdf_unassigned_and_measured_total(): + service, stubs, _, _ = composition("K7") + stubs["materials"].result = replace( + stubs["materials"].result, items=(measured_item(),), total_consumption_kg=3468.77 + ) + reader = Mock() + reader.get_fiber_bookings.return_value = [] + service.material_allocators = {"K7": K7FiberAllocationService(reader)} + report = service.build(machine_name="K7", start=START, end=END) + table = next( + block + for block in present_report(report) + if isinstance(block, TableBlock) and "Materialname" in block.headers + ) + assert table.rows == (("Materialzuordnung fehlt", "–", "3.468,77 kg"),) + assert report.materials.total_consumption_kg == 3468.77 diff --git a/tests/test_historical_reconcile.py b/tests/test_historical_reconcile.py new file mode 100644 index 0000000..1ca8637 --- /dev/null +++ b/tests/test_historical_reconcile.py @@ -0,0 +1,548 @@ +from dataclasses import replace +from datetime import UTC, datetime +from types import SimpleNamespace +from unittest.mock import MagicMock + +import pytest + +from production_analytics.enlyze.gateway import EnlyzeProductionRun +from production_analytics.service.historical_reconcile import ( + Decision, + HistoricalRecord, + decide, + reconcile_machine, + reconciliation_window, +) +from production_analytics.service.postgres_historical_reconcile import PostgresHistoricalRepository + + +def at(hour=12): + return datetime(2026, 10, 13, hour, tzinfo=UTC) + + +def record(order="old", machine="generic"): + return HistoricalRecord("material_consumption_snapshots", ("calc", machine, at()), + machine, at(), order, "retained-counter-run") + + +def run(order="Machine-123", machine="generic"): + return EnlyzeProductionRun("source-run", machine, None, order, at(10), at(14)) + + +def confirmation(order="123", hour=12): + return SimpleNamespace(production_order=order, workplace="workplace", + timestamp=at(hour), is_finished_goods=True) + + +def decision(r=None, runs=None, confirmations=None): + return decide(r or record(), runs if runs is not None else [run()], + confirmations if confirmations is not None else [confirmation()], + "workplace", "Machine-{production_order}") + + +def test_correct_and_stale_assignments(): + assert decision(record("Machine-123")).order == "Machine-123" + d = decision() + assert d.order == "Machine-123" + assert d.record.run_id == "retained-counter-run" + + +@pytest.mark.parametrize("machine", ["arbitrary-machine", "another-machine"]) +def test_machine_independent(machine): + assert decision(record(machine=machine), [run(machine=machine)]).order == "Machine-123" + + +@pytest.mark.parametrize("runs, confirmations", [ + ([run(), run("Machine-456")], [confirmation()]), + ([run()], [confirmation(), confirmation("456")]), + ([], [confirmation()]), + ([replace(run(), end=None)], [confirmation()]), + ([run(), replace(run(), end=None)], [confirmation()]), + ([run()], []), +]) +def test_ambiguous_or_missing_evidence(runs, confirmations): + assert decision(runs=runs, confirmations=confirmations).order is None + + +def test_previous_order_at_start_is_ignored_when_current_order_is_inside(): + start = confirmation("1030", 10) + current = confirmation("12026001032") + d = decide(record("K 7-12026001030", "reference-machine"), + [replace(run("K 7-12026001032", "reference-machine"), + start=at(10), end=at(14))], [start, current], + "workplace", "K 7-{production_order}") + assert d.order == "K 7-12026001032" + + +def test_interior_conflicting_order_remains_unresolved(): + assert decision(confirmations=[confirmation("123"), confirmation("456", 13)]).order is None + + +def test_correct_order_at_start_without_interior_evidence_is_unresolved(): + boundary = confirmation("123", 10) + assert decision(confirmations=[boundary]).order is None + + +def test_correct_order_strictly_inside_run_reconciles(): + assert decision(confirmations=[confirmation("123", 11)]).order == "Machine-123" + + +def test_confirmation_at_run_end_is_ignored(): + end = confirmation("123", 14) + assert decision(confirmations=[end]).order is None + + +def test_shared_boundary_confirmation_corroborates_neither_adjacent_run(): + left = replace(run("Machine-123"), start=at(10), end=at(12)) + right = replace(run("Machine-456"), uuid="right", start=at(12), end=at(14)) + boundary = confirmation("123", 12) + left_record = replace(record(), timestamp=at(11)) + right_record = replace(record(), timestamp=at(13)) + assert decide(left_record, [left, right], [boundary], "workplace", + "Machine-{production_order}").order is None + assert decide(right_record, [left, right], [boundary], "workplace", + "Machine-{production_order}").order is None + + +def test_k7_repaired_1030_to_1032_boundary_case_is_correctable(): + r = record("K 7-12026001030", "reference-machine") + run_start = at(11) + k7_run = replace(run("K 7-12026001032", "reference-machine"), + start=run_start, end=at(17)) + previous = confirmation("12026001030", 11) + d = decide(r, [k7_run], [previous, confirmation("12026001032", 12)], + "workplace", "K 7-{production_order}") + assert d.order == "K 7-12026001032" + + d = decide(r, [k7_run], [confirmation("12026001032"), confirmation("12026001037", 13)], + "workplace", "K 7-{production_order}") + assert d.order is None + + +def test_calendar_days_and_berlin_dst(): + start, end = reconciliation_window(datetime(2026, 10, 15, 2, 30, tzinfo=UTC)) + assert start.isoformat() == "2026-10-12T00:00:00+02:00" + assert end.isoformat() == "2026-10-15T00:00:00+02:00" + start, end = reconciliation_window(datetime(2026, 10, 27, tzinfo=UTC)) + assert (end.timestamp() - start.timestamp()) / 3600 == 73 + # UTC date still previous day; use Berlin's date. + assert reconciliation_window(datetime(2026, 10, 14, 23, tzinfo=UTC))[1].day == 15 + + +@pytest.mark.parametrize("days", [0, -1, True]) +def test_invalid_window(days): + with pytest.raises(ValueError): + reconciliation_window(at(), days) + + +def test_dry_run_and_source_failure(): + repository = MagicMock() + repository.read.return_value = [record()] + repository.guard_runs.side_effect = lambda decisions: decisions + source = MagicMock() + source.get_production_runs.return_value = [run()] + erp = MagicMock() + erp.get_confirmations.return_value = [confirmation()] + config = SimpleNamespace(machine_id="generic", erp_workplace="workplace") + decisions, applied = reconcile_machine(repository, source, erp, config, + "Machine-{production_order}", at(11), at(13), True) + assert decisions[0].order == "Machine-123" and applied == 0 + repository.apply.assert_not_called() + assert erp.get_confirmations.call_args.kwargs["start"] == at(10) + assert erp.get_confirmations.call_args.kwargs["end"] == at(14) + source.get_production_runs.side_effect = RuntimeError("source unavailable") + with pytest.raises(RuntimeError, match="source unavailable"): + reconcile_machine(repository, source, erp, config, "Machine-{production_order}", + at(11), at(13)) + repository.apply.assert_not_called() + + +def repository_with_connection(): + repository = PostgresHistoricalRepository(None) + connection = MagicMock() + repository.connect = MagicMock() + repository.connect.return_value.__enter__.return_value = connection + return repository, connection + + +def test_atomic_update_audit_and_repeated_run(): + repository, connection = repository_with_connection() + connection.execute.return_value.fetchone.side_effect = [(1,), (at(),)] + assert repository.apply([decision()]) == 1 + calls = connection.execute.call_args_list + assert len(calls) == 5 # isolation, lock, run guard, update, audit + update_args = calls[3].args[1] + assert update_args == ("Machine-123", "calc", "generic", at(), "old", "retained-counter-run") + audit_args = calls[4].args[1] + assert audit_args[0] == "generic" + assert audit_args[3:6] == ("old", "Machine-123", "retained-counter-run") + connection.reset_mock() + assert repository.apply([decision(record("Machine-123"))]) == 0 + assert connection.execute.call_count == 2 # no update or audit + + +def test_concurrent_change_fails_without_audit(): + repository, connection = repository_with_connection() + connection.execute.return_value.fetchone.side_effect = [(1,), None] + with pytest.raises(RuntimeError, match="concurrently"): + repository.apply([decision()]) + assert connection.execute.call_count == 4 + assert repository.connect.return_value.__exit__.call_args.args[0] is RuntimeError + + +def test_partial_and_split_run_guard(): + repository, connection = repository_with_connection() + connection.execute.return_value.fetchone.return_value = (2,) + assert repository.guard_runs([decision()])[0].order is None + d = decision() + other = replace(d, record=replace(d.record, timestamp=at(13)), order="Machine-456") + assert repository.guard_runs([d, other]) == [d, other] + assert all(d.order is None for d in repository.guard_runs([d, replace(other, order=None)])) + connection.execute.return_value.fetchone.return_value = (1,) + assert repository.guard_runs([decision()])[0].order == "Machine-123" + + +def test_database_failure_propagates(): + repository = PostgresHistoricalRepository(None) + repository.connect = MagicMock(side_effect=RuntimeError("database unavailable")) + with pytest.raises(RuntimeError, match="database unavailable"): + repository.read("machine", at(10), at(14)) + + +def test_cli_defaults(): + from production_analytics.cli.__main__ import _parser + args = _parser().parse_args(["historical-reconcile", "--dry-run"]) + assert args.lookback_days == 3 and args.dry_run and not args.verbose + assert _parser().parse_args(["historical-reconcile", "--verbose"]).verbose + assert _parser().parse_args(["historical-reconcile", "--dry-run", "--verbose"]).verbose + + +@pytest.mark.parametrize("split", [False, True]) +def test_end_to_end_dry_run_idempotency_and_physical_values(sqlite_schema, split): + import sqlite3 + + database = sqlite3.connect(":memory:") + database.executescript(sqlite_schema) + database.execute( + "INSERT INTO material_consumption_snapshots VALUES (?, ?, ?, ?, ?, ?)", + (at().isoformat(), "calc", "generic", "old", "retained-counter-run", 1234.5), + ) + + if split: + database.execute("DELETE FROM material_consumption_snapshots") + database.executemany( + "INSERT INTO material_consumption_snapshots VALUES (?, ?, ?, ?, ?, ?)", + [(at(hour).isoformat(), "calc", "generic", "OLD", "R1", value) + for hour, value in zip([10, 11, 12, 13], [1000, 1010, 1025, 1040])], + ) + + class Connection: + def __enter__(self): + return self + + def __exit__(self, exc_type, *_): + database.rollback() if exc_type else database.commit() + + def execute(self, statement, parameters=()): + statement = statement if isinstance(statement, str) else statement.as_string() + if statement.startswith(("SET TRANSACTION", "SELECT pg_advisory")): + return None + parameters = tuple( + str(p.obj) if hasattr(p, "obj") else p.isoformat() + if isinstance(p, datetime) else p for p in parameters + ) + return database.execute(statement.replace("%s", "?"), parameters) + + class Repository(PostgresHistoricalRepository): + def connect(self): + return Connection() + + def read(self, machine_id, start, end): + return [replace(r, timestamp=datetime.fromisoformat(r.timestamp), + identity=(*r.identity[:2], datetime.fromisoformat(r.identity[2]))) + for r in super().read(machine_id, start, end)] + + repository = Repository(None) + source = SimpleNamespace(get_production_runs=lambda machine: [run()]) + erp = SimpleNamespace(get_confirmations=lambda **kwargs: [confirmation()]) + config = SimpleNamespace(machine_id="generic", erp_workplace="workplace") + if split: + source = SimpleNamespace(get_production_runs=lambda machine: [ + replace(run("1032"), start=at(10), end=at(12)), + replace(run("1037"), uuid="second", start=at(12), end=at(14)), + ]) + erp = SimpleNamespace(get_confirmations=lambda **kwargs: [ + confirmation("1032", 11), confirmation("1037", 13)]) + template = "{production_order}" if split else "Machine-{production_order}" + args = (repository, source, erp, config, template, at(10), at(14)) + decisions, count = reconcile_machine(*args, dry_run=True) + assert count == 0 and decisions[0].order == ("1032" if split else "Machine-123") + assert database.execute("SELECT count(*) FROM historical_assignment_audit").fetchone() == (0,) + assert database.execute( + "SELECT production_order FROM material_consumption_snapshots" + ).fetchone() == (("OLD",) if split else ("old",)) + assert reconcile_machine(*args)[1] == (4 if split else 1) + assert reconcile_machine(*args)[1] == 0 + assert database.execute("SELECT count(*) FROM historical_assignment_audit").fetchone() == ( + 4 if split else 1,) + if split: + from production_analytics.calculations.shift_material import ( + ShiftMaterialSnapshot, + aggregate_shift_material, + ) + from production_analytics.service.historical_reconcile import grouped_counts + + assert grouped_counts(decisions) == (1, 1, 2, 0, 0) + rows = database.execute( + "SELECT timestamp, calculation_id, machine_id, production_order, run_id, " + "consumption_kg FROM material_consumption_snapshots ORDER BY timestamp" + ).fetchall() + snapshots = [ShiftMaterialSnapshot(datetime.fromisoformat(r[0]), *r[1:]) for r in rows] + assert [(r.timestamp.hour, r.run_id, r.consumption_kg) for r in snapshots] == [ + (10, "R1", 1000), (11, "R1", 1010), (12, "R1", 1025), (13, "R1", 1040)] + summary = aggregate_shift_material(snapshots, machine_id="generic", + calculation_ids=("calc",), start=at(10), end=at(14)) + assert [(i.production_order, i.consumption_kg) for i in summary.items] == [ + ("1032", 10), ("1037", 30)] + assert summary.total_consumption_kg == 40 + return + assert database.execute( + "SELECT timestamp, run_id, consumption_kg, production_order " + "FROM material_consumption_snapshots" + ).fetchone() == (at().isoformat(), "retained-counter-run", 1234.5, "Machine-123") + + +def test_erp_failure_never_becomes_no_changes(): + repository = MagicMock() + repository.read.return_value = [record()] + source = SimpleNamespace(get_production_runs=lambda machine: [run()]) + erp = MagicMock() + erp.get_confirmations.side_effect = RuntimeError("ERP offline") + with pytest.raises(RuntimeError, match="ERP offline"): + reconcile_machine(repository, source, erp, + SimpleNamespace(machine_id="generic", erp_workplace="workplace"), + "Machine-{production_order}", at(10), at(14)) + repository.apply.assert_not_called() + + +def test_runtime_reports_machine_failures_and_continues(monkeypatch, capsys): + from pathlib import Path + + from production_analytics.service import historical_runtime + + for factory in ("PostgresHistoricalRepository", "EnlyzeApiGateway", + "ExplorationClient", "ErpProductionConfirmationGateway"): + monkeypatch.setattr(historical_runtime, factory, MagicMock()) + for settings in (historical_runtime.PostgresSettings, historical_runtime.ErpSettings, + historical_runtime.ExplorationSettings): + monkeypatch.setattr(settings, "from_environment", MagicMock()) + reconcile = MagicMock(side_effect=[RuntimeError("source offline"), ([], 0), ([], 0)]) + monkeypatch.setattr(historical_runtime, "reconcile_machine", reconcile) + args = SimpleNamespace(lookback_days=3, dry_run=True, + config=Path("config/shift-report-machines.yaml"), + order_formats=Path("config/historical-order-formats.yaml")) + assert historical_runtime.run(args, {}) == 1 + assert reconcile.call_count == 3 + output = capsys.readouterr().out + assert "Physical runs inspected:" in output and "Unresolved segments:" in output + assert "Order segments proposed:" in output + assert "DRY RUN" in output and "FAILED B1" in output and "Failures: 1" in output + assert "source offline" in output + + +@pytest.mark.parametrize("dry_run", [True, False]) +@pytest.mark.parametrize("verbose", [True, False]) +def test_runtime_groups_record_output_and_preserves_totals(monkeypatch, capsys, dry_run, verbose): + from datetime import timedelta + from pathlib import Path + + from production_analytics.service import historical_runtime + + for factory in ("PostgresHistoricalRepository", "EnlyzeApiGateway", + "ExplorationClient", "ErpProductionConfirmationGateway"): + monkeypatch.setattr(historical_runtime, factory, MagicMock()) + for settings in (historical_runtime.PostgresSettings, historical_runtime.ErpSettings, + historical_runtime.ExplorationSettings): + monkeypatch.setattr(settings, "from_environment", MagicMock()) + + start = at(10) + correction_reason = ("closed ENLYZE run e0f474e0-1234 " + "[2026-10-13T10:00:00+00:00, 2026-10-13T14:00:00+00:00) " + "corroborated by ERP order K 7-12026001032") + corrections = [ + Decision(HistoricalRecord( + "material_consumption_snapshots", ("calc", "machine", start + timedelta(seconds=i)), + "machine", start + timedelta(seconds=i), "K 7-12026001030", "counter-run", + ), "K 7-12026001032", correction_reason) + for i in range(1964) + ] + unresolved = [ + Decision(HistoricalRecord( + "material_application_snapshots", ("application", "machine", + start + timedelta(seconds=i)), + "machine", start + timedelta(seconds=i), "B 1-42", "application-run", + ), None, "unresolved: missing or overlapping closed ENLYZE runs") + for i in range(8421) + ] + reconcile = MagicMock(side_effect=[(corrections, 1964 if not dry_run else 0), + (unresolved, 0), ([], 0)]) + monkeypatch.setattr(historical_runtime, "reconcile_machine", reconcile) + args = SimpleNamespace(lookback_days=3, dry_run=dry_run, verbose=verbose, + config=Path("config/shift-report-machines.yaml"), + order_formats=Path("config/historical-order-formats.yaml")) + + assert historical_runtime.run(args, {}) == 0 + output = capsys.readouterr().out + correction_action = "proposed" if dry_run else "corrected" + assert (f"B1 | {correction_action}: K 7-12026001030 -> K 7-12026001032 | " + "ENLYZE run e0f474e0-1234 | 1964 records") in output + assert ("E1 | unresolved: missing or overlapping closed ENLYZE runs | " + "physical run application-run | source material_application_snapshots/application | " + "8421 records | 2026-10-13T10:00:00+00:00 -> " + "2026-10-13T12:20:20+00:00") in output + assert output.count("1964 records") == 1 + assert output.count("8421 records") == 1 + if verbose: + assert output.count("Proposed B1 " if dry_run else "Corrected B1 ") == 1964 + assert output.count("Unresolved E1 ") == 8421 + else: + assert "Proposed B1 " not in output + assert "Corrected B1 " not in output + assert "Unresolved E1 " not in output + assert "('calc', 'machine'" not in output + assert len(output.splitlines()) == 15 + assert "Machines checked: 3\nRecords inspected: 10385" in output + assert f"Corrections {'proposed' if dry_run else 'applied'}: 1964" in output + assert "Ambiguous/unresolved: 8421\nUnchanged: 0\nFailures: 0" in output + assert "Physical runs inspected: 2\nRuns with proposed corrections: 1" in output + assert f"Order segments {correction_action}: 1" in output + assert "Unresolved runs: 1\nUnresolved segments: 1" in output + + +def test_grouped_counts_distinguish_rows_runs_and_segments(): + from production_analytics.service.historical_reconcile import grouped_counts + + d = decision() + decisions = [replace(d, record=replace(d.record, timestamp=at(hour)), order=order) + for hour, order in [(10, "A"), (11, "A"), (12, "B"), (13, None)]] + assert grouped_counts(decisions) == (1, 1, 2, 1, 1) + assert grouped_counts([]) == (0, 0, 0, 0, 0) + + +@pytest.mark.parametrize("calculation", [ + "bento1-fresh-bentonite-application", "bento1-spreader3-application", +]) +def test_application_collision_deduplicates_audits_and_is_idempotent( + sqlite_schema, calculation, +): + database, repository = application_repository(sqlite_schema) + for hour in (11, 12, 13): + insert_application(database, calculation, hour, "old", "old-run", 4730.169159683733) + insert_application(database, calculation, hour, "Machine-123", "source-run", + 4730.169159683733) + args = application_reconcile_args(repository) + decisions, count = reconcile_machine(*args, dry_run=True) + assert count == 0 and len([d for d in decisions if d.order != d.record.production_order]) == 3 + assert application_rows(database, calculation) == 6 + assert database.execute("SELECT count(*) FROM historical_assignment_audit").fetchone() == (0,) + assert reconcile_machine(*args)[1] == 3 + assert application_rows(database, calculation) == 3 + assert database.execute( + "SELECT production_order, run_id, application_g_m2 FROM material_application_snapshots " + "WHERE calculation_id = ? ORDER BY timestamp", (calculation,) + ).fetchall() == [("Machine-123", "source-run", 4730.169159683733)] * 3 + assert database.execute( + "SELECT previous_order, new_order, run_id, retained_run_id, action, reason, " + "record_identity FROM historical_assignment_audit ORDER BY id" + ).fetchall() == [ + ("old", "Machine-123", "old-run", "source-run", "deduplicated", + decisions[0].reason, str({"calculation_id": calculation, "machine_id": "generic", + "timestamp": str(at(hour))})) + for hour in (11, 12, 13) + ] + assert reconcile_machine(*args)[1] == 0 + + +def test_application_without_target_updates_normally(sqlite_schema): + database, repository = application_repository(sqlite_schema) + insert_application(database, "calc", 12, "old", "old-run", 42.5) + assert reconcile_machine(*application_reconcile_args(repository))[1] == 1 + assert database.execute( + "SELECT production_order, run_id, application_g_m2 FROM material_application_snapshots" + ).fetchone() == ("Machine-123", "old-run", 42.5) + assert database.execute( + "SELECT action, retained_run_id FROM historical_assignment_audit" + ).fetchone() == ("updated", None) + + +@pytest.mark.parametrize("target_value,target_run", [ + (99.0, "source-run"), (42.5, "unexpected-run"), +]) +def test_application_collision_rolls_back_whole_machine( + sqlite_schema, target_value, target_run, +): + database, repository = application_repository(sqlite_schema) + for hour in (11, 12): + insert_application(database, "calc", hour, "old", "old-run", 42.5) + insert_application(database, "calc", hour, "Machine-123", "source-run" if hour == 11 + else target_run, 42.5 if hour == 11 else target_value) + with pytest.raises(RuntimeError, match="conflicting measurement|unexpected target run"): + reconcile_machine(*application_reconcile_args(repository)) + assert application_rows(database, "calc") == 4 + assert database.execute("SELECT count(*) FROM historical_assignment_audit").fetchone() == (0,) + + +def application_repository(sqlite_schema): + import sqlite3 + + database = sqlite3.connect(":memory:") + database.executescript(sqlite_schema) + + class Connection: + def __enter__(self): + return self + + def __exit__(self, exc_type, *_): + database.rollback() if exc_type else database.commit() + + def execute(self, statement, parameters=()): + statement = statement if isinstance(statement, str) else statement.as_string() + if statement.startswith(("SET TRANSACTION", "SELECT pg_advisory")): + return None + parameters = tuple( + str(p.obj) if hasattr(p, "obj") else p.isoformat() + if isinstance(p, datetime) else p for p in parameters + ) + return database.execute(statement.replace(" FOR UPDATE", "").replace("%s", "?"), + parameters) + + class Repository(PostgresHistoricalRepository): + def connect(self): + return Connection() + + def read(self, machine_id, start, end): + return [replace(r, timestamp=datetime.fromisoformat(r.timestamp), + identity=(*r.identity[:2], datetime.fromisoformat(r.identity[2]))) + for r in super().read(machine_id, start, end)] + + return database, Repository(None) + + +def insert_application(database, calculation, hour, order, run_id, value): + database.execute("INSERT INTO material_application_snapshots VALUES (?, ?, ?, ?, ?, ?)", + (at(hour).isoformat(), calculation, "generic", order, run_id, value)) + database.commit() + + +def application_rows(database, calculation): + return database.execute( + "SELECT count(*) FROM material_application_snapshots WHERE calculation_id = ?", + (calculation,), + ).fetchone()[0] + + +def application_reconcile_args(repository): + source = SimpleNamespace(get_production_runs=lambda machine: [run()]) + erp = SimpleNamespace(get_confirmations=lambda **kwargs: [confirmation()]) + config = SimpleNamespace(machine_id="generic", erp_workplace="workplace") + return repository, source, erp, config, "Machine-{production_order}", at(10), at(14) diff --git a/tests/test_linear_signal_material.py b/tests/test_linear_signal_material.py index c253f44..a138242 100644 --- a/tests/test_linear_signal_material.py +++ b/tests/test_linear_signal_material.py @@ -120,6 +120,7 @@ def test_runtime_isolation_and_disjoint_runs(tmp_path, monkeypatch): assert separate.service._signal_discharge == ( configs[0].specific_discharge_kg_per_signal_unit_m) assert separate.service._nominal_width_provider.format_template == 'Bento 1-{production_order}' + assert separate.service._nominal_width_provider.fallback_nominal_width_m == 5.0 machine = configs[0].machine_ref order = 'Bento 1-test' separate_path = separate.service._state_store.store._path(machine, order) diff --git a/tests/test_rotational_material_consumption.py b/tests/test_rotational_material_consumption.py index 2bfbe50..04c3c3b 100644 --- a/tests/test_rotational_material_consumption.py +++ b/tests/test_rotational_material_consumption.py @@ -119,4 +119,5 @@ def test_bento_runtime_wiring(tmp_path, monkeypatch): assert service._gate_variable_id == 'fef41976-1103-4090-b780-eaeecc02fdfa' assert service._config == MaterialIntegratorConfig(0.3, 20) assert service._nominal_width_provider.workplace == 'Bento 1' + assert service._nominal_width_provider.fallback_nominal_width_m == 5.0 erp_settings.from_secret_file.assert_called_once_with(tmp_path / 'erp.env') diff --git a/tests/test_shift_downtime.py b/tests/test_shift_downtime.py index c871d87..75b0173 100644 --- a/tests/test_shift_downtime.py +++ b/tests/test_shift_downtime.py @@ -1,3 +1,4 @@ +import sqlite3 import traceback from dataclasses import FrozenInstanceError, replace from datetime import UTC, datetime, timedelta @@ -83,6 +84,103 @@ def test_open_event_clipped_to_shift_end(): assert summary.events[0].source.source_end is None +def test_raw_closed_event_without_attribution(): + source = event(start=START + timedelta(hours=1), end=START + timedelta(hours=2)) + summary = summarize([source]) + assert source.attributed_start is source.attributed_end is None + assert summary.events[0].start == source.source_start + assert summary.events[0].end == source.source_end + assert summary.total_downtime_seconds == 3600 + + +def test_attributed_end_closes_raw_open_event(): + attributed_end = START + timedelta(hours=2) + source = event(end=None, attributed_end=attributed_end) + summary = summarize([source]) + assert summary.events[0].start == START + assert summary.events[0].end is attributed_end + assert summary.events[0].source.source_end is None + assert summary.total_downtime_seconds == 2 * 3600 + + +def test_attributed_start_with_no_end_remains_open(): + summary = summarize([event(end=None, attributed_start=START + timedelta(hours=7))]) + assert summary.total_downtime_seconds == 3600 + assert summary.events[0].end is END + + +def test_attribution_overrides_conflicting_raw_interval(): + attributed_start = START + timedelta(hours=1) + attributed_end = START + timedelta(hours=2) + source = event( + start=END, + end=END + timedelta(hours=2), + attributed_start=attributed_start, + attributed_end=attributed_end, + ) + summary = summarize([source]) + assert summary.events[0].start is attributed_start + assert summary.events[0].end is attributed_end + assert summary.total_downtime_seconds == 3600 + assert source.source_start == END + assert source.source_end == END + timedelta(hours=2) + + +def test_attributed_interval_clips_both_shift_boundaries(): + source = event( + start=END, + end=END, + attributed_start=START - timedelta(hours=1), + attributed_end=END + timedelta(hours=1), + ) + summary = summarize([source]) + assert summary.events[0].start is START + assert summary.events[0].end is END + assert summary.total_downtime_seconds == 8 * 3600 + + +def test_production_reconciled_no_data_event_does_not_overlap_later_shift(): + source_start = datetime(2026, 10, 12, 8, 56, 30, tzinfo=UTC) + source = event( + start=source_start, + end=None, + attributed_start=source_start, + attributed_end=datetime(2026, 10, 12, 12, 36, 2, tzinfo=UTC), + ) + summary = summarize( + [source], + start=datetime(2026, 10, 13, 12, tzinfo=UTC), + end=datetime(2026, 10, 13, 20, tzinfo=UTC), + ) + assert summary.events == summary.reasons == () + assert summary.total_downtime_seconds == 0 + assert summary.non_downtime_seconds == 8 * 3600 + + +def test_attributed_intervals_preserve_union_and_reason_aggregation(): + sources = [ + event( + identifier, + end=None, + reason=reason, + attributed_start=START + timedelta(hours=lower), + attributed_end=START + timedelta(hours=upper), + ) + for identifier, reason, lower, upper in [ + ("a", "A", 0, 2), + ("b", "A", 1, 3), + ("c", "B", 2, 4), + ] + ] + summary = summarize(sources) + assert summary.total_downtime_seconds == 4 * 3600 + assert summary.non_downtime_seconds == 4 * 3600 + assert [ + (reason.reason_name, reason.duration_seconds, reason.event_count) + for reason in summary.reasons + ] == [("A", 3 * 3600, 2), ("B", 2 * 3600, 1)] + + def test_overlap_nested_duplicates_and_adjacent_intervals_are_not_double_counted(): events = [ event("a", end=START + timedelta(hours=2)), @@ -207,6 +305,8 @@ def db(monkeypatch): None, "UNKNOWN", None, + START.astimezone(UTC), + END.astimezone(UTC), ) ] repository = PostgresDowntimeRepository(PostgresSettings("localhost", 5432, "db", "user", "pw")) @@ -218,10 +318,14 @@ def test_repository_sql_parameters_mapping_and_lifecycle(db): values = repository.get_events(machine_id="machine", start=START, end=END) sql, params = connection.execute.call_args.args assert params == ("machine", END, START) - assert "WHERE machine_id = %s AND source_start < %s" in sql - assert "source_end IS NULL OR source_end > %s" in sql - assert "ORDER BY source_start, external_id" in sql - assert "attributed_" not in sql and "production_order" not in sql + assert "WHERE machine_id = %s AND COALESCE(attributed_start, source_start) < %s" in sql + assert "COALESCE(attributed_end, source_end) IS NULL" in sql + assert "OR COALESCE(attributed_end, source_end) > %s" in sql + assert "ORDER BY COALESCE(attributed_start, source_start), external_id" in sql + assert "category, comment, attributed_start, attributed_end" in sql + assert "production_order" not in sql + assert values[0].attributed_start == START.astimezone(UTC) + assert values[0].attributed_end == END.astimezone(UTC) assert len(values) == 1 and values[0].source_end is None assert values[0].source_start.tzinfo is UTC connect.assert_called_once_with( @@ -245,6 +349,46 @@ def test_machine_id_is_parameterized(db): assert params[0] == machine_id +def test_repository_excludes_production_reconciled_event_from_later_shift(db): + repository, _, connection = db + # Execute the repository's overlap predicate, translating only driver placeholders. + with sqlite3.connect(":memory:") as database: + database.execute( + """CREATE TABLE production_downtime_events ( + external_id, machine_id, source_start, source_end, + reason_id, reason_name, reason_description, reason_group, + category, comment, attributed_start, attributed_end)""" + ) + database.execute( + """INSERT INTO production_downtime_events + (external_id, machine_id, source_start, attributed_start, attributed_end) + VALUES (?, ?, ?, ?, ?)""", + ( + "reconciled-no-data", + "machine", + "2026-10-12T08:56:30+00:00", + "2026-10-12T08:56:30+00:00", + "2026-10-12T12:36:02+00:00", + ), + ) + + def execute(sql, params): + return database.execute( + sql.replace("%s", "?"), + tuple( + value.isoformat() if isinstance(value, datetime) else value + for value in params + ), + ) + + connection.execute.side_effect = execute + assert repository.get_events( + machine_id="machine", + start=datetime(2026, 10, 13, 12, tzinfo=UTC), + end=datetime(2026, 10, 13, 20, tzinfo=UTC), + ) == [] + + @pytest.mark.parametrize( "changes", [ @@ -291,6 +435,10 @@ def test_repository_errors_are_safe(db, stage): [ {"source_start": START.replace(tzinfo=None)}, {"source_end": END.replace(tzinfo=None)}, + {"attributed_start": START.replace(tzinfo=None)}, + {"attributed_end": END.replace(tzinfo=None)}, + {"attributed_start": "invalid"}, + {"attributed_end": "invalid"}, {"source_end": START - timedelta(seconds=1)}, {"reason_name": 123}, ], diff --git a/tests/test_shift_material.py b/tests/test_shift_material.py index e89783a..ccc7c05 100644 --- a/tests/test_shift_material.py +++ b/tests/test_shift_material.py @@ -202,9 +202,8 @@ def test_channel_b_identity_attribution_and_no_null_carry_forward(): ] summary = aggregate(rows, channel=True) assert [(item.material_name, item.consumption_kg) for item in summary.items] == [ - ("Material A", 30), + ("Material A", 45), (None, 10), - ("Material A", 15), ("Material B", 10), ] assert summary.items[1].material_mapping_status == "UNAVAILABLE" @@ -243,6 +242,7 @@ def test_e1_historical_null_channel_fixtures(): for minutes, value in ((-1, 5000), (479, 5000 + delta)) ] summary = aggregate(rows, channel=True) + assert summary.total_consumption_kg == pytest.approx(24_886.805) assert len(summary.items) == 14 assert {(item.extruder, item.doser_channel): item.consumption_kg for item in summary.items} == ( pytest.approx( @@ -321,14 +321,54 @@ def test_service_composes_once_and_propagates_errors(channel): @pytest.mark.parametrize("channel", [False, True]) -def test_ambiguous_stream_timestamps_and_reappearing_runs_rejected(channel): +def test_ambiguous_stream_timestamps_and_reappearing_runs_allowed(channel): sample = channel_sample if channel else machine_sample with pytest.raises(ValueError, match="same stream timestamp"): aggregate([sample(0, 100), sample(0, 100)], channel=channel) - with pytest.raises(ValueError, match="reappeared"): - aggregate([sample(0, 100), sample(10, 10, run="r2"), sample(20, 200)], channel=channel) - with pytest.raises(ValueError, match="Production order"): - aggregate([sample(0, 100), sample(10, 110, order="different")], channel=channel) + summary = aggregate([ + sample(0, 100), sample(10, 110), sample(20, 500, run="r2"), + sample(30, 520, run="r2"), sample(40, 200), sample(50, 230), + ], channel=channel) + assert summary.total_consumption_kg == 60 + assert [(item.run_id, item.consumption_kg) for item in summary.items] == [ + ("r1", 10), ("r2", 20), ("r1", 30), + ] + assert summary.items[2].baseline_missing + summary = aggregate([sample(0, 100), sample(10, 110, order="different")], channel=channel) + assert [(i.production_order, i.consumption_kg) for i in summary.items] == [("different", 10)] + + +@pytest.mark.parametrize("channel", [False, True]) +def test_reappearing_run_keeps_order_attribution_within_each_segment(channel): + sample = channel_sample if channel else machine_sample + rows = [ + sample(0, 100, run="A", order="first"), + sample(1, 110, run="A", order="second"), + sample(2, 500, run="B", order="second"), + sample(3, 520, run="B", order="third"), + sample(4, 200, run="A", order="third"), + sample(5, 230, run="A", order="fourth"), + ] + summary = aggregate(rows, channel=channel) + assert [(i.run_id, i.production_order, i.consumption_kg) for i in summary.items] == [ + ("A", "second", 10), ("B", "third", 20), ("A", "fourth", 30), + ] + + +def test_channel_identity_gap_does_not_bridge_across_reappearing_run_segment(): + rows = [ + channel_sample(0, 100, run="A", name="Known"), + channel_sample(1, 110, run="A", name=None), + channel_sample(2, 500, run="B", name="Other"), + channel_sample(3, 520, run="B", name="Other"), + channel_sample(4, 200, run="A", name=None), + channel_sample(5, 230, run="A", name="Known"), + ] + summary = aggregate(rows, channel=True) + assert summary.total_consumption_kg == 60 + assert [(item.run_id, item.material_name, item.consumption_kg) for item in summary.items] == [ + ("A", None, 10), ("B", "Other", 20), ("A", "Known", 30), + ] def test_machine_and_calculation_scoping(): @@ -375,17 +415,22 @@ def test_new_run_exactly_at_shift_start_is_its_own_baseline(channel): def test_invalid_counters_do_not_hide_run_boundaries(channel): sample = channel_sample if channel else machine_sample summary = aggregate( - [sample(-2, 1000), sample(-1, None, run="r2"), - sample(10, 50, run="r2"), sample(20, 60, run="r2")], + [ + sample(-2, 1000), + sample(-1, None, run="r2"), + sample(10, 50, run="r2"), + sample(20, 60, run="r2"), + ], channel=channel, ) assert summary.total_consumption_kg == 10 assert len(summary.items) == 1 assert summary.items[0].run_id == "r2" assert summary.items[0].baseline_missing - with pytest.raises(ValueError, match="reappeared"): - aggregate([sample(0, 100), sample(10, None, run="r2"), sample(20, 120)], - channel=channel) + summary = aggregate( + [sample(0, 100), sample(10, None, run="r2"), sample(20, 120)], channel=channel + ) + assert summary.total_consumption_kg == 0 @pytest.mark.parametrize("channel", [False, True]) @@ -401,7 +446,229 @@ def test_spring_dst_window_uses_elapsed_instants(channel): start = datetime(2026, 3, 29, 1, 30, tzinfo=berlin) end = datetime(2026, 3, 29, 3, 30, tzinfo=berlin) sample = channel_sample if channel else machine_sample - rows = [replace(sample(value=value), timestamp=timestamp) for timestamp, value in - [(start, 100), (datetime(2026, 3, 29, 1, 20, tzinfo=UTC), 110), (end, 999)]] + rows = [ + replace(sample(value=value), timestamp=timestamp) + for timestamp, value in [ + (start, 100), + (datetime(2026, 3, 29, 1, 20, tzinfo=UTC), 110), + (end, 999), + ] + ] assert (end.astimezone(UTC) - start.astimezone(UTC)).total_seconds() == 3600 assert aggregate(rows, channel=channel, start=start, end=end).total_consumption_kg == 10 + + +@pytest.mark.parametrize("middle", [None, "Material B"]) +@pytest.mark.parametrize("missing", [False, True]) +def test_repeated_channel_identity_consolidates_after_interval_attribution(middle, missing): + offset = 1 if missing else 0 + rows = [ + channel_sample(offset, 100, name="Material A"), + channel_sample(10, 110, name="Material A"), + channel_sample(20, 115, name=middle), + channel_sample(30, 135, name="Material A", quality=False), + ] + summary = aggregate(rows, channel=True) + assert len(summary.items) == 2 + a, other = summary.items + assert (a.material_name, a.consumption_kg) == ("Material A", 30) + assert (other.material_name, other.consumption_kg) == (middle, 5) + assert a.baseline_timestamp == rows[0].timestamp + assert a.end_timestamp == rows[-1].timestamp + assert not a.percentage_sum_valid + assert other.percentage_sum_valid + assert all(item.baseline_missing == missing for item in summary.items) + if middle is None: + assert other.material_mapping_status == "UNAVAILABLE" + assert summary.total_consumption_kg == 35 + assert summary == aggregate(reversed(rows), channel=True) + + +def test_hundreds_of_alternating_channel_identities_consolidate(): + rows = [channel_sample(0, 100)] + [ + channel_sample(index, 100 + index, name="Material A" if index % 2 else None) + for index in range(1, 401) + ] + summary = aggregate(rows, channel=True) + assert [(item.material_name, item.consumption_kg) for item in summary.items] == [ + ("Material A", 399), + (None, 1), + ] + assert summary.total_consumption_kg == 400 + assert summary == aggregate(reversed(rows), channel=True) + + +@pytest.mark.parametrize("context", ["channel", "extruder", "run", "order", "calculation"]) +def test_channel_consolidation_keeps_unrelated_streams_and_runs_separate(context): + rows = [channel_sample(0, 100), channel_sample(10, 110)] + changes = { + "channel": {"doser_channel": "C2"}, + "extruder": {"extruder": "Ex2"}, + "run": {"run_id": "r2"}, + "order": {"run_id": "r2", "production_order": "other"}, + "calculation": {"calculation_id": "calc2"}, + }[context] + rows += [ + replace(channel_sample(20, 500), **changes), + replace(channel_sample(30, 520), **changes), + ] + summary = aggregate(rows, channel=True, calculation_ids=("calc", "calc2")) + assert len(summary.items) == 2 + assert sorted(item.consumption_kg for item in summary.items) == [10, 20] + assert summary.total_consumption_kg == 30 + + +@pytest.mark.parametrize( + "field,value", [("material_number", "123"), ("material_mapping_status", "OTHER")] +) +def test_channel_consolidation_preserves_distinct_identity_metadata(field, value): + rows = [ + channel_sample(0, 100), + channel_sample(10, 110), + replace(channel_sample(20, 120), **{field: value}), + channel_sample(30, 130), + ] + summary = aggregate(rows, channel=True) + assert len(summary.items) == 2 + assert sorted(item.consumption_kg for item in summary.items) == [10, 20] + assert summary.total_consumption_kg == 30 + + +@pytest.mark.parametrize("include_zero", [False, True]) +def test_consolidated_channel_zero_handling(include_zero): + rows = [ + channel_sample(0, 100), + channel_sample(10, 100), + channel_sample(20, 105, name=None), + channel_sample(30, 105), + ] + summary = aggregate(rows, channel=True, include_zero=include_zero) + assert summary.total_consumption_kg == 5 + assert len(summary.items) == (2 if include_zero else 1) + if include_zero: + assert summary.items[0].consumption_kg == 0 + assert summary.items[0].baseline_timestamp == rows[0].timestamp + assert summary.items[0].end_timestamp == rows[-1].timestamp + + +@pytest.mark.parametrize("minutes", [(0, 1, 2), (0, 0.5, 1, 1.5), (0, 5, 10)]) +def test_short_bounded_unknown_gap_bridges_all_deltas(minutes): + rows = [ + channel_sample( + minute, + 100 + index * 10, + name=" Material A " if index in (0, len(minutes) - 1) else None, + quality=index != 1, + ) + for index, minute in enumerate(minutes) + ] + summary = aggregate(rows, channel=True) + assert len(summary.items) == 1 + item = summary.items[0] + assert item.material_name == "Material A" + assert item.consumption_kg == (len(minutes) - 1) * 10 + assert summary.total_consumption_kg == rows[-1].cumulative_consumption_kg - 100 + assert item.baseline_timestamp == rows[0].timestamp + assert item.end_timestamp == rows[-1].timestamp + assert not item.percentage_sum_valid + assert not item.baseline_missing + assert summary == aggregate(reversed(rows), channel=True) + + +@pytest.mark.parametrize( + "names,minutes", + [ + (("Material A", None, "Material B"), (0, 1, 2)), + (("Material A", None, None), (0, 1, 2)), + ((None, None, "Material A"), (0, 1, 2)), + (("Material A", None, "Material A"), (0, 1, 25)), + (("Material A", None, "Material A"), (0, 5, 10.01)), + ], +) +def test_ambiguous_unbounded_or_long_identity_gaps_stay_unknown(names, minutes): + rows = [ + channel_sample(minute, 100 + index * 10, name=name) + for index, (minute, name) in enumerate(zip(minutes, names)) + ] + summary = aggregate(rows, channel=True) + unknown = next(item for item in summary.items if item.material_name is None) + assert unknown.consumption_kg == (20 if names[-1] is None else 10) + assert unknown.material_mapping_status == "UNAVAILABLE" + assert summary.total_consumption_kg == 20 + + +@pytest.mark.parametrize( + "field,value", [("material_number", "M2"), ("material_mapping_status", "OTHER")] +) +def test_bridging_requires_exact_normalized_identity(field, value): + rows = [ + channel_sample(0, 100, number="M1"), + channel_sample(0.5, 105, number="M1"), + channel_sample(1, 115, name=None), + replace(channel_sample(2, 120, number="M1"), **{field: value}), + ] + summary = aggregate(rows, channel=True) + assert len(summary.items) == 3 + assert summary.items[1].material_name is None + assert summary.items[1].consumption_kg == 10 + assert summary.total_consumption_kg == 20 + + +@pytest.mark.parametrize("boundary", ["run", "order", "channel", "extruder"]) +def test_bridging_never_crosses_context_boundaries(boundary): + changes = { + "run": {"run": "r2"}, + "order": {"run": "r2", "order": "new-order"}, + "channel": {"channel": "C2"}, + "extruder": {"extruder": "Ex2"}, + }[boundary] + rows = [ + channel_sample(0, 100), + channel_sample(1, 110, name=None), + channel_sample(2, 500, **changes), + channel_sample(3, 520, **changes), + ] + summary = aggregate(rows, channel=True) + unknown = next(item for item in summary.items if item.material_name is None) + assert unknown.consumption_kg == 10 + assert summary.total_consumption_kg == 30 + + +def test_short_bridge_preserves_missing_baseline_and_zero_filter(): + rows = [channel_sample(1, 100), channel_sample(2, 100, name=None), channel_sample(3, 100)] + summary = aggregate(rows, channel=True) + assert len(summary.items) == 1 + assert summary.items[0].baseline_missing + assert summary.total_consumption_kg == 0 + assert aggregate(rows, channel=True, include_zero=False).items == () + + +@pytest.mark.parametrize("channel", [False, True]) +def test_orders_within_physical_run_conserve_counter_and_use_end_order(channel): + sample = channel_sample if channel else machine_sample + rows = [sample(i, value, order=order) for i, value, order in + [(0, 1000, "1032"), (1, 1010, "1032"), + (2, 1025, "1037"), (3, 1040, "1037")]] + summary = aggregate(rows, channel=channel) + assert [(i.production_order, i.consumption_kg) for i in summary.items] == [ + ("1032", 10), ("1037", 30)] + assert {i.run_id for i in summary.items} == {"r1"} + assert summary.total_consumption_kg == 40 + assert aggregate([replace(r, production_order="OLD") for r in rows], + channel=channel).total_consumption_kg == 40 + rows[2] = sample(2, 1005, order="1037") + with pytest.raises(ValueError, match="decreased/reset"): + aggregate(rows, channel=channel) + + +@pytest.mark.parametrize("orders", [("X", "Y", "Y"), ("X", "X", "Y"), ("X", "Y", "X")]) +def test_channel_unknown_gap_cannot_bridge_order_boundary(orders): + rows = [channel_sample(0, 100, order=orders[0]), + channel_sample(1, 110, name=None, order=orders[1]), + channel_sample(2, 120, order=orders[2])] + summary = aggregate(rows, channel=True) + unknown = [i for i in summary.items if i.material_name is None] + assert len(unknown) == 1 + assert unknown[0].production_order == orders[1] + assert unknown[0].consumption_kg == 10 + assert summary.total_consumption_kg == 20 diff --git a/tests/test_shift_production.py b/tests/test_shift_production.py index 56819ff..acacb47 100644 --- a/tests/test_shift_production.py +++ b/tests/test_shift_production.py @@ -216,6 +216,20 @@ def test_service_reads_once_and_preserves_boundary_timezones(): assert summary.items[0].first_confirmation_at.tzinfo is BERLIN +def test_service_passes_explicit_site_timezone_to_gateway(): + malaysia = ZoneInfo("Asia/Kuala_Lumpur") + gateway = Mock() + gateway.get_confirmations.return_value = [] + start = datetime(2026, 10, 19, 6, tzinfo=malaysia) + end = datetime(2026, 10, 19, 14, tzinfo=malaysia) + ShiftProductionService(gateway).summarize( + workplace="Malaysia", start=start, end=end, timezone=malaysia, + ) + gateway.get_confirmations.assert_called_once_with( + workplace="Malaysia", start=start, end=end, timezone=malaysia, + ) + + def test_gateway_errors_propagate(): gateway = Mock() gateway.get_confirmations.side_effect = ErpReadError("ERP production confirmation read failed") diff --git a/tests/test_shift_report.py b/tests/test_shift_report.py index 9f47a5e..10b60dd 100644 --- a/tests/test_shift_report.py +++ b/tests/test_shift_report.py @@ -1,7 +1,8 @@ from copy import deepcopy from dataclasses import FrozenInstanceError -from datetime import UTC, date, timedelta +from datetime import UTC, date, datetime, timedelta from pathlib import Path +from zoneinfo import ZoneInfo import pytest import yaml @@ -17,13 +18,20 @@ from production_analytics.calculations.shift_production import ( ShiftProductionItem, ShiftProductionSummary, ) -from production_analytics.calculations.shift_report import shift_report_window +from production_analytics.calculations.shift_report import ( + most_recent_completed_shift, + shift_report_window, +) from production_analytics.calculations.shift_speed import aggregate_shift_speed from production_analytics.service.shift_report import ShiftReportService -from production_analytics.service.shift_report_config import load_shift_report_machines +from production_analytics.service.shift_report_config import ( + load_shift_report_config, + load_shift_report_machines, +) CONFIG_PATH = Path(__file__).resolve().parents[1] / "config/shift-report-machines.yaml" -START, END = shift_report_window(date(2026, 10, 7), "early") +SHIFT_TIMEZONE = ZoneInfo("Europe/Berlin") +START, END = shift_report_window(date(2026, 10, 7), "early", SHIFT_TIMEZONE) class Stub: @@ -58,11 +66,12 @@ def composition(name="B1"): event = ClippedShiftDowntimeEvent(source, START, source.source_end, 100) downtime = ShiftDowntimeSummary(config.machine_id, START, END, 28800, 100, 28700, (event,), reasons) - channel = config.material.mode == "channel" + channel = config.material is not None and config.material.mode == "channel" item = ShiftMaterialItem( source="channel_material_consumption_snapshots" if channel else "material_consumption_snapshots", - calculation_id=config.material.calculation_ids[0], machine_id=config.machine_id, + calculation_id=config.material.calculation_ids[0] if config.material else "unused", + machine_id=config.machine_id, production_order="order", run_id="run", consumption_kg=42, baseline_timestamp=START, end_timestamp=END - timedelta(seconds=1), baseline_missing=False, extruder="Ex1" if channel else None, @@ -89,7 +98,8 @@ def test_machine_composition(name, workplace, mode, ids): service, stubs, calls, config = composition(name) report = service.build(machine_name=name, start=START, end=END) assert calls == [ - ("production", {"workplace": workplace, "start": START, "end": END}), + ("production", {"workplace": workplace, "start": START, "end": END, + "timezone": SHIFT_TIMEZONE}), ("downtime", {"machine_id": config.machine_id, "start": START, "end": END}), (mode, {"machine_id": config.machine_id, "calculation_ids": ids, "start": START, "end": END}), @@ -113,6 +123,172 @@ def test_machine_composition(name, workplace, mode, ids): report.machine_name = "other" +@pytest.mark.parametrize("name", ["Gitter 1", "Gitter 2", "Gitter 3", "Gitter 4", "K5"]) +def test_boolean_speed_machines_appear_in_report_without_material(name): + service, stubs, calls, config = composition(name) + report = service.build(machine_name=name, start=START, end=END) + assert [stage for stage, _ in calls] == ["production", "downtime", "speed"] + assert calls[-1][1]["config"] is config.speed + assert report.speed is stubs["speed"].result + assert report.materials is None + + +def test_sites_and_existing_machine_capabilities(): + config = load_shift_report_config(CONFIG_PATH) + assert {key: site.display_name for key, site in config.sites.items()} == { + "espelkamp": "Espelkamp", "adorf": "Adorf", "malaysia": "Malaysia", + } + assert set(config.machines) == { + "B1", "E1", "K7", "K3/4", "E4", "Gitter 1", "Gitter 2", + "Gitter 3", "Gitter 4", "K5", "Secumat 1/2", "Secumat 3", + "Bento 2", "K1", "K6", + } + assert all(config.machines[name].site == "espelkamp" for name in ("B1", "E1", "K7")) + assert all(vars_for_capabilities(machine) == (True, True, True, True) + for name, machine in config.machines.items() if name in ("B1", "E1", "K7")) + assert config.machines["K7"].material.allocation == "erp_fiber_share" + assert config.machines["B1"].material.allocation == "none" + assert config.sites["espelkamp"].timezone is SHIFT_TIMEZONE + assert config.sites["adorf"].timezone is SHIFT_TIMEZONE + assert config.sites["malaysia"].timezone.key == "Asia/Kuala_Lumpur" + assert all(config.machines[name].timezone is SHIFT_TIMEZONE + for name in ("B1", "E1", "K7")) + with pytest.raises(TypeError): + config.sites["new"] = config.sites["adorf"] + + +def vars_for_capabilities(machine): + value = machine.capabilities + return value.production, value.downtime, value.material, value.speed + + +def test_new_production_machines_have_valid_sites_and_capabilities(): + machines = load_shift_report_config(CONFIG_PATH).machines + expected = { + "K3/4": ("espelkamp", "K3/4", None), + "E4": ("espelkamp", "1568700", "646ebfa0-e97d-4970-b9f4-da94492aecc3"), + "Gitter 1": ("adorf", "GITTERANL", "35612735-03cc-4496-a72e-3c3e2216c720"), + "Gitter 2": ("adorf", "GITTER II", "5e89db10-ef0e-4224-866c-eee12bc3d27c"), + "Gitter 3": ("adorf", "GITTERIII", "ec3baac3-ccc1-4d1e-9b57-3f5ab2daa567"), + "Gitter 4": ("adorf", "GITTER IV", "ffa5de99-66a2-44bd-b039-9b4275bc5f9e"), + "K5": ("adorf", "K5", "8c094b9d-32d2-4ddf-b56a-2cd11a09eebf"), + "Secumat 1/2": ("adorf", "SECEXTRU", "16c0a111-3049-41d5-9e19-42ee0e047757"), + "Secumat 3": ("adorf", "SEC3", "0c207a7c-7813-4cff-90ba-6a0148919d38"), + "Bento 2": ("malaysia", "BENTO 2", "6201f3de-b940-45d7-930c-1481c5ae9e1d"), + "K1": ("malaysia", "K1", "40f1f58b-21fc-490a-8343-d1888938f11b"), + "K6": ("malaysia", "K6", "5e778f87-2d0f-47ac-a3ce-0c0dd9957918"), + } + assert len(machines) == 15 + assert set(machines) - {"B1", "E1", "K7"} == set(expected) + downtime_enabled = { + "E4", "Gitter 1", "Gitter 2", "Gitter 3", "Gitter 4", + "K5", "Secumat 1/2", "Secumat 3", + } + for name, (site, workplace, machine_id) in expected.items(): + machine = machines[name] + assert (machine.display_name, machine.site, machine.erp_workplace, + machine.machine_id) == (name, site, workplace, machine_id) + speed_enabled = name in {"Gitter 1", "Gitter 2", "Gitter 3", "Gitter 4", "K5"} + assert vars_for_capabilities(machine) == (True, name in downtime_enabled, False, + speed_enabled) + assert machine.material is None + assert (machine.speed is not None) == speed_enabled + assert machine.timezone.key == ("Asia/Kuala_Lumpur" if site == "malaysia" + else "Europe/Berlin") + ids = [machine.machine_id for machine in machines.values() if machine.machine_id] + assert len(ids) == len(set(ids)) == 14 + + +@pytest.mark.parametrize("downtime", [False, True]) +def test_partial_capabilities_skip_disabled_sources_and_render_unavailable( + downtime, +): + from dataclasses import replace + + from production_analytics.presentation.shift_report import TextBlock, present_report + from production_analytics.service.shift_report_config import ShiftReportCapabilities + + service, stubs, calls, config = composition() + partial = replace(config, + capabilities=ShiftReportCapabilities(True, downtime, False, False), + material=None, speed=None) + service.machines = {"Synthetic": partial} + report = service.build(machine_name="Synthetic", start=START, end=END) + expected = ["production", "downtime"] if downtime else ["production"] + assert [name for name, _ in calls] == expected + assert report.production is stubs["production"].result + assert report.downtime is (stubs["downtime"].result if downtime else None) + assert report.materials is None and report.speed is None + assert report.downtime_event_count == (1 if downtime else 0) + blocks = present_report(report) + unavailable = [b for b in blocks if isinstance(b, TextBlock) + and b.text == "Für diese Maschine nicht verfügbar."] + assert len(unavailable) == (2 if downtime else 3) + + +def test_downtime_only_machine_does_not_query_production(): + from dataclasses import replace + + from production_analytics.service.shift_report_config import ShiftReportCapabilities + + service, stubs, calls, config = composition() + service.machines = {"DowntimeOnly": replace( + config, capabilities=ShiftReportCapabilities(False, True, False, False), + material=None, speed=None, + )} + report = service.build(machine_name="DowntimeOnly", start=START, end=END) + assert [name for name, _ in calls] == ["downtime"] + assert report.production is None and report.downtime is stubs["downtime"].result + + +@pytest.mark.parametrize("explicit_null", [False, True]) +def test_production_only_machine_without_enlyze_id_loads_and_builds(tmp_path, explicit_null): + document = deepcopy(yaml.safe_load(CONFIG_PATH.read_text())) + document["machines"] = {"K3/4": { + "display_name": "K3/4", "site": "espelkamp", "erp_workplace": "K3/4", + "capabilities": {"production": True, "downtime": False, + "material": False, "speed": False}, + }} + if explicit_null: + document["machines"]["K3/4"]["machine_id"] = None + path = tmp_path / "machines.yaml" + path.write_text(yaml.safe_dump(document)) + machine = load_shift_report_config(path).machines["K3/4"] + assert machine.machine_id is None and machine.timezone is SHIFT_TIMEZONE + service, stubs, calls, _ = composition() + service.machines = {"K3/4": machine} + report = service.build(machine_name="K3/4", start=START, end=END) + assert report.machine_id is None and report.timezone is SHIFT_TIMEZONE + assert report.production is stubs["production"].result + assert report.downtime is report.materials is report.speed is None + assert [name for name, _ in calls] == ["production"] + + +def test_malaysia_report_carries_site_timezone_to_production_and_presentation(): + from dataclasses import replace + + from production_analytics.presentation.shift_report import TextBlock, present_report + from production_analytics.service.shift_report_config import ShiftReportCapabilities + + malaysia = ZoneInfo("Asia/Kuala_Lumpur") + service, _, calls, config = composition() + service.machines = {"Synthetic": replace( + config, site="malaysia", timezone=malaysia, machine_id=None, + capabilities=ShiftReportCapabilities(True, False, False, False), + material=None, speed=None, + )} + start, end = shift_report_window(date(2026, 10, 19), "late", malaysia) + report = service.build(machine_name="Synthetic", start=start.astimezone(UTC), + end=end.astimezone(UTC)) + assert report.timezone is malaysia + assert report.start == start and report.end == end + assert calls == [("production", {"workplace": config.erp_workplace, + "start": start, "end": end, "timezone": malaysia})] + texts = [block.text for block in present_report(report) if isinstance(block, TextBlock)] + assert "Zeitzone: Asia/Kuala_Lumpur" in texts + assert any("Schichtbeginn: 19.10.2026 14:00:00" in value for value in texts) + + def test_top_three_and_fallback_preserve_reason_metadata_and_order(): service, stubs, _, _ = composition() report = service.build(machine_name="B1", start=START, end=END) @@ -191,7 +367,7 @@ def test_utc_input_is_normalized_to_berlin_without_changing_instants(): ("early", (6, 14)), ("late", (14, 22)), ("night", (22, 6)), ]) def test_shift_windows(shift, hours): - start, end = shift_report_window(date(2026, 10, 7), shift) + start, end = shift_report_window(date(2026, 10, 7), shift, SHIFT_TIMEZONE) assert (start.hour, end.hour) == hours expected_end_day = date(2026, 10, 8) if shift == "night" else start.date() assert end.date() == expected_end_day @@ -200,10 +376,28 @@ def test_shift_windows(shift, hours): @pytest.mark.parametrize("day,hours", [(date(2026, 3, 28), 7), (date(2026, 10, 24), 9)]) def test_night_shift_dst_elapsed_duration(day, hours): - start, end = shift_report_window(day, "night") + start, end = shift_report_window(day, "night", SHIFT_TIMEZONE) assert (end.astimezone(UTC) - start.astimezone(UTC)).total_seconds() == hours * 3600 +@pytest.mark.parametrize("shift,start_hour,end_hour", [ + ("early", 6, 14), ("late", 14, 22), ("night", 22, 6), +]) +def test_malaysia_shift_windows_use_local_wall_clock(shift, start_hour, end_hour): + malaysia = ZoneInfo("Asia/Kuala_Lumpur") + start, end = shift_report_window(date(2026, 10, 19), shift, malaysia) + assert start.tzinfo is end.tzinfo is malaysia + assert (start.hour, end.hour) == (start_hour, end_hour) + assert (end.astimezone(UTC) - start.astimezone(UTC)).total_seconds() == 28800 + + +def test_same_instant_has_different_site_completed_shifts(): + now = datetime(2026, 10, 19, 11, tzinfo=UTC) + assert most_recent_completed_shift(now, SHIFT_TIMEZONE) == (date(2026, 10, 18), "night") + assert most_recent_completed_shift(now, ZoneInfo("Asia/Kuala_Lumpur")) == ( + date(2026, 10, 19), "early") + + @pytest.mark.parametrize("mutation", [ lambda d: d["machines"]["B1"].pop("erp_workplace"), lambda d: d["machines"]["B1"].update(unknown=True), @@ -221,6 +415,25 @@ def test_night_shift_dst_elapsed_duration(day, hours): lambda d: d["machines"]["E1"].update(machine_id=d["machines"]["B1"]["machine_id"]), lambda d: d["machines"]["B1"].update(erp_workplace=1568705), lambda d: d.update(extra=True), + lambda d: d["machines"]["B1"].update(site="unknown"), + lambda d: d["machines"]["B1"].update(site=[]), + lambda d: d["machines"]["B1"].pop("capabilities"), + lambda d: d["machines"]["B1"]["capabilities"].update(material=False), + lambda d: d["machines"]["B1"].pop("material"), + lambda d: d["machines"]["B1"]["capabilities"].update(speed=False), + lambda d: d["machines"]["B1"].pop("speed"), + lambda d: d["machines"]["B1"]["capabilities"].update(production="true"), + lambda d: d["machines"]["B1"].update(display_name=" "), + lambda d: d["sites"]["espelkamp"].update(display_name=""), + lambda d: d["sites"]["espelkamp"].update(extra=True), + lambda d: d["machines"]["B1"]["material"].update(allocation="unknown"), + lambda d: d["sites"]["malaysia"].update(timezone="Mars/Base"), + lambda d: d["sites"]["malaysia"].update(timezone=""), + lambda d: d["sites"]["malaysia"].pop("timezone"), + lambda d: d["machines"]["B1"].pop("machine_id"), + lambda d: d["machines"]["B1"].update(machine_id=None), + lambda d: d["machines"]["B1"]["capabilities"].update( + production=False, downtime=False, material=False, speed=False), ]) def test_strict_configuration(tmp_path, mutation): document = deepcopy(yaml.safe_load(CONFIG_PATH.read_text())) @@ -236,3 +449,38 @@ def test_duplicate_yaml_keys_rejected(tmp_path): path.write_text("machines: {}\nmachines: {}\n") with pytest.raises(ValueError, match="unique"): load_shift_report_machines(path) + + +def test_duplicate_site_key_rejected(tmp_path): + document = CONFIG_PATH.read_text().replace( + " adorf:\n display_name: Adorf", " espelkamp:\n display_name: Adorf" + ) + path = tmp_path / "machines.yaml" + path.write_text(document) + with pytest.raises(ValueError, match="unique"): + load_shift_report_config(path) + + +def test_duplicate_machine_key_rejected(tmp_path): + document = CONFIG_PATH.read_text().replace(" E1:\n", " B1:\n") + path = tmp_path / "machines.yaml" + path.write_text(document) + with pytest.raises(ValueError, match="unique"): + load_shift_report_config(path) + + +@pytest.mark.parametrize("capability", ["downtime", "material", "speed"]) +def test_machine_id_required_for_nonproduction_capabilities(tmp_path, capability): + document = deepcopy(yaml.safe_load(CONFIG_PATH.read_text())) + machine = document["machines"]["B1"] + machine["capabilities"] = {name: name == capability + for name in ("production", "downtime", "material", "speed")} + machine.pop("machine_id") + if capability != "material": + machine.pop("material") + if capability != "speed": + machine.pop("speed") + path = tmp_path / "machines.yaml" + path.write_text(yaml.safe_dump(document)) + with pytest.raises(ValueError): + load_shift_report_config(path) diff --git a/tests/test_shift_report_cli.py b/tests/test_shift_report_cli.py new file mode 100644 index 0000000..a7869ea --- /dev/null +++ b/tests/test_shift_report_cli.py @@ -0,0 +1,135 @@ +from dataclasses import replace +from pathlib import Path +from types import SimpleNamespace + +import pytest +from test_shift_report import END, START, composition + +from production_analytics.cli import __main__ as cli +from production_analytics.presentation import shift_report as presenter +from production_analytics.service import shift_report_runtime as runtime + + +def arguments(*extra): + return [ + "report", + "shift", + "--machine", + "E1", + "--start", + START.isoformat(), + "--end", + END.isoformat(), + "--output", + "/tmp/shift.pdf", + *extra, + ] + + +@pytest.mark.parametrize( + "extra,message", + [ + (["--machine", "UNKNOWN"], "Unknown shift-report machine"), + (["--start", "2026-10-07T06:00:00"], "timezone"), + (["--start", "invalid"], "Invalid isoformat"), + (["--end", START.isoformat()], "end must follow start"), + (["--end", "2026-10-06T06:00:00+02:00"], "end must follow start"), + ], +) +def test_validation_before_settings_or_source_access(monkeypatch, capsys, extra, message): + def unexpected(*args, **kwargs): + pytest.fail("Invalid arguments reached runtime setup") + + monkeypatch.setattr(cli, "_runtime_environment", unexpected) + assert cli.main(arguments(*extra)) == 2 + assert message in capsys.readouterr().err + + +def test_start_end_and_output_are_required(): + with pytest.raises(SystemExit) as caught: + cli.main(["report", "shift", "--machine", "E1"]) + assert caught.value.code == 2 + + +def test_cli_builds_one_report_and_passes_output(monkeypatch, capsys): + service, _, _, _ = composition("E1") + value = service.build(machine_name="E1", start=START, end=END) + calls = [] + + def environment(*paths): + calls.append(paths) + return {"settings": "supplied"} + + def build(machines, env): + assert set(machines) == { + "B1", "E1", "K7", "K3/4", "E4", "Gitter 1", "Gitter 2", + "Gitter 3", "Gitter 4", "K5", "Secumat 1/2", "Secumat 3", + "Bento 2", "K1", "K6", + } + assert env == {"settings": "supplied"} + + def report(**kwargs): + calls.append(kwargs) + return value + + return SimpleNamespace(build=report) + + monkeypatch.setattr(cli, "_runtime_environment", environment) + monkeypatch.setattr(runtime, "build_shift_report_service", build) + monkeypatch.setattr( + presenter, "write_pdf", lambda report, output: calls.append((report, output)) + ) + assert cli.main(arguments()) == 0 + assert calls == [ + (Path("secrets/enlyze.env"), Path("secrets/erp.env"), Path("secrets/postgres.env")), + {"machine_name": "E1", "start": START, "end": END}, + (value, Path("/tmp/shift.pdf")), + ] + assert capsys.readouterr().out.strip() == "/tmp/shift.pdf" + + +def test_runtime_wires_existing_readers_without_connecting(monkeypatch): + machines = composition("E1")[0].machines + tokens = {"postgres": object(), "erp": object(), "enlyze": object()} + for settings, token in ( + (runtime.PostgresSettings, tokens["postgres"]), + (runtime.ErpSettings, tokens["erp"]), + (runtime.ExplorationSettings, tokens["enlyze"]), + ): + monkeypatch.setattr(settings, "from_environment", lambda env, token=token: token) + service = runtime.build_shift_report_service(machines, {}) + assert service.production.gateway._settings is tokens["erp"] + assert service.downtime.repository.settings is tokens["postgres"] + assert service.materials.repository.settings is tokens["postgres"] + assert service.channel_materials.repository.settings is tokens["postgres"] + assert isinstance(service.speed.gateway, runtime.EnlyzeApiGateway) + assert set(service.material_allocators) == {"K7"} + + +def test_allocator_selection_uses_strategy_for_any_machine_name(monkeypatch): + machines = dict(composition("K7")[0].machines) + k7 = machines.pop("K7") + machines["OtherMachine"] = replace(k7, machine_id="other-id", speed=None, + capabilities=replace(k7.capabilities, speed=False)) + machines["B1"] = replace(machines["B1"], material=replace( + machines["B1"].material, allocation="none")) + for settings in (runtime.PostgresSettings, runtime.ErpSettings, + runtime.ExplorationSettings): + monkeypatch.setattr(settings, "from_environment", lambda env: object()) + service = runtime.build_shift_report_service(machines, {}) + assert set(service.material_allocators) == {"OtherMachine"} + assert isinstance(service.material_allocators["OtherMachine"], + runtime.K7FiberAllocationService) + + +def test_source_failure_is_safe_and_does_not_render(monkeypatch, capsys): + def fail(**kwargs): + raise RuntimeError("secret source details") + + monkeypatch.setattr(cli, "_runtime_environment", lambda *args: {}) + monkeypatch.setattr( + runtime, "build_shift_report_service", lambda *args: SimpleNamespace(build=fail) + ) + monkeypatch.setattr(presenter, "write_pdf", lambda *args: pytest.fail("Rendered failed read")) + assert cli.main(arguments()) == 1 + assert capsys.readouterr().err == "Report failed: RuntimeError\n" diff --git a/tests/test_shift_report_html.py b/tests/test_shift_report_html.py new file mode 100644 index 0000000..e9a93b7 --- /dev/null +++ b/tests/test_shift_report_html.py @@ -0,0 +1,92 @@ +from dataclasses import replace +from datetime import date, datetime +from html import escape +from zoneinfo import ZoneInfo + +import pytest +from test_shift_report_pdf import material_report + +from production_analytics.presentation.shift_report import MaterialPieBlock, present_report +from production_analytics.presentation.shift_report_html import render_page + +SHIFT_TIMEZONE = ZoneInfo("Europe/Berlin") + + +def page(value): + return render_page( + machines={value.machine_name: None}, + labels={"early": "Frühschicht"}, + day=date(2026, 10, 14), + shift="early", + machine=value.machine_name, + report=value, + generated_at=datetime.now(SHIFT_TIMEZONE), + error=None, + ) + + +def test_multiple_materials_chart_and_table(): + html = page(material_report((10, 30))) + assert '
    ' in html + assert 'Materialname' in html + assert "Material-0" in html and "30,00 kg" in html + + +def test_zero_entries_omitted_and_one_material_supported(): + value = material_report((0, 12, 0)) + html = page(value) + assert "Material-0" not in html and "Material-2" not in html + assert "Material-1: 12,00 kg (100,00 %)" in html + assert html.count("' not in html + assert "" not in html and "" not in html + assert escape(name + " (M0)") in html + assert escape(name + " (M1)") in html + assert "" + escape(name) + "" in html + + +@pytest.mark.parametrize("machine", ["B1", "E1", "K7"]) +def test_chart_uses_shared_consolidated_material_totals(machine): + value = material_report((10, 20, 30)) + items = tuple( + replace( + item, + material_name="Harz", + material_number="M1", + production_order=f"order-{index}", + erp_booking_share=0.5 if machine == "K7" else None, + ) + for index, item in enumerate(value.materials.items) + ) + value = replace(value, machine_name=machine, materials=replace(value.materials, items=items)) + html = page(value) + assert "Harz: 60,00 kg (100,00 %)" in html + assert html.count("order-{index}" in html + assert "ERP-Anteil" in html diff --git a/tests/test_shift_report_pdf.py b/tests/test_shift_report_pdf.py new file mode 100644 index 0000000..47fb92d --- /dev/null +++ b/tests/test_shift_report_pdf.py @@ -0,0 +1,326 @@ +from dataclasses import replace +from datetime import UTC, datetime + +import pytest +from test_shift_report import END, START, composition + +from production_analytics.presentation.shift_report import ( + MaterialPieBlock, + TableBlock, + TextBlock, + present_report, + render_pdf, + write_pdf, +) + + +def report(name="E1"): + service, _, _, _ = composition(name) + return service.build(machine_name=name, start=START, end=END) + + +def content(value): + return "\n".join( + block.text + if isinstance(block, TextBlock) + else "\n".join(" | ".join(row) for row in (block.headers, *block.rows)) + for block in present_report(value) + if isinstance(block, (TextBlock, TableBlock)) + ) + + +def test_stable_model_required_labels_and_supplied_quantities(): + value = report() + assert present_report(value) == present_report(value) + text = content(value) + for label in ( + "Schichtbericht", + "Maschine: E1", + "Schichtbeginn", + "Schichtende", + "Produktion", + "Produktionsauftrag", + "Artikelnummer", + "Artikelbeschreibung", + "Rollen gesamt: 1", + "Gesamtmenge: 123,00 m²", + "Stillstand gesamt", + "Zeit ohne erfassten Stillstand", + "Materialverbrauch", + "42,00 kg", + "Liniengeschwindigkeit im Lauf", + "order", + "article", + "description", + ): + assert label in text + assert "Produktionszeit" not in text + value = replace(value, speed=replace(value.speed, average_line_speed_m_min=12.345)) + assert "12,35 m/min" in content(value) + + +def test_top_three_preserve_order_and_durations(): + tables = [block for block in present_report(report()) if isinstance(block, TableBlock)] + reasons = next(block for block in tables if block.headers == ("Stillstandsgrund", "Dauer")) + assert reasons.rows == ( + ("Ohne Stillstandsgrund", "0 h 01 min 40,0 s"), + ("Stop", "0 h 01 min 30,0 s"), + ("Ohne Stillstandsgrund", "0 h 01 min 20,0 s"), + ) + assert "Other" not in content(report()) + + +def test_material_summary_names_numbers_and_unknown_label(): + value = report() + assert "Materialzuordnung fehlt" in content(value) + assert "Ex1" not in content(value) + item = replace(value.materials.items[0], material_number="M123", material_name="Harz & Öl") + text = content(replace(value, materials=replace(value.materials, items=(item,)))) + assert "M123" in text + assert "Harz & Öl" in text + + +def test_empty_sections_and_zero_totals(): + value = report() + value = replace( + value, + production=replace(value.production, items=(), total_produced_m2=0, total_roll_count=0), + downtime=replace(value.downtime, events=(), reasons=(), total_downtime_seconds=0), + materials=replace(value.materials, items=(), total_consumption_kg=0), + ) + text = content(value) + for message in ( + "Keine Produktionsdaten vorhanden.", + "Keine Stillstandsgründe vorhanden.", + "Keine Stillstandsereignisse vorhanden.", + "Keine Materialverbrauchsdaten vorhanden.", + "keine Laufdaten", + "Gesamtmenge: 0,00 m²", + "Rollen gesamt: 0", + ): + assert message in text + + +@pytest.mark.parametrize( + "start,end,expected", + [ + ( + datetime(2026, 1, 1, 5, tzinfo=UTC), + datetime(2026, 1, 1, 13, tzinfo=UTC), + ("01.01.2026 06:00:00 CET (+0100)", "01.01.2026 14:00:00 CET (+0100)"), + ), + ( + datetime(2026, 10, 25, 0, 30, tzinfo=UTC), + datetime(2026, 10, 25, 1, 30, tzinfo=UTC), + ("25.10.2026 02:30:00 CEST (+0200)", "25.10.2026 02:30:00 CET (+0100)"), + ), + ], +) +def test_berlin_display_including_dst_fold(start, end, expected): + text = content(replace(report(), start=start, end=end)) + assert all(timestamp in text for timestamp in expected) + + +def test_pdf_is_repeatable_a4_and_written_to_requested_path(tmp_path): + pytest.importorskip("reportlab") + value = report() + payload = render_pdf(value) + assert payload == render_pdf(value) + assert payload.startswith(b"%PDF-") + assert b"/MediaBox [ 0 0 595.2756 841.8898 ]" in payload + output = tmp_path / "nested" / "shift.pdf" + write_pdf(value, output) + assert output.read_bytes() == payload + + +def test_pdf_paginates_long_reports_and_escapes_source_markup(): + pytest.importorskip("reportlab") + value = report() + item = replace(value.production.items[0], article_description=" & description " * 5) + value = replace(value, production=replace(value.production, items=(item,) * 60)) + payload = render_pdf(value) + assert payload.count(b"/Type /Page\n") > 1 + + +@pytest.mark.parametrize("name", ["B1", "E1", "K7"]) +def test_every_machine_renders_supplied_values_without_correction(name): + value = report(name) + value = replace(value, production=replace(value.production, total_produced_m2=1234.56)) + text = content(value) + assert f"Maschine: {name}" in text + assert "Gesamtmenge: 1.234,56 m²" in text + assert "123,00 m²" in text + assert "Materialverbrauch gesamt: 42,00 kg" in text + + +def material_report(quantities): + value = report() + template = value.materials.items[0] + items = tuple( + replace( + template, + calculation_id=f"calculation-{index}", + doser_channel=f"C{index + 1}", + consumption_kg=quantity, + material_name=f"Material-{index}", + ) + for index, quantity in enumerate(quantities) + ) + return replace( + value, materials=replace(value.materials, items=items, total_consumption_kg=sum(quantities)) + ) + + +def test_material_zero_filter_preserves_report_and_total(): + value = material_report((0, 10, 0.001, -2)) + original = value.materials + text = content(value) + assert "Material-0" not in text + assert "Material-1" in text + assert "Material-2" in text # Exactly zero, not rounded-to-zero filtering. + assert "Material-3" in text + assert "Materialverbrauch gesamt: 8,00 kg" in text + assert value.materials is original + assert len(value.materials.items) == 4 + chart = next(block for block in present_report(value) if isinstance(block, MaterialPieBlock)) + assert chart.consumption_kg == (10, 0.001) + assert chart.labels == ("Material-1", "Material-2") + + +@pytest.mark.parametrize("quantities", [(), (0, 0), (0, 12)]) +def test_material_chart_requires_two_positive_items(quantities): + value = material_report(quantities) + assert not any(isinstance(block, MaterialPieBlock) for block in present_report(value)) + if not any(quantities): + assert "Keine Materialverbrauchsdaten vorhanden." in content(value) + assert not any( + isinstance(block, TableBlock) and block.headers[0] == "Materialname" + for block in present_report(value) + ) + assert render_pdf(value).startswith(b"%PDF-") + + +def test_material_chart_labels_and_repeatable_pdf(): + value = material_report((10, 20, 30, 40)) + items = list(value.materials.items) + items[0] = replace(items[0], material_name="Harz & Öl") + items[1] = replace(items[1], extruder=None, doser_channel=None, material_name="Polymer") + items[2] = replace( + items[2], extruder=None, doser_channel=None, material_number="M123", material_name=None + ) + items[3] = replace(items[3], extruder=None, doser_channel=None, material_name=None) + value = replace(value, materials=replace(value.materials, items=tuple(items))) + blocks = present_report(value) + chart = next(block for block in blocks if isinstance(block, MaterialPieBlock)) + assert chart.labels == ("Materialzuordnung fehlt", "M123", "Harz & Öl", "Polymer") + assert chart.consumption_kg == (40, 30, 10, 20) + assert blocks == present_report(value) + assert render_pdf(value) == render_pdf(value) + assert "Materialverbrauch gesamt: 100,00 kg" in content(value) + + +def test_material_chart_long_legend_paginates(): + value = material_report((1,) * 80) + items = tuple( + replace(item, material_name=f"{index:02d} " + "Long material name & resin " * 3) + for index, item in enumerate(value.materials.items) + ) + value = replace(value, materials=replace(value.materials, items=items)) + assert render_pdf(value).count(b"/Type /Page\n") > 1 + + +def material_table(value): + return next( + block + for block in present_report(value) + if isinstance(block, TableBlock) and block.headers[0] == "Materialname" + ) + + +def test_material_summary_combines_channels_unknowns_and_uses_same_pie_totals(): + value = material_report((10, 20, 5, 15, 30, 0)) + items = tuple( + replace( + item, + extruder="Ex1" if index % 2 else "Ex2", + doser_channel="C7", + material_name=("Resin" if index < 2 else "Additive" if index == 4 else None), + ) + for index, item in enumerate(value.materials.items) + ) + value = replace(value, materials=replace(value.materials, items=items)) + original = value.materials + assert material_table(value).rows == ( + ("Materialzuordnung fehlt", "–", "20,00 kg"), + ("Additive", "–", "30,00 kg"), + ("Resin", "–", "30,00 kg"), + ) + chart = next(block for block in present_report(value) if isinstance(block, MaterialPieBlock)) + assert chart.labels == ("Materialzuordnung fehlt", "Additive", "Resin") + assert chart.consumption_kg == (20, 30, 30) + assert sum(chart.consumption_kg) == value.materials.total_consumption_kg == 80 + assert "Materialverbrauch gesamt: 80,00 kg" in content(value) + assert value.materials is original + assert value.materials.items == items + assert "Ex1" not in content(value) and "C7" not in content(value) + reversed_value = replace( + value, materials=replace(value.materials, items=tuple(reversed(items))) + ) + assert present_report(value) == present_report(reversed_value) + assert render_pdf(value) == render_pdf(reversed_value) + + +def test_same_name_with_different_numbers_remains_distinct_and_legend_disambiguates(): + value = material_report((10, 20)) + items = tuple( + replace(item, material_name="Resin", material_number=f"M{index}") + for index, item in enumerate(value.materials.items) + ) + value = replace(value, materials=replace(value.materials, items=items)) + assert material_table(value).rows == (("Resin", "M0", "10,00 kg"), ("Resin", "M1", "20,00 kg")) + chart = next(block for block in present_report(value) if isinstance(block, MaterialPieBlock)) + assert chart.labels == ("Resin (M0)", "Resin (M1)") + + +def test_historical_e1_unknown_channels_become_single_material_category(): + from test_shift_material import aggregate, channel_sample + + deltas = ( + 0, + 4890.271, + 4890.271, + 1772.723, + 0, + 0, + 672.412, + 7596.677, + 822.973, + 2481.581, + 1266.113, + 0, + 0, + 493.784, + ) + rows = [ + channel_sample( + minute, counter, extruder=f"Ex{index // 7 + 1}", channel=f"C{index % 7 + 1}", name=None + ) + for index, delta in enumerate(deltas) + for minute, counter in ((-1, 5000), (479, 5000 + delta)) + ] + summary = aggregate(rows, channel=True) + value = replace(report(), materials=summary) + assert len(summary.items) == 14 + assert summary.total_consumption_kg == pytest.approx(24886.805) + assert material_table(value).rows == (("Materialzuordnung fehlt", "–", "24.886,81 kg"),) + assert not any(isinstance(block, MaterialPieBlock) for block in present_report(value)) + + +def test_same_known_material_across_channels_has_one_row_and_no_pie(): + value = material_report((10, 20, 0)) + items = tuple( + replace(item, material_name="Resin", material_number="M1") for item in value.materials.items + ) + value = replace(value, materials=replace(value.materials, items=items)) + assert material_table(value).rows == (("Resin", "M1", "30,00 kg"),) + assert not any(isinstance(block, MaterialPieBlock) for block in present_report(value)) diff --git a/tests/test_shift_report_web.py b/tests/test_shift_report_web.py new file mode 100644 index 0000000..cc5c744 --- /dev/null +++ b/tests/test_shift_report_web.py @@ -0,0 +1,255 @@ +from dataclasses import replace +from datetime import UTC, date, datetime +from types import SimpleNamespace +from urllib.parse import urlencode +from wsgiref.util import setup_testing_defaults +from zoneinfo import ZoneInfo + +import pytest +from test_shift_report_pdf import report + +from production_analytics import web +from production_analytics.calculations.shift_report import ( + most_recent_completed_shift, + shift_report_window, +) +from production_analytics.service.shift_report_config import ( + load_shift_report_config, + load_shift_report_machines, +) + +SHIFT_TIMEZONE = ZoneInfo("Europe/Berlin") + + +@pytest.mark.parametrize( + "hour,minute,day,shift", + [ + (5, 0, 13, "late"), + (6, 0, 13, "night"), + (10, 0, 13, "night"), + (14, 0, 14, "early"), + (15, 46, 14, "early"), + (21, 59, 14, "early"), + (22, 0, 14, "late"), + (23, 0, 14, "late"), + (0, 0, 13, "late"), + ], +) +def test_completed_shift(hour, minute, day, shift): + now = datetime(2026, 10, 14, hour, minute, tzinfo=SHIFT_TIMEZONE) + assert most_recent_completed_shift(now, SHIFT_TIMEZONE) == (date(2026, 10, day), shift) + start, end = shift_report_window(*most_recent_completed_shift(now, SHIFT_TIMEZONE), + SHIFT_TIMEZONE) + assert start.astimezone(UTC) < end.astimezone(UTC) <= now.astimezone(UTC) + + +@pytest.mark.parametrize("day,hours", [(date(2026, 3, 28), 7), (date(2026, 10, 24), 9)]) +def test_dst_night(day, hours): + start, end = shift_report_window(day, "night", SHIFT_TIMEZONE) + assert (end.astimezone(UTC) - start.astimezone(UTC)).total_seconds() == hours * 3600 + assert start.hour == 22 and end.hour == 6 + assert most_recent_completed_shift(end, SHIFT_TIMEZONE) == (day, "night") + # Both occurrences of the autumn fold remain inside the running night shift. + for fold in (0, 1): + now = end.replace(hour=2, fold=fold) + assert most_recent_completed_shift(now, SHIFT_TIMEZONE) == (day, "late") + + +def test_clock_requires_timezone_and_accepts_utc(): + with pytest.raises(ValueError): + most_recent_completed_shift(datetime(2026, 1, 1), SHIFT_TIMEZONE) + assert most_recent_completed_shift(datetime(2026, 10, 14, 12, tzinfo=UTC), + SHIFT_TIMEZONE) == ( + date(2026, 10, 14), + "early", + ) + + +def request(app, **params): + env = {} + setup_testing_defaults(env) + env["QUERY_STRING"] = urlencode(params) + response = [] + payload = b"".join(app(env, lambda status, headers: response.append((status, dict(headers))))) + return *response[0], payload + + +@pytest.fixture +def application(): + machines = load_shift_report_machines("config/shift-report-machines.yaml") + calls = [] + value = report() + + def build(**kwargs): + calls.append(kwargs) + return replace( + value, machine_name=kwargs["machine_name"], start=kwargs["start"], end=kwargs["end"] + ) + + app = web.create_app( + machines, + lambda: SimpleNamespace(build=build), + clock=lambda: datetime(2026, 10, 14, 15, 46, tzinfo=SHIFT_TIMEZONE), + ) + return app, calls + + +def test_default_and_render(application): + app, calls = application + status, headers, body = request(app) + assert status == "200 OK" + assert calls == [ + dict( + machine_name="B1", + start=shift_report_window(date(2026, 10, 14), "early", SHIFT_TIMEZONE)[0], + end=shift_report_window(date(2026, 10, 14), "early", SHIFT_TIMEZONE)[1], + ) + ] + text = body.decode() + for expected in ( + "123,00 m²", + "42,00 kg", + "description", + "Ohne Stillstandsgrund", + "Nicht verfügbar", + "Datenstand: 14.10.2026 15:46:00 CEST", + "Europe/Berlin", + "Als PDF exportieren", + ): + assert expected in text + assert headers["Cache-Control"] == "no-store" + + +def test_explicit_and_fresh_each_request(application): + app, calls = application + for _ in range(2): + assert request(app, date="2026-03-28", shift="night", machine="K7")[0] == "200 OK" + start, end = shift_report_window(date(2026, 3, 28), "night", SHIFT_TIMEZONE) + assert calls == [dict(machine_name="K7", start=start, end=end)] * 2 + + +@pytest.mark.parametrize( + "params", + [ + dict(machine="invalid"), + dict(shift="invalid"), + dict(date="bad"), + dict(date="9999-12-31", shift="night"), + ], +) +def test_invalid_selection(application, params): + app, calls = application + status, _, body = request(app, **params) + assert status == "400 Bad Request" + assert "Ungültige Auswahl" in body.decode() + assert not calls + + +def test_failure_safe(application): + machines = load_shift_report_machines("config/shift-report-machines.yaml") + + def fail(): + raise RuntimeError("password=secret database.internal") + + status, _, body = request(web.create_app(machines, fail)) + assert status == "503 Service Unavailable" + assert "konnte nicht erstellt werden" in body.decode() + assert b"secret" not in body and b"database.internal" not in body + + +def test_pdf_uses_one_fresh_service_model(application, monkeypatch): + app, calls = application + rendered = [] + + def pdf(value): + rendered.append(value) + return b"%PDF-fake" + + monkeypatch.setattr(web, "render_pdf", pdf) + status, headers, body = request( + app, date="2026-10-13", shift="night", machine="E1", format="pdf" + ) + assert status == "200 OK" and headers["Content-Type"] == "application/pdf" + assert body == b"%PDF-fake" + assert len(calls) == len(rendered) == 1 + assert rendered[0].machine_name == calls[0]["machine_name"] + assert (rendered[0].start, rendered[0].end) == shift_report_window( + date(2026, 10, 13), "night", SHIFT_TIMEZONE) + + +def test_source_markup_escaped(): + from production_analytics.presentation.shift_report_html import render_page + + value = report() + item = replace(value.production.items[0], article_description="") + value = replace(value, production=replace(value.production, items=(item,))) + page = render_page( + machines={"E1": None}, + labels=web.SHIFT_LABELS, + day=date(2026, 10, 14), + shift="early", + machine="E1", + report=value, + generated_at=datetime.now(SHIFT_TIMEZONE), + error=None, + ) + assert "