models.py

556 Zeilen · 26,3 KB · Python
Rohdatei
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
from datetime import date, datetime

from sqlalchemy import (Boolean, Date, DateTime, Float, ForeignKey, Integer, String, Text,
                        UniqueConstraint, func)
from sqlalchemy.orm import Mapped, mapped_column, relationship

from .db import Base

# Rollen: admin > leitung > mitarbeiter
ROLES = {
    "admin": "Administrator",
    "leitung": "Praxisleitung / QM",
    "mitarbeiter": "Mitarbeiter/in",
}
ROLE_RANK = {"mitarbeiter": 1, "leitung": 2, "admin": 3}

# Berechtigungen, die über gültige Qualifikationen vergeben werden
PERMISSIONS = {
    "steri_freigabe": "Steri-Chargen freigeben",
    "roentgen": "Röntgen technisch durchführen",
    "roentgen_fachkunde": "Röntgen anordnen / rechtfertigende Indikation",
    "geraete_einweisung": "Medizinprodukte bedienen (eingewiesen)",
}

INTERVAL_UNITS = {"tag": "Tag(e)", "woche": "Woche(n)", "monat": "Monat(e)", "jahr": "Jahr(e)"}

DEVICE_CATEGORIES = [
    "Sterilisator", "Thermodesinfektor", "Röntgen intraoral", "Röntgen OPG", "DVT",
    "Behandlungseinheit", "Kompressor", "Absauganlage", "Siegelgerät", "Ultraschallbad",
    "Polymerisationslampe", "Elektrogerät", "Notfallausrüstung", "Sonstiges",
]

DOC_CATEGORIES = [
    "Hygieneplan", "Arbeitsanweisung", "Betriebsanweisung", "Gefährdungsbeurteilung",
    "Hautschutzplan", "Notfallplan", "Formular", "Sonstiges",
]

STOCK_KINDS = {"zugang": "Zugang", "entnahme": "Entnahme", "korrektur": "Korrektur", "verfall": "Verfall/Entsorgung"}


class User(Base):
    __tablename__ = "users"
    id: Mapped[int] = mapped_column(primary_key=True)
    username: Mapped[str] = mapped_column(String(60), unique=True, index=True)
    full_name: Mapped[str] = mapped_column(String(120))
    email: Mapped[str | None] = mapped_column(String(200))
    job_title: Mapped[str | None] = mapped_column(String(80))
    role: Mapped[str] = mapped_column(String(20), default="mitarbeiter")
    password_hash: Mapped[str | None] = mapped_column(String(100))
    pin_hash: Mapped[str | None] = mapped_column(String(100))
    kiosk_visible: Mapped[bool] = mapped_column(Boolean, default=True)
    active: Mapped[bool] = mapped_column(Boolean, default=True)
    entry_date: Mapped[date | None] = mapped_column(Date)
    notes: Mapped[str | None] = mapped_column(Text)
    failed_logins: Mapped[int] = mapped_column(Integer, default=0)
    locked_until: Mapped[datetime | None] = mapped_column(DateTime)
    created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())
    # Zeiterfassung & Urlaub
    time_tracking: Mapped[bool] = mapped_column(Boolean, default=True)
    hr_access: Mapped[bool] = mapped_column(Boolean, default=False)  # sieht Zeiten/Urlaub aller
    weekly_hours: Mapped[float] = mapped_column(Float, default=40.0)
    work_days: Mapped[str] = mapped_column(String(20), default="1,2,3,4,5")  # ISO-Wochentage 1=Mo
    vacation_days: Mapped[float] = mapped_column(Float, default=28.0)
    tracking_start: Mapped[date | None] = mapped_column(Date)  # Saldo-Berechnung ab

    qualifications: Mapped[list["UserQualification"]] = relationship(
        back_populates="user", foreign_keys="UserQualification.user_id",
        order_by="UserQualification.acquired_on.desc()")

    @property
    def role_label(self) -> str:
        return ROLES.get(self.role, self.role)

    @property
    def work_day_set(self) -> set[int]:
        return {int(d) for d in (self.work_days or "").split(",") if d.strip().isdigit()}

    @property
    def work_days_label(self) -> str:
        names = ["Mo", "Di", "Mi", "Do", "Fr", "Sa", "So"]
        return ", ".join(names[d - 1] for d in sorted(self.work_day_set) if 1 <= d <= 7)

    @property
    def daily_target_min(self) -> int:
        n = len(self.work_day_set)
        return round((self.weekly_hours or 0) * 60 / n) if n else 0

    @property
    def initials(self) -> str:
        parts = [p for p in self.full_name.replace("-", " ").split() if p]
        return "".join(p[0] for p in parts[:2]).upper() or self.username[:2].upper()


class QualificationType(Base):
    __tablename__ = "qualification_types"
    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str] = mapped_column(String(150), unique=True)
    description: Mapped[str | None] = mapped_column(Text)
    validity_months: Mapped[int | None] = mapped_column(Integer)  # None = unbefristet
    warn_days: Mapped[int] = mapped_column(Integer, default=60)
    permissions: Mapped[str] = mapped_column(String(300), default="")  # vergibt Berechtigung (kommagetrennt)
    # zusätzlich zwingend nötig für diese Berechtigungen (z. B. jährliche Unterweisung Strahlenschutz)
    prerequisite_for: Mapped[str] = mapped_column(String(300), default="")
    required_for_all: Mapped[bool] = mapped_column(Boolean, default=False)
    is_instruction: Mapped[bool] = mapped_column(Boolean, default=False)  # Unterweisung statt Zertifikat
    active: Mapped[bool] = mapped_column(Boolean, default=True)

    @property
    def permission_list(self) -> list[str]:
        return [p for p in (self.permissions or "").split(",") if p]

    @property
    def prerequisite_list(self) -> list[str]:
        return [p for p in (self.prerequisite_for or "").split(",") if p]


class UserQualification(Base):
    __tablename__ = "user_qualifications"
    id: Mapped[int] = mapped_column(primary_key=True)
    user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True)
    type_id: Mapped[int] = mapped_column(ForeignKey("qualification_types.id"), index=True)
    acquired_on: Mapped[date] = mapped_column(Date)
    valid_until: Mapped[date | None] = mapped_column(Date)
    note: Mapped[str | None] = mapped_column(Text)
    file_path: Mapped[str | None] = mapped_column(String(300))
    file_name: Mapped[str | None] = mapped_column(String(200))
    created_by_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"))
    created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())

    user: Mapped[User] = relationship(back_populates="qualifications", foreign_keys=[user_id])
    type: Mapped[QualificationType] = relationship()


class Device(Base):
    __tablename__ = "devices"
    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str] = mapped_column(String(150))
    category: Mapped[str] = mapped_column(String(60))
    manufacturer: Mapped[str | None] = mapped_column(String(100))
    model: Mapped[str | None] = mapped_column(String(100))
    serial_no: Mapped[str | None] = mapped_column(String(100))
    inventory_no: Mapped[str | None] = mapped_column(String(60))
    location: Mapped[str | None] = mapped_column(String(100))
    purchase_date: Mapped[date | None] = mapped_column(Date)
    is_steri: Mapped[bool] = mapped_column(Boolean, default=False)  # erzeugt Chargen
    programs: Mapped[str | None] = mapped_column(Text)  # eine Zeile pro Programm
    required_permission: Mapped[str | None] = mapped_column(String(40))
    active: Mapped[bool] = mapped_column(Boolean, default=True)
    notes: Mapped[str | None] = mapped_column(Text)
    # Temperaturüberwachung (z. B. Impfstoff-Kühlschrank): beide gesetzt = Messstelle
    temp_min: Mapped[float | None] = mapped_column(Float)
    temp_max: Mapped[float | None] = mapped_column(Float)

    tasks: Mapped[list["Task"]] = relationship(back_populates="device", order_by="Task.next_due")

    @property
    def is_temp_point(self) -> bool:
        return self.temp_min is not None and self.temp_max is not None

    @property
    def program_list(self) -> list[str]:
        return [p.strip() for p in (self.programs or "").splitlines() if p.strip()]


class Task(Base):
    """Wiederkehrende Prüfung / Wartung / Routine (mit oder ohne Gerät)."""
    __tablename__ = "tasks"
    id: Mapped[int] = mapped_column(primary_key=True)
    device_id: Mapped[int | None] = mapped_column(ForeignKey("devices.id"), index=True)
    title: Mapped[str] = mapped_column(String(200))
    description: Mapped[str | None] = mapped_column(Text)
    interval_value: Mapped[int] = mapped_column(Integer, default=1)
    interval_unit: Mapped[str] = mapped_column(String(10), default="jahr")
    external: Mapped[bool] = mapped_column(Boolean, default=False)  # durch Fremdfirma/Sachverständige
    responsible_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"))
    warn_days: Mapped[int] = mapped_column(Integer, default=14)
    next_due: Mapped[date] = mapped_column(Date)
    last_done: Mapped[date | None] = mapped_column(Date)
    active: Mapped[bool] = mapped_column(Boolean, default=True)

    device: Mapped[Device | None] = relationship(back_populates="tasks")
    responsible: Mapped[User | None] = relationship()
    records: Mapped[list["TaskRecord"]] = relationship(back_populates="task", order_by="TaskRecord.done_on.desc()")

    @property
    def interval_label(self) -> str:
        return f"alle {self.interval_value} {INTERVAL_UNITS.get(self.interval_unit, self.interval_unit)}"


class TaskRecord(Base):
    __tablename__ = "task_records"
    id: Mapped[int] = mapped_column(primary_key=True)
    task_id: Mapped[int] = mapped_column(ForeignKey("tasks.id"), index=True)
    done_on: Mapped[date] = mapped_column(Date)
    done_by_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"))
    provider: Mapped[str | None] = mapped_column(String(150))
    result: Mapped[str] = mapped_column(String(20), default="ok")  # ok | maengel | nicht_ok
    note: Mapped[str | None] = mapped_column(Text)
    file_path: Mapped[str | None] = mapped_column(String(300))
    file_name: Mapped[str | None] = mapped_column(String(200))
    created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())

    task: Mapped[Task] = relationship(back_populates="records")
    done_by: Mapped[User | None] = relationship()


class SteriBatch(Base):
    __tablename__ = "steri_batches"
    id: Mapped[int] = mapped_column(primary_key=True)
    batch_no: Mapped[str] = mapped_column(String(40), unique=True, index=True)
    device_id: Mapped[int] = mapped_column(ForeignKey("devices.id"))
    program: Mapped[str | None] = mapped_column(String(150))
    cycle_no: Mapped[str | None] = mapped_column(String(40))
    started_at: Mapped[datetime] = mapped_column(DateTime)
    operator_id: Mapped[int] = mapped_column(ForeignKey("users.id"))
    load_description: Mapped[str | None] = mapped_column(Text)
    packaged: Mapped[bool] = mapped_column(Boolean, default=True)
    expiry_date: Mapped[date | None] = mapped_column(Date)
    chk_process: Mapped[bool | None] = mapped_column(Boolean)
    chk_indicator: Mapped[bool | None] = mapped_column(Boolean)
    chk_packaging: Mapped[bool | None] = mapped_column(Boolean)
    chk_dry: Mapped[bool | None] = mapped_column(Boolean)
    status: Mapped[str] = mapped_column(String(20), default="offen")  # offen | freigegeben | gesperrt
    released_by_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"))
    released_at: Mapped[datetime | None] = mapped_column(DateTime)
    release_note: Mapped[str | None] = mapped_column(Text)
    file_path: Mapped[str | None] = mapped_column(String(300))
    file_name: Mapped[str | None] = mapped_column(String(200))
    created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())

    device: Mapped[Device] = relationship()
    operator: Mapped[User] = relationship(foreign_keys=[operator_id])
    released_by: Mapped[User | None] = relationship(foreign_keys=[released_by_id])
    corrections: Mapped[list["SteriCorrection"]] = relationship(
        back_populates="batch", order_by="SteriCorrection.created_at")


class SteriCorrection(Base):
    """Nachträge zu abgeschlossenen Chargen – das Original bleibt unverändert."""
    __tablename__ = "steri_corrections"
    id: Mapped[int] = mapped_column(primary_key=True)
    batch_id: Mapped[int] = mapped_column(ForeignKey("steri_batches.id"), index=True)
    user_id: Mapped[int] = mapped_column(ForeignKey("users.id"))
    created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())
    text: Mapped[str] = mapped_column(Text)

    batch: Mapped[SteriBatch] = relationship(back_populates="corrections")
    user: Mapped[User] = relationship()


class Article(Base):
    __tablename__ = "articles"
    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str] = mapped_column(String(200))
    article_no: Mapped[str | None] = mapped_column(String(80))
    barcode: Mapped[str | None] = mapped_column(String(120), index=True)
    supplier: Mapped[str | None] = mapped_column(String(120))
    category: Mapped[str | None] = mapped_column(String(80))
    unit: Mapped[str] = mapped_column(String(30), default="Stück")
    min_stock: Mapped[float] = mapped_column(Float, default=0)
    order_qty: Mapped[float | None] = mapped_column(Float)
    location: Mapped[str | None] = mapped_column(String(100))
    track_lots: Mapped[bool] = mapped_column(Boolean, default=False)
    ordered_on: Mapped[date | None] = mapped_column(Date)
    active: Mapped[bool] = mapped_column(Boolean, default=True)
    notes: Mapped[str | None] = mapped_column(Text)

    lots: Mapped[list["StockLot"]] = relationship(back_populates="article", order_by="StockLot.expiry")

    @property
    def stock(self) -> float:
        return round(sum(l.quantity for l in self.lots), 3)


class StockLot(Base):
    __tablename__ = "stock_lots"
    id: Mapped[int] = mapped_column(primary_key=True)
    article_id: Mapped[int] = mapped_column(ForeignKey("articles.id"), index=True)
    lot_no: Mapped[str | None] = mapped_column(String(80))
    expiry: Mapped[date | None] = mapped_column(Date)
    quantity: Mapped[float] = mapped_column(Float, default=0)

    article: Mapped[Article] = relationship(back_populates="lots")


class StockMovement(Base):
    __tablename__ = "stock_movements"
    id: Mapped[int] = mapped_column(primary_key=True)
    article_id: Mapped[int] = mapped_column(ForeignKey("articles.id"), index=True)
    lot_id: Mapped[int | None] = mapped_column(ForeignKey("stock_lots.id"))
    delta: Mapped[float] = mapped_column(Float)
    kind: Mapped[str] = mapped_column(String(20))
    user_id: Mapped[int] = mapped_column(ForeignKey("users.id"))
    note: Mapped[str | None] = mapped_column(String(300))
    created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())

    article: Mapped[Article] = relationship()
    lot: Mapped[StockLot | None] = relationship()
    user: Mapped[User] = relationship()


class Document(Base):
    __tablename__ = "documents"
    id: Mapped[int] = mapped_column(primary_key=True)
    title: Mapped[str] = mapped_column(String(200))
    category: Mapped[str] = mapped_column(String(60))
    description: Mapped[str | None] = mapped_column(Text)
    requires_ack: Mapped[bool] = mapped_column(Boolean, default=True)
    review_months: Mapped[int | None] = mapped_column(Integer, default=12)
    owner_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"))
    active: Mapped[bool] = mapped_column(Boolean, default=True)
    created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())

    owner: Mapped[User | None] = relationship()
    versions: Mapped[list["DocumentVersion"]] = relationship(
        back_populates="document", order_by="DocumentVersion.version_no.desc()")

    @property
    def current(self) -> "DocumentVersion | None":
        return self.versions[0] if self.versions else None


class DocumentVersion(Base):
    __tablename__ = "document_versions"
    __table_args__ = (UniqueConstraint("document_id", "version_no"),)
    id: Mapped[int] = mapped_column(primary_key=True)
    document_id: Mapped[int] = mapped_column(ForeignKey("documents.id"), index=True)
    version_no: Mapped[int] = mapped_column(Integer)
    valid_from: Mapped[date] = mapped_column(Date)
    change_note: Mapped[str | None] = mapped_column(Text)
    content: Mapped[str | None] = mapped_column(Text)  # Text direkt in der App (Markdown)
    pdf_path: Mapped[str | None] = mapped_column(String(300))  # automatisch erzeugtes PDF einer Office-Datei
    # Volltext für die Suche (nur bei Bedarf geladen); search_norm NULL = noch nicht erfasst
    plain_text: Mapped[str | None] = mapped_column(Text, deferred=True)
    search_norm: Mapped[str | None] = mapped_column(Text, deferred=True)
    file_path: Mapped[str | None] = mapped_column(String(300))
    file_name: Mapped[str | None] = mapped_column(String(200))
    created_by_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"))
    created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())

    document: Mapped[Document] = relationship(back_populates="versions")
    created_by: Mapped[User | None] = relationship()
    acks: Mapped[list["DocumentAck"]] = relationship(back_populates="version")


class DocumentAck(Base):
    __tablename__ = "document_acks"
    __table_args__ = (UniqueConstraint("version_id", "user_id"),)
    id: Mapped[int] = mapped_column(primary_key=True)
    version_id: Mapped[int] = mapped_column(ForeignKey("document_versions.id"), index=True)
    user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True)
    acked_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())

    version: Mapped[DocumentVersion] = relationship(back_populates="acks")
    user: Mapped[User] = relationship()


class KioskDevice(Base):
    """Als Tablet/Kiosk freigeschaltetes Endgerät (PIN-Login nur dort möglich)."""
    __tablename__ = "kiosk_devices"
    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str] = mapped_column(String(100))
    token_hash: Mapped[str] = mapped_column(String(100), unique=True)
    created_by_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"))
    created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())
    last_seen: Mapped[datetime | None] = mapped_column(DateTime)
    active: Mapped[bool] = mapped_column(Boolean, default=True)


class AuditLog(Base):
    """Nur anhängen – Änderungen/Löschungen werden per DB-Trigger verhindert."""
    __tablename__ = "audit_log"
    id: Mapped[int] = mapped_column(primary_key=True)
    ts: Mapped[datetime] = mapped_column(DateTime, server_default=func.now(), index=True)
    user_id: Mapped[int | None] = mapped_column(Integer)
    username: Mapped[str | None] = mapped_column(String(60))
    action: Mapped[str] = mapped_column(String(60))
    entity: Mapped[str | None] = mapped_column(String(40))
    entity_id: Mapped[int | None] = mapped_column(Integer)
    details: Mapped[str | None] = mapped_column(Text)


class KV(Base):
    __tablename__ = "kv"
    key: Mapped[str] = mapped_column(String(60), primary_key=True)
    value: Mapped[str | None] = mapped_column(Text)


# ---------- Zeiterfassung ----------

class TimeEntry(Base):
    """Ein Arbeitsblock (Kommen bis Gehen). Pausen in TimeBreak oder als Minuten-Korrektur."""
    __tablename__ = "time_entries"
    id: Mapped[int] = mapped_column(primary_key=True)
    user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True)
    day: Mapped[date] = mapped_column(Date, index=True)
    start: Mapped[datetime] = mapped_column(DateTime)
    end: Mapped[datetime | None] = mapped_column(DateTime)
    break_minutes_manual: Mapped[int | None] = mapped_column(Integer)  # überschreibt erfasste Pausen
    source: Mapped[str] = mapped_column(String(20), default="stempel")  # auto | stempel | manuell | korrigiert
    note: Mapped[str | None] = mapped_column(Text)
    created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())
    updated_by_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"))

    user: Mapped[User] = relationship(foreign_keys=[user_id])
    breaks: Mapped[list["TimeBreak"]] = relationship(back_populates="entry", order_by="TimeBreak.start",
                                                     cascade="all, delete-orphan")

    @property
    def open_break(self) -> "TimeBreak | None":
        return next((b for b in self.breaks if b.end is None), None)

    def break_minutes(self, now: datetime | None = None) -> int:
        if self.break_minutes_manual is not None:
            return self.break_minutes_manual
        now = now or datetime.now()
        return int(sum(((b.end or now) - b.start).total_seconds() for b in self.breaks) // 60)

    def gross_minutes(self, now: datetime | None = None) -> int:
        end = self.end or now or datetime.now()
        return max(0, int((end - self.start).total_seconds() // 60))

    def net_minutes(self, now: datetime | None = None) -> int:
        return max(0, self.gross_minutes(now) - self.break_minutes(now))


class TimeBreak(Base):
    __tablename__ = "time_breaks"
    id: Mapped[int] = mapped_column(primary_key=True)
    entry_id: Mapped[int] = mapped_column(ForeignKey("time_entries.id"), index=True)
    start: Mapped[datetime] = mapped_column(DateTime)
    end: Mapped[datetime | None] = mapped_column(DateTime)

    entry: Mapped[TimeEntry] = relationship(back_populates="breaks")


# ---------- Urlaub & Abwesenheit ----------

ABSENCE_KINDS = {
    "urlaub": "Urlaub",
    "ueberstunden": "Überstundenabbau",
    "fortbildung": "Fortbildung",
    "krank": "Krank",
    "kind_krank": "Kind krank",
    "sonstiges": "Sonstige Abwesenheit",
}
# Diese Arten gelten als Soll erfüllt (kein Minus auf dem Zeitkonto)
ABSENCE_CREDITED = {"urlaub", "fortbildung", "krank", "kind_krank", "sonstiges"}
# Diese Arten sehen nur Personalverantwortliche und die Person selbst im Detail
ABSENCE_PRIVATE = {"krank", "kind_krank"}
ABSENCE_STATUS = {"beantragt": "beantragt", "genehmigt": "genehmigt", "abgelehnt": "abgelehnt",
                  "storniert": "storniert"}


class Absence(Base):
    __tablename__ = "absences"
    id: Mapped[int] = mapped_column(primary_key=True)
    user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True)
    kind: Mapped[str] = mapped_column(String(20), default="urlaub")
    start: Mapped[date] = mapped_column(Date, index=True)
    end: Mapped[date] = mapped_column(Date, index=True)
    half_day: Mapped[bool] = mapped_column(Boolean, default=False)
    status: Mapped[str] = mapped_column(String(20), default="beantragt")
    note: Mapped[str | None] = mapped_column(Text)
    created_by_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"))
    created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())
    decided_by_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"))
    decided_at: Mapped[datetime | None] = mapped_column(DateTime)
    decision_note: Mapped[str | None] = mapped_column(Text)

    user: Mapped[User] = relationship(foreign_keys=[user_id])
    decided_by: Mapped[User | None] = relationship(foreign_keys=[decided_by_id])

    @property
    def kind_label(self) -> str:
        return ABSENCE_KINDS.get(self.kind, self.kind)


class LeaveYear(Base):
    """Urlaubskonto pro Person und Jahr (Anspruch + Übertrag aus Vorjahr)."""
    __tablename__ = "leave_years"
    __table_args__ = (UniqueConstraint("user_id", "year"),)
    id: Mapped[int] = mapped_column(primary_key=True)
    user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True)
    year: Mapped[int] = mapped_column(Integer)
    entitlement: Mapped[float] = mapped_column(Float)
    carryover: Mapped[float] = mapped_column(Float, default=0)
    note: Mapped[str | None] = mapped_column(String(200))


class ClosureDay(Base):
    """Zusätzliche praxisfreie Tage (z. B. Heiligabend, Silvester) – kein Soll."""
    __tablename__ = "closure_days"
    id: Mapped[int] = mapped_column(primary_key=True)
    day: Mapped[date] = mapped_column(Date, unique=True)
    name: Mapped[str] = mapped_column(String(100))


class ImportItem(Base):
    """Zwischenstand beim QM-Sammelimport (hochgeladen, noch nicht übernommen)."""
    __tablename__ = "import_items"
    id: Mapped[int] = mapped_column(primary_key=True)
    batch: Mapped[str] = mapped_column(String(40), index=True)
    rel_path: Mapped[str] = mapped_column(String(500))  # Pfad auf dem Stick / im Ordner
    file_path: Mapped[str] = mapped_column(String(300))  # gespeicherte Datei
    file_name: Mapped[str] = mapped_column(String(200))
    size: Mapped[int] = mapped_column(Integer, default=0)
    modified: Mapped[date | None] = mapped_column(Date)
    created_by_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"))
    created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())


# ---------- Netfilter (IP-Sperren) ----------

class NetBan(Base):
    """Gesperrtes Netz (einzelne IP als /32 bzw. /128 oder größeres Netz). until=None: dauerhaft."""
    __tablename__ = "netfilter_bans"
    id: Mapped[int] = mapped_column(primary_key=True)
    network: Mapped[str] = mapped_column(String(50), unique=True)
    reason: Mapped[str | None] = mapped_column(String(200))
    created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())
    banned_at: Mapped[datetime] = mapped_column(DateTime)
    until: Mapped[datetime | None] = mapped_column(DateTime)
    ban_count: Mapped[int] = mapped_column(Integer, default=1)  # für steigende Sperrdauer
    manual: Mapped[bool] = mapped_column(Boolean, default=False)


class NetFail(Base):
    """Fehlversuch einer IP (Login, PIN, Scanner-Pfad …) – Grundlage für automatische Sperren."""
    __tablename__ = "netfilter_fails"
    id: Mapped[int] = mapped_column(primary_key=True)
    ts: Mapped[datetime] = mapped_column(DateTime, index=True)
    ip: Mapped[str] = mapped_column(String(45), index=True)
    kind: Mapped[str] = mapped_column(String(30))
    detail: Mapped[str | None] = mapped_column(String(150))


# ---------- Temperaturprotokoll ----------

class TempReading(Base):
    """Temperaturmessung an einer Messstelle (Gerät mit Sollbereich). Nur anhängen, nicht ändern."""
    __tablename__ = "temp_readings"
    id: Mapped[int] = mapped_column(primary_key=True)
    device_id: Mapped[int] = mapped_column(ForeignKey("devices.id"), index=True)
    ts: Mapped[datetime] = mapped_column(DateTime, index=True)  # Zeitpunkt der Ablesung
    current: Mapped[float] = mapped_column(Float)
    min_value: Mapped[float | None] = mapped_column(Float)  # Min/Max-Thermometer seit letztem Reset
    max_value: Mapped[float | None] = mapped_column(Float)
    in_range: Mapped[bool] = mapped_column(Boolean, default=True)
    action: Mapped[str | None] = mapped_column(Text)  # Maßnahme bei Abweichung
    note: Mapped[str | None] = mapped_column(String(300))
    user_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"))
    created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())

    device: Mapped[Device] = relationship()
    user: Mapped[User | None] = relationship()