251 lines
13 KiB
Markdown
251 lines
13 KiB
Markdown
# Unified shift-report composition
|
||
|
||
`ShiftReportService` composes the existing production, downtime, material, and
|
||
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 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:
|
||
- bento1-fresh-bentonite-consumption
|
||
- bento1-spreader3-consumption
|
||
speed:
|
||
signal_ref: fef41976-1103-4090-b780-eaeecc02fdfa
|
||
signal: Transport Auszug Geschwindigkeit Istwert
|
||
unit: m/min
|
||
production_gate_m_min: 0.3
|
||
```
|
||
|
||
Every machine requires a display name, configured site, ERP workplace, and all four
|
||
boolean capability flags; at least one capability must be enabled. A machine ID is
|
||
required for downtime, material, or speed, but may be absent for production-only
|
||
machines. Material and speed configuration are required
|
||
exactly when their capability is enabled. Material modes remain `cumulative` and
|
||
`channel`; optional `allocation` is `none` (default) or `erp_fiber_share`. K7 selects
|
||
the latter through configuration. `load_shift_report_config()` exposes immutable
|
||
site and machine mappings; `load_shift_report_machines()` retains the machine-only
|
||
view used by historical reconciliation.
|
||
|
||
The loader returns `ShiftReportMachineConfig` values with frozen material and
|
||
speed configurations. Speed-only consumers now use `machines[name].speed`.
|
||
Missing/unknown fields, duplicate YAML keys or non-null machine IDs, invalid site
|
||
timezones, unsupported material
|
||
modes, empty/duplicate calculation IDs, and invalid speed metadata are rejected.
|
||
No unrelated YAML configuration is loaded at runtime.
|
||
|
||
Inject already constructed services:
|
||
|
||
```python
|
||
machines = load_shift_report_machines("config/shift-report-machines.yaml")
|
||
service = ShiftReportService(
|
||
machines=machines,
|
||
production=production_service,
|
||
downtime=downtime_service,
|
||
materials=material_service,
|
||
channel_materials=channel_material_service,
|
||
speed=speed_service,
|
||
)
|
||
start, end = shift_report_window(day, "early", machines["B1"].timezone)
|
||
report = service.build(machine_name="B1", start=start, end=end)
|
||
```
|
||
|
||
`shift_report_window` lives in `calculations.shift_report`; the loader and
|
||
service live in `service.shift_report_config` and `service.shift_report`.
|
||
The day is the shift's start date in the machine site's timezone. Early is 06:00–14:00, late is
|
||
14:00–22:00, and night is 22:00–06:00 on the following day. Night shifts can have
|
||
seven or nine elapsed hours at DST transitions. Explicit windows are validated
|
||
as aware, positive-duration instants and normalized to the site timezone for all service
|
||
calls. All source services retain their `[start, end)` semantics.
|
||
|
||
## Source semantics
|
||
|
||
Production uses the existing finished-goods ERP service with workplaces B1:
|
||
`BENTO 1`, E1: `1568705`, and K7: `K7`. Its order/article groups, m², roll counts,
|
||
and first/last confirmation timestamps remain available in `report.production`.
|
||
The ERP SQL query uses naive site-local `[start, end)` timestamps, and returned
|
||
confirmations are attached to the configured IANA timezone. Historical
|
||
reconciliation retains its Europe/Berlin default.
|
||
|
||
`report.downtime.non_downtime_seconds` is the elapsed shift duration minus the
|
||
union of downtime intervals. It is a time complement and does not measure actual
|
||
production time. It is never named `production_time_seconds`. The report exposes
|
||
`downtime_event_count`, all `downtime_reasons`, and `top_downtime_reasons` (at most
|
||
three). Reason views retain the original immutable reason, including duration
|
||
and metadata; null/blank names get `Ohne Stillstandsgrund`. The existing summary
|
||
provides ranking and tie ordering. Overlapping reasons can have durations whose
|
||
sum exceeds total downtime.
|
||
|
||
B1 uses cumulative fresh-bentonite and spreader3 snapshot streams; K7 uses the
|
||
cumulative fiber stream. E1 uses channel snapshots, preserving extruder/channel,
|
||
material number/name/status, calculation ID, and source in each item. Existing
|
||
counter differencing, reset failure behavior, and sample-to-sample attribution
|
||
remain unchanged. Null material names remain null; no carry-forward or report
|
||
label invents an identity. ERP raw-material booking quantities are excluded
|
||
because their timing is not synchronized with physical shift consumption.
|
||
|
||
Speed is the arithmetic sample mean strictly above the configured production
|
||
gate: average speed while running, not average speed over the full shift.
|
||
Counts, gate, and active min/max are preserved in `report.speed`.
|
||
|
||
Every enabled source is mandatory. Disabled sections are `None` in the report and
|
||
render as unavailable; no source is queried for them. Exceptions propagate
|
||
immediately and later services are not called. An empty successful summary remains
|
||
an empty summary; a failed
|
||
read is never replaced with zeros. No cross-source matching of runs or orders is
|
||
introduced, and sequential reads are not a transactionally consistent snapshot
|
||
across ERP, PostgreSQL, and ENLYZE.
|
||
|
||
## Generate an explicit shift PDF
|
||
|
||
Install the project with `pip install -e '.[dev]'`. Shift PDFs use the declared
|
||
`reportlab>=4.2,<5` dependency: a direct PDF writer without an external browser
|
||
or native HTML rendering stack. The older monthly energy report remains separate.
|
||
|
||
Run from the repository root, with access to the existing read-only sources:
|
||
|
||
```bash
|
||
production-analytics report shift --machine E1 \
|
||
--start '2026-10-07T06:00:00+02:00' \
|
||
--end '2026-10-07T14:00:00+02:00' \
|
||
--output data/reports/E1_2026-10-07_early.pdf
|
||
```
|
||
|
||
The PDF is written exactly to `--output`, relative to the working directory for
|
||
relative paths. Parent directories are created, and an existing file is replaced
|
||
only after rendering succeeds. No sidecar HTML is written. B1, E1, and K7 are
|
||
configured in `config/shift-report-machines.yaml`; override with `--config`.
|
||
Start and end are mandatory ISO 8601 timestamps with offsets (or `Z`); the end
|
||
must follow the start. There is no implicit current-shift selection.
|
||
|
||
Settings are read from the process environment, overlaid by these dotenv files:
|
||
|
||
- `secrets/enlyze.env` (`--secrets-file`): `ENLYZE_BASE_URL`, `ENLYZE_API_KEY`,
|
||
optional `ENLYZE_HTTP_TIMEOUT_SECONDS`.
|
||
- `secrets/erp.env` (`--erp-secrets-file`): `ERP_DB_HOST`, `ERP_DB_PORT`,
|
||
`ERP_DB_NAME`, `ERP_DB_USER`, `ERP_DB_PASSWORD`.
|
||
- `secrets/postgres.env` (`--db-secrets-file`): `POSTGRES_HOST`, `POSTGRES_PORT`,
|
||
`POSTGRES_DB`, `POSTGRES_USER`, `POSTGRES_PASSWORD`.
|
||
|
||
PostgreSQL must already contain the existing downtime and material snapshots;
|
||
this command performs no collection or polling. ERP supplies production and
|
||
ENLYZE supplies speed through the existing readers. Source failures fail the
|
||
command; empty successful summaries receive explicit German empty-state text.
|
||
Validation/configuration errors return exit code 2; other failures return 1.
|
||
|
||
The A4 slip includes production, supplied totals, downtime with the top three
|
||
reasons, material consumption including channel identities, and running speed.
|
||
Numbers use German separators with two decimal places. Durations retain hours,
|
||
minutes, and tenths of seconds. Times display the report site's timezone and
|
||
numeric offsets, including across daylight-saving transitions. Missing material
|
||
names are explicitly marked `Nicht verfügbar`; no identity is inferred. B1
|
||
source assignments are rendered unchanged, and energy is excluded.
|
||
|
||
`present_report(report)` returns an immutable, deterministic presentation model;
|
||
`render_pdf(report)` returns PDF bytes and `write_pdf(report, output)` writes them.
|
||
Only the supplied `ShiftReport` is consumed. Fixed ReportLab invariant metadata,
|
||
styles, fonts, and no generated-at clock make PDF bytes repeatable for the same
|
||
input and installed ReportLab version. Bytes are not promised identical across
|
||
library versions. Long reports paginate with repeated table headers and page
|
||
numbers. The domain report is also the input for the live web presenter.
|
||
|
||
|
||
## Live web interface
|
||
|
||
The website is the primary working interface; PDF is an export/archive artifact.
|
||
Run from the repository root:
|
||
|
||
```bash
|
||
.venv/bin/python -m production_analytics.web --port 8087
|
||
```
|
||
|
||
Open <http://127.0.0.1:8087/>. After installing the updated project, the equivalent
|
||
entry point is `production-analytics-web`. This lightweight standard-library WSGI
|
||
application uses no frontend framework. `--host` defaults to loopback; `--port`
|
||
defaults to `SHIFT_REPORT_PORT` or 8087. The bundled server is intended for local
|
||
use; a production deployment can serve `create_app(...)` with a WSGI server.
|
||
Machine configuration and secret-file options match the report CLI: `--config`,
|
||
`--secrets-file`, `--erp-secrets-file`, and `--db-secrets-file`.
|
||
|
||
The date is always the shift **start date**, including night shifts. The default
|
||
uses the selected machine site's local time and selects the most recent fully completed
|
||
shift: before 06:00 yesterday's late shift; from 06:00 yesterday's night shift;
|
||
from 14:00 today's early shift; from 22:00 today's late shift. At a boundary the
|
||
just-completed shift becomes the default. Night windows end on the following
|
||
calendar day; DST nights have seven or nine elapsed hours.
|
||
|
||
GET parameters are `date=YYYY-MM-DD`, `shift=early|late|night`, and `machine`
|
||
(configuration key). Omitted parameters use the default selection. Every request,
|
||
including reloads and `format=pdf`, constructs the existing source services and
|
||
calls `ShiftReportService.build` exactly once. No final report is persisted or
|
||
cached. Existing raw material snapshots remain source inputs. Responses use
|
||
`Cache-Control: no-store`.
|
||
|
||
HTML formats `present_report(report)` blocks shared with PDF, including the
|
||
existing material allocation explanation. `Als PDF exportieren` submits the
|
||
selected controls and passes that request's freshly built `ShiftReport` directly
|
||
to `render_pdf`. Export therefore reflects current data at export time; source
|
||
corrections between viewing and exporting may change the result. It never reuses
|
||
a stale stored report or runs a second fetch/calculation path. The HTML data-state
|
||
time is recorded after service generation, in the machine site's timezone, and makes no
|
||
completeness claim. Sources are still read sequentially, not transactionally.
|
||
|
||
Invalid selections return a German page-level error (HTTP 400). Source/settings
|
||
or rendering failures return a generic German error (HTTP 503), retaining the
|
||
selection controls without exposing exception text or credentials.
|
||
|
||
## Fertigungsauftrag search
|
||
|
||
The web UI links to `/orders?q=...` for a complete or partial FA number. Search
|
||
trims surrounding whitespace, rejects empty input, treats SQL wildcard characters
|
||
literally, and caps results at 25 distinct FAs. An exact match is listed first;
|
||
other results are ordered by FA. Repeated confirmation rows collapse into one FA
|
||
result, with separate workplace/article entries when needed. `/order?production_order=...`
|
||
shows the selected order and its affected shifts. Each shift links to the existing
|
||
live report URL with machine, shift start date and shift name.
|
||
|
||
The order view reads positive `Rückmeldemenge` rows from
|
||
`dbo.GRAFANA_PRODUCTION_CONFIRMATION`, matching the finished-production quantity
|
||
semantics of the shift report. The view's `Zeitstempel` is an ERP confirmation
|
||
timestamp; first and last timestamps do not describe uninterrupted machine runtime.
|
||
Each row is assigned to a configured machine by its exact `erp_workplace`, then
|
||
interpreted in that machine's site timezone. Local 22:00–05:59 belongs to the
|
||
night shift whose start date may be the previous day. Multiple rows for the same
|
||
FA, machine and shift sum their positive feedback m². Unknown or ambiguous
|
||
workplaces remain visible but cannot be assigned a configured shift.
|
||
|
||
The ERP gateway owns parameterized read-only SQL, the production-order service
|
||
owns mapping and shift grouping, and a dedicated presenter renders HTML. The
|
||
order/machine/shift model is the anchor for later order-specific KPI, roll/QS and
|
||
setup-sheet views; those data are not included yet. ERP timestamps are local
|
||
datetimes without offsets; autumn repeated-hour rows are interpreted as the
|
||
first occurrence, as in the existing confirmation gateway.
|