import secrets from app import db from app.utils.time_utils import now_eastern class Facility(db.Model): __tablename__ = 'facilities' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) address = db.Column(db.Text) contact_person = db.Column(db.String(100)) contact_phone = db.Column(db.String(20)) active = db.Column(db.Boolean, default=True) created_at = db.Column(db.DateTime, default=now_eastern, nullable=True) # Phase 1: link facility to a project (nullable for backward compatibility) project_id = db.Column(db.Integer, db.ForeignKey('projects.id', ondelete='SET NULL'), nullable=True, index=True) # Phase 34: unguessable token encoded in the facility's public QR code. # The QR points at /f/, a login-free occupant summary page. # Backfilled for existing rows by phase34; set at creation for new rows. public_token = db.Column(db.String(48), nullable=True, unique=True, index=True) # Relationships areas = db.relationship('Area', backref='facility', lazy='dynamic') inspections = db.relationship('Inspection', backref='facility', lazy='dynamic') @staticmethod def generate_public_token() -> str: """Return a fresh URL-safe token for the public QR link.""" return secrets.token_urlsafe(24) def ensure_public_token(self) -> str: """Return this facility's public_token, generating & persisting one if it is missing (e.g. a row created before phase34 ran). The caller is responsible for db.session.commit().""" if not self.public_token: self.public_token = self.generate_public_token() return self.public_token def __repr__(self): return f'' class Area(db.Model): __tablename__ = 'areas' id = db.Column(db.Integer, primary_key=True) facility_id = db.Column(db.Integer, db.ForeignKey('facilities.id'), nullable=False) name = db.Column(db.String(255), nullable=False) area_type = db.Column(db.String(50)) # Phase 39: unguessable token encoded in the area's public QR code. # The QR points at /f/area/, a login-free occupant summary # page scoped to this area. Backfilled for existing rows by phase39. public_token = db.Column(db.String(48), nullable=True, unique=True, index=True) # Relationships inspections = db.relationship('Inspection', backref='area', lazy='dynamic') issues = db.relationship('Issue', backref='area', lazy='dynamic') @staticmethod def generate_public_token() -> str: """Return a fresh URL-safe token for the public QR link.""" return secrets.token_urlsafe(24) def ensure_public_token(self) -> str: """Return this area's public_token, generating & persisting one if it is missing. The caller is responsible for db.session.commit().""" if not self.public_token: self.public_token = self.generate_public_token() return self.public_token def __repr__(self): return f''