Files
shopdb-flask/shopdb/core/models/relationship.py
cproudlock e2c45d33bc One printer picker for machines and PCs, and one default per asset
The assignment belongs to the MACHINE, and until now there was no way to set it
except the generic relationships card or the API - the form for the thing the
feature is about did not exist. MachineForm now carries the picker, and PCForm
uses the SAME component rather than its own copy: the PC's set overrides the
machine's, and two implementations of that would drift, with the two ends of an
override disagreeing being exactly the bug nobody would spot.

The shared picker also fixes what PCForm did on save. It wrote row at a time
through the generic relationship endpoints, which is a non-atomic reconcile: an
HTTP failure part way left a PC half-assigned with nothing recording what was
meant. It now calls the reconcile endpoint, which validates the default before
writing anything.

A relationship type can now say it allows one active row per asset
(relationshiptypes.issingular, migration 7d34), and defaultprinter says it.
Cardinality belongs to the type rather than the printers plugin: core's create
path is where every hand-made link passes, and the next type meaning "exactly
one" gets the rule for free. Setting a second default REPLACES the first instead
of refusing, because "make this the default" means that - and a card answering
409 would leave the user hunting for the old row.

Without it the schema was happy to hold two defaults: the unique constraint is
(source, target, type), so two different targets are two valid rows, and the
resolver takes the OLDEST - the new default silently lost. Proven by disabling
the new rule and watching the tests fail.

FOUND WHILE TESTING IN A BROWSER, and it was not mine: MachineForm read
.data.data off computersApi.listAll(), which resolves to the ARRAY - fetchAllPages
has already unwrapped every page. The whole parallel load threw into the catch,
so every dropdown on the machine edit form came up empty and the machine's own
values never loaded. A build cannot see this; only opening the page can.

GET /api/printers/assignments/for-asset/<id> returns an asset's OWN assignment,
without inheritance, because the editor must show what this asset's rows say -
otherwise a machine's printers appear ticked on the PC that inherits them and
unticking one silently creates an override.
2026-08-19 11:22:48 -04:00

172 lines
6.2 KiB
Python

"""Machine and Asset relationship models."""
from shopdb.extensions import db
from .base import BaseModel
class RelationshipType(BaseModel):
"""
Types of relationships between assets.
ADR-001 seeds three canonical types: partof, controls, connectedto.
Sites may add legacy/communication-flavored types (Serial Cable, Direct
Ethernet, USB, WiFi, Dualpath) for backward compatibility with pre-1.0
data, but new ADR-001 code paths only reason about the three canonical
types via free-text label for nuance.
"""
__tablename__ = 'relationshiptypes'
relationshiptypeid = db.Column(db.Integer, primary_key=True)
relationshiptype = db.Column(db.String(50), unique=True, nullable=False)
description = db.Column(db.Text)
color = db.Column(db.String(20), comment='CSS color for relationship badges')
# True: edge has a source->target meaning (controls, partof, Backup For).
# False: symmetric link (Dualpath, connectedto, USB...) shown on the card
# once per peer with no direction, both stored direction rows collapsed.
# At most one ACTIVE relationship of this type per source asset. A PC has
# one default printer; the (source, target, type) unique constraint cannot
# express that, because two different targets are two different rows.
issingular = db.Column(db.Boolean, nullable=False, default=False)
isdirectional = db.Column(
db.Boolean,
default=True,
nullable=False,
server_default='1',
comment='False = symmetric connection, shown direction-blind'
)
# Sibling propagation (ADR-001), WIRED. When a relationship of this type is
# created, the create path fans it out across every through-type in this
# type's propagation set (relationshiptypepropagations rows). For each
# SYMMETRIC through-type P, the source's edge to the target is mirrored to
# every asset linked to the target via P. This is M:N so one type can
# propagate through several rails at once. Seeded rows on this DB:
# controls -> partof (declared; directional rail, NOT consumed yet -
# parent/child fan-out direction is ambiguous)
# controls -> Dualpath (consumed; a dual-bay pair is one physical machine
# with one controller, so both bays carry controls)
# A dual-bay Dualpath pair thus gets the PC's controls link on both bays.
# propagatesthrough is the list of through-type RelationshipType rows.
propagatesthrough = db.relationship(
'RelationshipType',
secondary='relationshiptypepropagations',
primaryjoin='RelationshipType.relationshiptypeid'
' == RelationshipTypePropagation.relationshiptypeid',
secondaryjoin='RelationshipType.relationshiptypeid'
' == RelationshipTypePropagation.throughtypeid',
viewonly=True,
)
def __repr__(self):
return f"<RelationshipType {self.relationshiptype}>"
class RelationshipTypePropagation(db.Model):
"""
M:N propagation rails (ADR-001). One row means: a relationship of type
relationshiptypeid propagates through the connections of type throughtypeid.
Replaces the old single-valued relationshiptypes.propagatesthroughid so a
type (controls) can propagate through several through-types (partof AND
Dualpath) at once. Seed/CLI-managed; no management UI.
"""
__tablename__ = 'relationshiptypepropagations'
propagationid = db.Column(db.Integer, primary_key=True)
relationshiptypeid = db.Column(
db.Integer,
db.ForeignKey('relationshiptypes.relationshiptypeid'),
nullable=False
)
throughtypeid = db.Column(
db.Integer,
db.ForeignKey('relationshiptypes.relationshiptypeid'),
nullable=False
)
__table_args__ = (
db.UniqueConstraint(
'relationshiptypeid',
'throughtypeid',
name='uq_reltype_propagation'
),
)
def __repr__(self):
return f"<RelationshipTypePropagation {self.relationshiptypeid} through {self.throughtypeid}>"
class AssetRelationship(BaseModel):
"""
Relationships between assets.
Examples:
- Computer controls Machine
- Two machines are dualpath partners
- Network device connects to machine
"""
__tablename__ = 'assetrelationships'
relationshipid = db.Column(db.Integer, primary_key=True)
sourceassetid = db.Column(
db.Integer,
db.ForeignKey('assets.assetid'),
nullable=False
)
targetassetid = db.Column(
db.Integer,
db.ForeignKey('assets.assetid'),
nullable=False
)
relationshiptypeid = db.Column(
db.Integer,
db.ForeignKey('relationshiptypes.relationshiptypeid'),
nullable=False
)
# Free-text description carrying domain nuance ("DNC feed",
# "operator workstation", "ethernet PoE"). Avoids inflating type list.
label = db.Column(db.String(200), comment='Free-text relationship description (ADR-001)')
# When true, resolve_asset_position walks across this edge (priority 2
# in the resolution chain). Defaults to true for partof + controls when
# the relationship is created via the API; nullable for legacy rows.
inheritsposition = db.Column(
db.Boolean,
default=True,
nullable=False,
server_default='1',
comment='If true, resolved-position walk follows this edge (ADR-001)'
)
notes = db.Column(db.Text)
sourceasset = db.relationship(
'Asset',
foreign_keys=[sourceassetid],
backref='outgoing_relationships'
)
targetasset = db.relationship(
'Asset',
foreign_keys=[targetassetid],
backref='incoming_relationships'
)
relationshiptype = db.relationship('RelationshipType', backref='asset_relationships')
__table_args__ = (
db.UniqueConstraint(
'sourceassetid',
'targetassetid',
'relationshiptypeid',
name='uq_asset_relationship'
),
db.Index('idx_asset_rel_source', 'sourceassetid'),
db.Index('idx_asset_rel_target', 'targetassetid'),
)
def __repr__(self):
return f"<AssetRelationship {self.sourceassetid} -> {self.targetassetid}>"