Buildings and levels for the floor map, and make every identifier searchable

This commit is contained in:
2026-08-17 13:03:54 -04:00
parent 47fb65fdd2
commit fbd99041b0
54 changed files with 4173 additions and 880 deletions

View File

@@ -8,6 +8,8 @@ from .model import Model
from .businessunit import BusinessUnit
from .dashboarddefault import DashboardDefault
from .location import Location, LocationType, derive_locationcode
from .maplevel import Building, MapLevel
from .mapsnapshot import MapPositionSnapshot
from .operatingsystem import OperatingSystem
from .relationship import AssetRelationship, RelationshipType, RelationshipTypePropagation
from .communication import Communication, CommunicationType
@@ -37,6 +39,10 @@ __all__ = [
'DashboardDefault',
'Location',
'LocationType',
# Map model (ADR-017): which drawing renders an asset, at what size
'Building',
'MapLevel',
'MapPositionSnapshot',
'derive_locationcode',
'OperatingSystem',
# Relationships

View File

@@ -117,9 +117,24 @@ class Asset(BaseModel, SoftDeleteMixin, AuditMixin):
nullable=True
)
# Floor map position (ADR-001: asset-specific override; nullable)
mapx = db.Column(db.Integer, comment='X coordinate on floor map (ADR-001)')
mapy = db.Column(db.Integer, comment='Y coordinate on floor map (ADR-001)')
# Floor map position (ADR-001: asset-specific override; nullable).
#
# Absolute pixels in the NATIVE COORDINATE SPACE OF ITS LEVEL, not of the
# site (ADR-017). levelid says which drawing they are pixels of, and without
# it a position cannot be rendered - a marker drawn on the wrong level's
# blueprint looks perfectly correct and points at the wrong place, so the UI
# shows "level unknown" rather than assuming the default.
mapx = db.Column(db.Integer, comment='X coordinate on this level (ADR-017)')
mapy = db.Column(db.Integer, comment='Y coordinate on this level (ADR-017)')
levelid = db.Column(
db.Integer, db.ForeignKey('maplevels.levelid'), nullable=True,
index=True,
comment='Which drawing mapx/mapy are pixels of (ADR-017)')
# When the position was last CONFIRMED against the current drawing. A bulk
# transform clears it, because a transform is a starting guess: the levels
# were redrawn and machines moved, and nothing in the coordinates says which
# markers are now stale. Null means "not yet reviewed on this drawing".
mapverifiedat = db.Column(db.DateTime, nullable=True)
# Notes
notes = db.Column(db.Text, nullable=True)
@@ -198,6 +213,10 @@ class Asset(BaseModel, SoftDeleteMixin, AuditMixin):
'locationname': related.location.locationname if related.location else None,
'mapx': related.mapx,
'mapy': related.mapy,
# The level belongs to whichever asset supplied the
# coordinates (ADR-017). Inheriting a position without its
# level draws it on the borrower's drawing instead.
'levelid': related.levelid,
'inheritedfrom': related.assetnumber
}
@@ -250,6 +269,11 @@ class Asset(BaseModel, SoftDeleteMixin, AuditMixin):
result['mapx'] = inherited['mapx']
if result.get('mapy') is None:
result['mapy'] = inherited['mapy']
# Coordinates and their level move together, always. Copying the
# position while leaving levelid as this asset's own is how an
# inherited marker lands on the wrong drawing.
if result.get('levelid') is None:
result['levelid'] = inherited.get('levelid')
# Operation/short code of the resolved location (own or inherited).
# Derived from the location name's leading token; labels can encode a

View File

@@ -70,6 +70,13 @@ class Location(BaseModel):
# chain priority 3.
mapx = db.Column(db.Integer, comment='Default X coordinate for assets at this location')
mapy = db.Column(db.Integer, comment='Default Y coordinate for assets at this location')
# Which drawing those coordinates are pixels of (ADR-017). A location is on a
# level as much as an asset is, and an asset with no position of its own
# inherits BOTH the coordinates and the level from here - inheriting the
# coordinates alone would draw them on whatever level the asset claims.
levelid = db.Column(
db.Integer, db.ForeignKey('maplevels.levelid'), nullable=True, index=True,
comment='Which level mapx/mapy are pixels of (ADR-017)')
# Relationships
locationtype = db.relationship('LocationType')

View File

@@ -0,0 +1,109 @@
"""Building + MapLevel models: which drawing renders an asset, at what size.
See ADR-017. A site used to have one floor map, described by four settings, and
`assets.mapx`/`mapy` were pixels in that one image. A second level and a likely
second building make that a table rather than a setting.
The alternative - stacking levels on one tall canvas - was rejected because it
turns "which level is this on" into `mapy > 2550`: an inference over a magic
number that changes whenever the drawing is re-exported.
"""
from shopdb.extensions import db
from .base import BaseModel
class Building(BaseModel):
"""A building at this site. Groups levels; holds nothing a level needs.
Separate from Location deliberately (ADR-017): a Location answers which
operation owns an asset, a building groups the drawings it appears on.
"""
__tablename__ = 'buildings'
buildingid = db.Column(db.Integer, primary_key=True)
buildingname = db.Column(db.String(100), nullable=False, unique=True)
# Display order. Buildings have no natural ordering and their names are not
# reliably ordinal ('Main', 'Annex', 'Building 2'), so the order is stated.
sortorder = db.Column(db.Integer, nullable=False, default=0)
levels = db.relationship(
'MapLevel', back_populates='building',
order_by='MapLevel.sortorder', cascade='all, delete-orphan')
def __repr__(self):
return f"<Building {self.buildingname}>"
def to_dict(self):
data = super().to_dict()
data['levels'] = [level.to_dict() for level in self.levels
if level.isactive]
return data
class MapLevel(BaseModel):
"""One drawing: a level of a building, with its own blueprint and size.
WHY THE DIMENSIONS LIVE HERE. They were site-wide settings, which cannot
express a mezzanine drawn at a different scale from the floor below it, and
certainly not a second building. `mapx`/`mapy` are absolute pixels in THIS
level's coordinate space, so a level without its own dimensions cannot place
a marker correctly.
Name and order are separate columns on purpose: levels are not reliably
numbered (basement, ground, mezzanine, roof), and `sortorder` gives
adjacency and up/down navigation without pretending the names are ordinal.
It also lets a mezzanine be inserted later without renumbering anything.
"""
__tablename__ = 'maplevels'
levelid = db.Column(db.Integer, primary_key=True)
buildingid = db.Column(
db.Integer, db.ForeignKey('buildings.buildingid'), nullable=False,
index=True)
levelname = db.Column(db.String(100), nullable=False)
sortorder = db.Column(db.Integer, nullable=False, default=0)
# Both themes, because the map renders in whichever the viewer is using and
# a light-on-white blueprint is unreadable in dark mode. Either may be
# blank; the renderer falls back to the other rather than to nothing.
blueprintlight = db.Column(db.String(255), nullable=True)
blueprintdark = db.Column(db.String(255), nullable=True)
# Native pixel size of the blueprint. Positions are absolute pixels in this
# space (ADR-017), so these are what a marker's coordinates mean.
mapwidth = db.Column(db.Integer, nullable=False, default=3300)
mapheight = db.Column(db.Integer, nullable=False, default=2550)
# Exactly one level carries this. It is where an asset with no level lands,
# and what the map opens on. Enforced in the API rather than by a constraint,
# because "exactly one" across rows is not a column-level rule.
isdefault = db.Column(db.Boolean, nullable=False, default=False)
building = db.relationship('Building', back_populates='levels')
__table_args__ = (
db.UniqueConstraint('buildingid', 'levelname',
name='uq_maplevel_building_name'),
)
def __repr__(self):
return f"<MapLevel {self.levelname}>"
def to_dict(self):
data = super().to_dict()
data['buildingname'] = self.building.buildingname if self.building else None
return data
@classmethod
def default_level(cls):
"""The default level, or the lowest-sorted one if none is marked.
Never returns None on a seeded database: the migration that created this
table also created one level from the settings it replaced.
"""
level = cls.query.filter_by(isdefault=True, isactive=True).first()
if level is not None:
return level
return (cls.query.filter_by(isactive=True)
.order_by(cls.sortorder, cls.levelid).first())

View File

@@ -0,0 +1,76 @@
"""A saved set of marker positions, so a bulk change can be undone.
Positions had no history. A landmark transform rewrites every marker on a level
in one statement, and without a way back the honest instruction would be "take a
database backup first" - which nobody does before clicking a button in a UI, so
in practice the feature would either not be used or be used once, badly.
One row holds the whole set as JSON rather than a row per asset. A snapshot is
read back whole or not at all, so restore stays a single statement, and there is
no orphan-child case to reason about.
"""
import json
from shopdb.extensions import db
from .base import BaseModel
class MapPositionSnapshot(BaseModel):
__tablename__ = 'mappositionsnapshots'
snapshotid = db.Column(db.Integer, primary_key=True)
# Which level the operation targeted. Nullable because a snapshot may span
# levels (moving assets between them), and then no single level owns it.
levelid = db.Column(db.Integer, nullable=True)
reason = db.Column(db.String(255), nullable=True)
assetcount = db.Column(db.Integer, nullable=False, default=0)
positionsjson = db.Column(db.Text, nullable=False)
# Set when this snapshot has been restored, so the history reads as what
# happened rather than as a list of identical-looking saves.
restoredat = db.Column(db.DateTime, nullable=True)
createdby = db.Column(db.String(100), nullable=True)
def __repr__(self):
return f"<MapPositionSnapshot {self.snapshotid} ({self.assetcount})>"
@property
def positions(self):
try:
return json.loads(self.positionsjson or '[]')
except ValueError:
return []
def to_dict(self):
"""Metadata only. The positions themselves are large and nobody browsing
a list of snapshots wants them."""
data = super().to_dict()
data.pop('positionsjson', None)
return data
@classmethod
def capture(cls, assets, reason, levelid=None, createdby=None):
"""Record the CURRENT positions of these assets, before they change.
Includes levelid and mapverifiedat, not just the coordinates: a restore
has to put a marker back on the level it was on and with the review state
it had, or undo would silently mark reviewed work as unreviewed.
"""
rows = [{
'assetid': asset.assetid,
'mapx': asset.mapx,
'mapy': asset.mapy,
'levelid': asset.levelid,
'mapverifiedat': asset.mapverifiedat.isoformat()
if asset.mapverifiedat else None,
} for asset in assets]
snapshot = cls(
levelid=levelid,
reason=reason,
assetcount=len(rows),
positionsjson=json.dumps(rows, separators=(',', ':')),
createdby=createdby,
)
db.session.add(snapshot)
db.session.flush()
return snapshot