Initial import: shopdb-flask multi-site asset platform

Flask + Vue rewrite of the classic-ASP shopdb, built as a plugin
framework so sister GE Aerospace sites can adopt it. Product version
0.7.0-pre-0.8.0, plugin contract 0.11.0, 966 backend tests.

Key entry points:
- docs/INSTALL-WINDOWS-IIS.md - tested Windows + IIS install runbook
  (own-site and subpath deployment methods)
- docs/PILOT-DEPLOY.md - production pilot: stand up + import + verify
- docs/IMPORT-API.md - schema-agnostic legacy data import contract
- scripts/site_imports/wjf/ - West Jefferson reference import loader
- docs/adr/ - twelve accepted architecture decision records
This commit is contained in:
2026-07-14 07:58:51 -04:00
commit a9d0dfff4a
599 changed files with 88557 additions and 0 deletions

View File

@@ -0,0 +1,5 @@
"""Computers plugin for ShopDB."""
from .plugin import ComputersPlugin
__all__ = ['ComputersPlugin']

View File

@@ -0,0 +1,5 @@
"""Computers plugin API."""
from .routes import computers_bp
__all__ = ['computers_bp']

View File

@@ -0,0 +1,894 @@
"""Computers plugin API endpoints."""
from flask import Blueprint, request
from flask_jwt_extended import jwt_required
from shopdb.api import db, Asset, AssetType, OperatingSystem, Application, AuditLog, Communication, CommunicationType, Setting, success_response, error_response, paginated_response, ErrorCodes, get_pagination_params, paginate_query
from ..models import Computer, ComputerType, ComputerInstalledApp, AccessProtocol, ComputerAccess
from shopdb.api import require_permission, apply_import_timestamps
computers_bp = Blueprint('computers', __name__)
# =============================================================================
# Computer Types
# =============================================================================
@computers_bp.route('/types', methods=['GET'])
@jwt_required(optional=True)
def list_computer_types():
"""List all computer types."""
page, per_page = get_pagination_params(request)
query = ComputerType.query
if request.args.get('active', 'true').lower() != 'false':
query = query.filter(ComputerType.isactive == True)
if search := request.args.get('search'):
query = query.filter(ComputerType.computertype.ilike(f'%{search}%'))
query = query.order_by(ComputerType.computertype)
items, total = paginate_query(query, page, per_page)
data = [t.to_dict() for t in items]
return paginated_response(data, page, per_page, total)
@computers_bp.route('/types/<int:type_id>', methods=['GET'])
@jwt_required(optional=True)
def get_computer_type(type_id: int):
"""Get a single computer type."""
t = db.session.get(ComputerType, type_id)
if not t:
return error_response(
ErrorCodes.NOT_FOUND,
f'Computer type with ID {type_id} not found',
http_code=404
)
return success_response(t.to_dict())
@computers_bp.route('/types', methods=['POST'])
@jwt_required()
@require_permission('computers.create')
def create_computer_type():
"""Create a new computer type."""
data = request.get_json()
if not data or not data.get('computertype'):
return error_response(ErrorCodes.VALIDATION_ERROR, 'computertype is required')
existing = ComputerType.query.filter_by(computertype=data['computertype']).first()
if existing:
if not existing.isactive:
# Adding a name that matches a deactivated type revives it.
existing.isactive = True
for key in ('description', 'icon', 'color'):
if data.get(key) is not None:
setattr(existing, key, data[key])
db.session.commit()
return success_response(existing.to_dict(), message='Reactivated existing computer type')
return error_response(
ErrorCodes.CONFLICT,
f"Computer type '{data['computertype']}' already exists",
http_code=409
)
t = ComputerType(
computertype=data['computertype'],
description=data.get('description'),
icon=data.get('icon'), color=data.get('color')
)
db.session.add(t)
db.session.commit()
return success_response(t.to_dict(), message='Computer type created', http_code=201)
@computers_bp.route('/types/<int:type_id>', methods=['PUT'])
@jwt_required()
@require_permission('computers.edit')
def update_computer_type(type_id: int):
"""Update a computer type."""
t = db.session.get(ComputerType, type_id)
if not t:
return error_response(
ErrorCodes.NOT_FOUND,
f'Computer type with ID {type_id} not found',
http_code=404
)
data = request.get_json()
if not data:
return error_response(ErrorCodes.VALIDATION_ERROR, 'No data provided')
if 'computertype' in data and data['computertype'] != t.computertype:
if ComputerType.query.filter_by(computertype=data['computertype']).first():
return error_response(
ErrorCodes.CONFLICT,
f"Computer type '{data['computertype']}' already exists",
http_code=409
)
for key in ['computertype', 'description', 'icon', 'color', 'isactive']:
if key in data:
setattr(t, key, data[key])
db.session.commit()
return success_response(t.to_dict(), message='Computer type updated')
@computers_bp.route('/types/<int:type_id>', methods=['DELETE'])
@jwt_required()
@require_permission('computers.delete')
def delete_computer_type(type_id: int):
"""Delete a computer type. Refused if any PC still uses it."""
t = db.session.get(ComputerType, type_id)
if not t:
return error_response(ErrorCodes.NOT_FOUND, 'Computer type not found', http_code=404)
inuse = Computer.query.filter_by(computertypeid=type_id).count()
if inuse:
return error_response(ErrorCodes.CONFLICT,
f"Cannot delete: {inuse} PC(s) still use this type", http_code=409)
db.session.delete(t)
db.session.commit()
return success_response(message='Computer type deleted')
# =============================================================================
# Access protocol catalog (VNC / WinRM / RDP / ...) - admin-managed
# =============================================================================
@computers_bp.route('/protocols', methods=['GET'])
@jwt_required(optional=True)
def list_protocols():
"""List access protocols. ?active=false includes disabled ones."""
query = AccessProtocol.query
if request.args.get('active', 'true').lower() != 'false':
query = query.filter(AccessProtocol.isactive == True)
protocols = query.order_by(AccessProtocol.name).all()
return success_response([p.to_dict() for p in protocols])
@computers_bp.route('/protocols', methods=['POST'])
@jwt_required()
@require_permission('computers.edit')
def create_protocol():
data = request.get_json() or {}
if not (data.get('name') and data.get('scheme') and data.get('linktemplate')):
return error_response(ErrorCodes.VALIDATION_ERROR, 'name, scheme and linktemplate are required')
if AccessProtocol.query.filter_by(name=data['name']).first():
return error_response(ErrorCodes.CONFLICT, f"Protocol '{data['name']}' already exists", http_code=409)
p = AccessProtocol(
name=data['name'],
scheme=data['scheme'],
defaultport=data.get('defaultport') or None,
linktemplate=data['linktemplate'],
isactive=data.get('isactive', True),
)
db.session.add(p)
db.session.commit()
return success_response(p.to_dict(), message='Protocol created', http_code=201)
@computers_bp.route('/protocols/<int:protocol_id>', methods=['PUT', 'PATCH'])
@jwt_required()
@require_permission('computers.edit')
def update_protocol(protocol_id):
p = db.session.get(AccessProtocol, protocol_id)
if not p:
return error_response(ErrorCodes.NOT_FOUND, 'Protocol not found', http_code=404)
data = request.get_json() or {}
for field in ('name', 'scheme', 'linktemplate'):
if data.get(field):
setattr(p, field, data[field])
if 'defaultport' in data:
p.defaultport = data['defaultport'] or None
if 'isactive' in data:
p.isactive = bool(data['isactive'])
db.session.commit()
return success_response(p.to_dict(), message='Protocol updated')
@computers_bp.route('/protocols/<int:protocol_id>', methods=['DELETE'])
@jwt_required()
@require_permission('computers.edit')
def delete_protocol(protocol_id):
p = db.session.get(AccessProtocol, protocol_id)
if not p:
return error_response(ErrorCodes.NOT_FOUND, 'Protocol not found', http_code=404)
# If any PC still references it, deactivate rather than hard-delete.
if ComputerAccess.query.filter_by(protocolid=protocol_id).first():
p.isactive = False
db.session.commit()
return success_response(message='Protocol is in use; deactivated instead of deleted')
db.session.delete(p)
db.session.commit()
return success_response(message='Protocol deleted')
def _pc_access_domain():
# Contract-pure read of the pc_access_domain setting (no core.api import).
row = Setting.query.filter_by(key='pc_access_domain').first()
return ((row.value if row else '') or '').strip()
def _computer_access_links(comp, domain=None):
"""Resolved remote-access links for a computer: each enabled protocol's
template filled with the PC hostname joined to the pc_access_domain setting.
A hostname that is already an FQDN (has a dot) is used as-is. Pass domain
when calling in a loop to avoid one settings lookup per computer."""
if domain is None:
domain = _pc_access_domain()
hostname = (comp.hostname or '').strip()
if not hostname:
host = ''
elif '.' in hostname or not domain:
host = hostname
else:
host = f"{hostname}.{domain}"
links = []
for am in comp.accessmethods:
protocol = am.protocol
if not (am.isactive and protocol and protocol.isactive):
continue
port = am.portoverride or protocol.defaultport
link = None
if host:
try:
link = protocol.linktemplate.format(
host=host,
port=(port if port is not None else ''),
scheme=protocol.scheme,
)
except (KeyError, IndexError, ValueError):
link = None
links.append({
'id': am.id,
'protocolid': protocol.protocolid,
'name': protocol.name,
'scheme': protocol.scheme,
'port': port,
'portoverride': am.portoverride,
'link': link,
})
return links
def _sync_access_methods(comp, data):
"""Replace a computer's enabled protocols from data['accessmethods'] (a list
of {protocolid, portoverride?}). No-op if the key is absent, so callers that
don't touch access aren't affected."""
if 'accessmethods' not in data:
return
desired = data.get('accessmethods') or []
ComputerAccess.query.filter_by(computerid=comp.computerid).delete()
seen = set()
for m in desired:
try:
pid = int(m.get('protocolid'))
except (TypeError, ValueError):
continue
if pid in seen:
continue
seen.add(pid)
port = m.get('portoverride')
try:
port = int(port) if port not in (None, '') else None
except (TypeError, ValueError):
port = None
db.session.add(ComputerAccess(
computerid=comp.computerid,
protocolid=pid,
portoverride=port,
isactive=True,
))
# =============================================================================
# Computers CRUD
# =============================================================================
@computers_bp.route('', methods=['GET'])
@jwt_required(optional=True)
def list_computers():
"""
List all computers with filtering and pagination.
Query parameters:
- page, per_page: Pagination
- active: Filter by active status
- search: Search by asset number, name, or hostname
- type_id: Filter by computer type ID
- os_id: Filter by operating system ID
- location_id: Filter by location ID
- businessunit_id: Filter by business unit ID
- shopfloor: Filter by shopfloor flag (true/false)
"""
page, per_page = get_pagination_params(request)
# Join Computer with Asset
query = db.session.query(Computer).join(Asset)
# Active filter
if request.args.get('active', 'true').lower() != 'false':
query = query.filter(Asset.isactive == True)
# Exact-match natural-key lookup for idempotent import (asset number).
if exactassetnumber := request.args.get('assetnumber'):
query = query.filter(Asset.assetnumber == exactassetnumber)
# Search filter
if search := request.args.get('search'):
query = query.filter(
db.or_(
Asset.assetnumber.ilike(f'%{search}%'),
Asset.name.ilike(f'%{search}%'),
Asset.serialnumber.ilike(f'%{search}%'),
Computer.hostname.ilike(f'%{search}%')
)
)
# Computer type filter
if type_id := request.args.get('typeid', request.args.get('type_id')):
query = query.filter(Computer.computertypeid == int(type_id))
# OS filter
if os_id := request.args.get('osid', request.args.get('os_id')):
query = query.filter(Computer.osid == int(os_id))
# Location filter
if location_id := request.args.get('locationid', request.args.get('location_id')):
query = query.filter(Asset.locationid == int(location_id))
# Business unit filter
if bu_id := request.args.get('businessunitid', request.args.get('businessunit_id')):
query = query.filter(Asset.businessunitid == int(bu_id))
# Shopfloor filter (by the Shopfloor computer type)
if shopfloor := request.args.get('shopfloor'):
sf = ComputerType.query.filter_by(computertype='Shopfloor').first()
sf_id = sf.computertypeid if sf else -1
if shopfloor.lower() == 'true':
query = query.filter(Computer.computertypeid == sf_id)
else:
query = query.filter(db.or_(Computer.computertypeid != sf_id,
Computer.computertypeid.is_(None)))
# Sorting
sort_by = request.args.get('sort', 'hostname')
sort_dir = request.args.get('dir', 'asc')
if sort_by == 'hostname':
col = Computer.hostname
elif sort_by == 'assetnumber':
col = Asset.assetnumber
elif sort_by == 'name':
col = Asset.name
elif sort_by == 'lastreporteddate':
col = Computer.lastreporteddate
else:
col = Computer.hostname
query = query.order_by(col.desc() if sort_dir == 'desc' else col)
items, total = paginate_query(query, page, per_page)
# Build response with both asset and computer data
data = []
accessdomain = _pc_access_domain()
for comp in items:
item = comp.asset.to_dict() if comp.asset else {}
item['computer'] = comp.to_dict()
item['accessmethods'] = _computer_access_links(comp, domain=accessdomain)
data.append(item)
return paginated_response(data, page, per_page, total)
@computers_bp.route('/<int:computer_id>', methods=['GET'])
@jwt_required(optional=True)
def get_computer(computer_id: int):
"""Get a single computer with full details."""
comp = db.session.get(Computer, computer_id)
if not comp:
return error_response(
ErrorCodes.NOT_FOUND,
f'Computer with ID {computer_id} not found',
http_code=404
)
result = comp.asset.to_dict() if comp.asset else {}
result['computer'] = comp.to_dict()
result['communications'] = [
c.to_dict() for c in
Communication.query.filter_by(assetid=comp.assetid).all()
]
result['accessmethods'] = _computer_access_links(comp)
return success_response(result)
@computers_bp.route('/by-asset/<int:asset_id>', methods=['GET'])
@jwt_required(optional=True)
def get_computer_by_asset(asset_id: int):
"""Get computer data by asset ID."""
comp = Computer.query.filter_by(assetid=asset_id).first()
if not comp:
return error_response(
ErrorCodes.NOT_FOUND,
f'Computer for asset {asset_id} not found',
http_code=404
)
result = comp.asset.to_dict() if comp.asset else {}
result['computer'] = comp.to_dict()
return success_response(result)
@computers_bp.route('/by-hostname/<hostname>', methods=['GET'])
@jwt_required(optional=True)
def get_computer_by_hostname(hostname: str):
"""Get computer by hostname."""
comp = Computer.query.filter_by(hostname=hostname).first()
if not comp:
return error_response(
ErrorCodes.NOT_FOUND,
f'Computer with hostname {hostname} not found',
http_code=404
)
result = comp.asset.to_dict() if comp.asset else {}
result['computer'] = comp.to_dict()
return success_response(result)
@computers_bp.route('', methods=['POST'])
@jwt_required()
@require_permission('computers.create')
def create_computer():
"""
Create new computer (creates both Asset and Computer records).
Required fields:
- assetnumber: Business identifier
Optional fields:
- name, serialnumber, statusid, locationid, businessunitid
- computertypeid, hostname, osid
- mapx, mapy, notes
"""
data = request.get_json()
if not data:
return error_response(ErrorCodes.VALIDATION_ERROR, 'No data provided')
if not data.get('assetnumber'):
return error_response(ErrorCodes.VALIDATION_ERROR, 'assetnumber is required')
# Check for duplicate assetnumber
if Asset.query.filter_by(assetnumber=data['assetnumber']).first():
return error_response(
ErrorCodes.CONFLICT,
f"Asset with number '{data['assetnumber']}' already exists",
http_code=409
)
# Check for duplicate hostname
if data.get('hostname'):
if Computer.query.filter_by(hostname=data['hostname']).first():
return error_response(
ErrorCodes.CONFLICT,
f"Computer with hostname '{data['hostname']}' already exists",
http_code=409
)
# Get computer asset type
computer_type = AssetType.query.filter_by(assettype='computer').first()
if not computer_type:
return error_response(
ErrorCodes.INTERNAL_ERROR,
'Computer asset type not found. Plugin may not be properly installed.',
http_code=500
)
# Create the core asset
asset = Asset(
assetnumber=data['assetnumber'],
name=data.get('name'),
serialnumber=data.get('serialnumber'),
gaugelabreference=data.get('gaugelabreference'),
maintenancereference=data.get('maintenancereference'),
assettypeid=computer_type.assettypeid,
statusid=data.get('statusid', 1),
locationid=data.get('locationid'),
businessunitid=data.get('businessunitid'),
mapx=data.get('mapx'),
mapy=data.get('mapy'),
notes=data.get('notes')
)
db.session.add(asset)
db.session.flush() # Get the assetid
# Create the computer extension
comp = Computer(
assetid=asset.assetid,
computertypeid=data.get('computertypeid'),
hostname=data.get('hostname'),
osid=data.get('osid'),
vendorid=data.get('vendorid'),
modelnumberid=data.get('modelnumberid'),
loggedinuser=data.get('loggedinuser'),
lastreporteddate=data.get('lastreporteddate'),
lastboottime=data.get('lastboottime')
)
db.session.add(comp)
db.session.flush()
# Optional primary IP communication
if data.get('ipaddress'):
ip_comtype = CommunicationType.query.filter_by(comtype='IP').first()
if ip_comtype:
db.session.add(Communication(
assetid=asset.assetid,
comtypeid=ip_comtype.comtypeid,
ipaddress=data['ipaddress'],
isprimary=True,
))
# Remote-access protocols
_sync_access_methods(comp, data)
# Preserve legacy timestamps in import mode (no-op otherwise)
apply_import_timestamps(asset, data)
# Audit log
AuditLog.log('created', 'Computer', entityid=comp.computerid,
entityname=data.get('hostname') or data['assetnumber'])
db.session.commit()
result = asset.to_dict()
result['computer'] = comp.to_dict()
result['accessmethods'] = _computer_access_links(comp)
return success_response(result, message='Computer created', http_code=201)
@computers_bp.route('/<int:computer_id>', methods=['PUT'])
@jwt_required()
@require_permission('computers.edit')
def update_computer(computer_id: int):
"""Update computer (both Asset and Computer records)."""
comp = db.session.get(Computer, computer_id)
if not comp:
return error_response(
ErrorCodes.NOT_FOUND,
f'Computer with ID {computer_id} not found',
http_code=404
)
data = request.get_json()
if not data:
return error_response(ErrorCodes.VALIDATION_ERROR, 'No data provided')
asset = comp.asset
# Check for conflicting assetnumber
if 'assetnumber' in data and data['assetnumber'] != asset.assetnumber:
if Asset.query.filter_by(assetnumber=data['assetnumber']).first():
return error_response(
ErrorCodes.CONFLICT,
f"Asset with number '{data['assetnumber']}' already exists",
http_code=409
)
# Check for conflicting hostname
if 'hostname' in data and data['hostname'] != comp.hostname:
existing = Computer.query.filter_by(hostname=data['hostname']).first()
if existing and existing.computerid != computer_id:
return error_response(
ErrorCodes.CONFLICT,
f"Computer with hostname '{data['hostname']}' already exists",
http_code=409
)
# Track changes for audit log
changes = {}
# Update asset fields
asset_fields = ['assetnumber', 'name', 'serialnumber', 'gaugelabreference',
'maintenancereference', 'statusid',
'locationid', 'businessunitid', 'mapx', 'mapy', 'notes', 'isactive']
for key in asset_fields:
if key in data:
old_val = getattr(asset, key)
new_val = data[key]
if old_val != new_val:
changes[key] = {'old': old_val, 'new': new_val}
setattr(asset, key, data[key])
# Update computer fields
computer_fields = ['computertypeid', 'hostname', 'osid', 'vendorid',
'modelnumberid', 'loggedinuser', 'lastreporteddate',
'lastboottime']
for key in computer_fields:
if key in data:
old_val = getattr(comp, key)
new_val = data[key]
if old_val != new_val:
changes[key] = {'old': old_val, 'new': new_val}
setattr(comp, key, data[key])
# Upsert the primary IP communication so a single PUT covers it
if 'ipaddress' in data:
ip = (data.get('ipaddress') or '').strip()
primary = Communication.query.filter_by(
assetid=asset.assetid, isprimary=True).first()
if ip:
if primary:
primary.ipaddress = ip
else:
ip_comtype = CommunicationType.query.filter_by(comtype='IP').first()
if ip_comtype:
db.session.add(Communication(
assetid=asset.assetid, comtypeid=ip_comtype.comtypeid,
ipaddress=ip, isprimary=True))
elif primary:
primary.ipaddress = None
# Remote-access protocols
_sync_access_methods(comp, data)
# Audit log if there were changes
if changes:
AuditLog.log('updated', 'Computer', entityid=comp.computerid,
entityname=comp.hostname or asset.assetnumber, changes=changes)
apply_import_timestamps(asset, data)
db.session.commit()
result = asset.to_dict()
result['computer'] = comp.to_dict()
result['accessmethods'] = _computer_access_links(comp)
return success_response(result, message='Computer updated')
@computers_bp.route('/<int:computer_id>', methods=['DELETE'])
@jwt_required()
@require_permission('computers.delete')
def delete_computer(computer_id: int):
"""Delete (soft delete) computer."""
comp = db.session.get(Computer, computer_id)
if not comp:
return error_response(
ErrorCodes.NOT_FOUND,
f'Computer with ID {computer_id} not found',
http_code=404
)
# Soft delete the asset
comp.asset.isactive = False
# Audit log
AuditLog.log('deleted', 'Computer', entityid=comp.computerid,
entityname=comp.hostname or comp.asset.assetnumber)
db.session.commit()
return success_response(message='Computer deleted')
# =============================================================================
# Installed Applications
# =============================================================================
@computers_bp.route('/<int:computer_id>/apps', methods=['GET'])
@jwt_required(optional=True)
def get_installed_apps(computer_id: int):
"""Get all installed applications for a computer."""
comp = db.session.get(Computer, computer_id)
if not comp:
return error_response(
ErrorCodes.NOT_FOUND,
f'Computer with ID {computer_id} not found',
http_code=404
)
apps = ComputerInstalledApp.query.filter_by(
computerid=computer_id,
isactive=True
).all()
data = [app.to_dict() for app in apps]
return success_response(data)
@computers_bp.route('/<int:computer_id>/apps', methods=['POST'])
@jwt_required()
@require_permission('computers.create')
def add_installed_app(computer_id: int):
"""Add an installed application to a computer."""
comp = db.session.get(Computer, computer_id)
if not comp:
return error_response(
ErrorCodes.NOT_FOUND,
f'Computer with ID {computer_id} not found',
http_code=404
)
data = request.get_json()
if not data or not data.get('appid'):
return error_response(ErrorCodes.VALIDATION_ERROR, 'appid is required')
appid = data['appid']
# Validate app exists
if not db.session.get(Application, appid):
return error_response(ErrorCodes.NOT_FOUND, f'Application {appid} not found', http_code=404)
# Check for duplicate
existing = ComputerInstalledApp.query.filter_by(
computerid=computer_id,
appid=appid
).first()
if existing:
if existing.isactive:
return error_response(
ErrorCodes.CONFLICT,
'This application is already installed on this computer',
http_code=409
)
else:
# Reactivate
existing.isactive = True
existing.appversionid = data.get('appversionid')
db.session.commit()
return success_response(existing.to_dict(), message='Application reinstalled')
# Create new installation record
installed = ComputerInstalledApp(
computerid=computer_id,
appid=appid,
appversionid=data.get('appversionid')
)
db.session.add(installed)
db.session.commit()
return success_response(installed.to_dict(), message='Application installed', http_code=201)
@computers_bp.route('/<int:computer_id>/apps/<int:app_id>', methods=['DELETE'])
@jwt_required()
@require_permission('computers.delete')
def remove_installed_app(computer_id: int, app_id: int):
"""Remove an installed application from a computer."""
installed = ComputerInstalledApp.query.filter_by(
computerid=computer_id,
appid=app_id,
isactive=True
).first()
if not installed:
return error_response(
ErrorCodes.NOT_FOUND,
'Installation record not found',
http_code=404
)
installed.isactive = False
db.session.commit()
return success_response(message='Application uninstalled')
# =============================================================================
# Status Reporting
# =============================================================================
@computers_bp.route('/<int:computer_id>/report', methods=['POST'])
@jwt_required()
@require_permission('computers.create')
def report_status(computer_id: int):
"""
Report computer status (for agent-based reporting).
This endpoint can be called periodically by a client agent
to update status information.
"""
comp = db.session.get(Computer, computer_id)
if not comp:
return error_response(
ErrorCodes.NOT_FOUND,
f'Computer with ID {computer_id} not found',
http_code=404
)
data = request.get_json() or {}
# Update status fields
from datetime import datetime, timezone
comp.lastreporteddate = datetime.now(timezone.utc).replace(tzinfo=None)
if 'loggedinuser' in data:
comp.loggedinuser = data['loggedinuser']
if 'lastboottime' in data:
comp.lastboottime = data['lastboottime']
db.session.commit()
return success_response(message='Status reported')
# =============================================================================
# Dashboard
# =============================================================================
@computers_bp.route('/dashboard/summary', methods=['GET'])
@jwt_required(optional=True)
def dashboard_summary():
"""Get computer dashboard summary data."""
# Total active computers
total = db.session.query(Computer).join(Asset).filter(
Asset.isactive == True
).count()
# Count by computer type
by_type = db.session.query(
ComputerType.computertype,
db.func.count(Computer.computerid)
).join(Computer, Computer.computertypeid == ComputerType.computertypeid
).join(Asset, Asset.assetid == Computer.assetid
).filter(Asset.isactive == True
).group_by(ComputerType.computertype
).all()
# Count by OS
by_os = db.session.query(
OperatingSystem.osname,
db.func.count(Computer.computerid)
).join(Computer, Computer.osid == OperatingSystem.osid
).join(Asset, Asset.assetid == Computer.assetid
).filter(Asset.isactive == True
).group_by(OperatingSystem.osname
).all()
# Count shopfloor vs non-shopfloor
sf = ComputerType.query.filter_by(computertype='Shopfloor').first()
shopfloor_count = db.session.query(Computer).join(Asset).filter(
Asset.isactive == True,
Computer.computertypeid == (sf.computertypeid if sf else -1)
).count()
return success_response({
'total': total,
'bytype': [{'type': t, 'count': c} for t, c in by_type],
'byos': [{'os': o, 'count': c} for o, c in by_os],
'shopfloor': shopfloor_count,
'nonshopfloor': total - shopfloor_count
})

View File

@@ -0,0 +1,23 @@
{
"name": "computers",
"version": "1.0.0",
"description": "Computer management plugin for PCs, servers, and workstations with software tracking",
"author": "ShopDB Team",
"dependencies": [],
"core_version": ">=0.1.0,<1.0.0",
"api_prefix": "/api/computers",
"provides": {
"asset_type": "computer",
"features": [
"computer_tracking",
"software_inventory",
"remote_access",
"os_management"
]
},
"settings": {
"enable_winrm": true,
"enable_vnc": true,
"auto_report_interval_hours": 24
}
}

View File

@@ -0,0 +1,14 @@
"""Alembic environment for the computers plugin migration chain.
Delegates to the shared runner in shopdb.plugins.alembic_template, which
filters the metadata to this plugin's tables and drives Alembic against the
per-plugin version table alembic_version_computers. See ADR-008 for the
ownership cutover between the core chain and per-plugin chains.
"""
import os
os.environ['PLUGIN_NAME'] = 'computers'
from shopdb.plugins.alembic_template import run_migrations # noqa: E402
run_migrations()

View File

@@ -0,0 +1,24 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)}
branch_labels = ${repr(branch_labels)}
depends_on = ${repr(depends_on)}
def upgrade():
${upgrades if upgrades else "pass"}
def downgrade():
${downgrades if downgrades else "pass"}

View File

@@ -0,0 +1,28 @@
"""computers plugin anchor (ownership cutover).
Stamp-only no-op. The core Alembic chain (baseline .. 7d16_directoryemployees)
already created every table this plugin owns at the cutover point, so there is
nothing to build here. This revision gives the plugin's own chain a base that
`flask plugin upgrade-all` can stamp into alembic_version_computers. From this
anchor forward, new computers schema changes land as 000N revisions in this
directory, never in the core chain. See ADR-008.
"""
from alembic import op # noqa: F401
import sqlalchemy as sa # noqa: F401
# revision identifiers, used by Alembic.
revision = 'computers0001anchor'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# No-op: the core chain owns every table that exists at the cutover.
pass
def downgrade():
# No-op: this anchor never unwinds core-owned tables.
pass

View File

@@ -0,0 +1,17 @@
"""Computers plugin models."""
from .computer import (
Computer,
ComputerType,
ComputerInstalledApp,
AccessProtocol,
ComputerAccess,
)
__all__ = [
'Computer',
'ComputerType',
'ComputerInstalledApp',
'AccessProtocol',
'ComputerAccess',
]

View File

@@ -0,0 +1,284 @@
"""Computer plugin models."""
from datetime import datetime, timezone
from shopdb.api import db, BaseModel
def _utcnow():
# naive UTC to match the other DB DateTime columns (stored without tzinfo)
return datetime.now(timezone.utc).replace(tzinfo=None)
class ComputerType(BaseModel):
"""
Computer type classification.
Examples: Shopfloor PC, Engineer Workstation, CMM PC, Server, etc.
"""
__tablename__ = 'computertypes'
computertypeid = db.Column(db.Integer, primary_key=True)
computertype = db.Column(db.String(100), unique=True, nullable=False)
description = db.Column(db.Text)
icon = db.Column(db.String(50), comment='Icon name for UI')
color = db.Column(db.String(20), comment='CSS color for UI/map markers')
def __repr__(self):
return f"<ComputerType {self.computertype}>"
class Computer(BaseModel):
"""
Computer-specific extension data.
Links to core Asset table via assetid.
Stores computer-specific fields like hostname, OS, logged in user, etc.
"""
__tablename__ = 'computers'
computerid = db.Column(db.Integer, primary_key=True)
# Link to core asset
assetid = db.Column(
db.Integer,
db.ForeignKey('assets.assetid', ondelete='CASCADE'),
unique=True,
nullable=False,
index=True
)
# Computer classification
computertypeid = db.Column(
db.Integer,
db.ForeignKey('computertypes.computertypeid'),
nullable=True
)
# Network identity
hostname = db.Column(
db.String(100),
comment='Network hostname'
)
# Operating system
osid = db.Column(
db.Integer,
db.ForeignKey('operatingsystems.osid'),
nullable=True
)
# Hardware make/model (PCs carry vendor + model like machines)
vendorid = db.Column(
db.Integer,
db.ForeignKey('vendors.vendorid'),
nullable=True
)
modelnumberid = db.Column(
db.Integer,
db.ForeignKey('models.modelnumberid'),
nullable=True
)
# Status tracking
loggedinuser = db.Column(db.String(100), nullable=True)
lastreporteddate = db.Column(db.DateTime, nullable=True)
lastboottime = db.Column(db.DateTime, nullable=True)
# Remote access is now modeled per-protocol via the accessmethods
# relationship (AccessProtocol / ComputerAccess), replacing isvnc/iswinrm.
# Relationships
asset = db.relationship(
'Asset',
backref=db.backref('computer', uselist=False, lazy='joined')
)
computertype = db.relationship('ComputerType', backref='computers')
operatingsystem = db.relationship('OperatingSystem', backref='computers')
vendor = db.relationship('Vendor')
model = db.relationship('Model')
# Installed applications (one-to-many)
installedapps = db.relationship(
'ComputerInstalledApp',
back_populates='computer',
cascade='all, delete-orphan',
lazy='dynamic'
)
# Remote-access protocols enabled on this PC (replaces isvnc/iswinrm)
accessmethods = db.relationship(
'ComputerAccess',
back_populates='computer',
cascade='all, delete-orphan',
lazy='selectin'
)
__table_args__ = (
db.Index('idx_computer_type', 'computertypeid'),
db.Index('idx_computer_hostname', 'hostname'),
db.Index('idx_computer_os', 'osid'),
)
def __repr__(self):
return f"<Computer {self.hostname or self.assetid}>"
def to_dict(self):
"""Convert to dictionary with related names."""
result = super().to_dict()
# Add related object names
if self.computertype:
result['computertypename'] = self.computertype.computertype
if self.operatingsystem:
result['osname'] = self.operatingsystem.osname
if self.vendor:
result['vendorname'] = self.vendor.vendor
if self.model:
result['modelname'] = self.model.modelnumber
if self.model.imageurl:
result['imageurl'] = self.model.imageurl
# Names of enabled remote-access protocols (for list badges)
result['accessprotocolnames'] = [
am.protocol.name for am in self.accessmethods
if am.isactive and am.protocol and am.protocol.isactive
]
return result
class ComputerInstalledApp(db.Model):
"""
Junction table for applications installed on computers.
Tracks which applications are installed on which computers,
including version information.
"""
__tablename__ = 'computerinstalledapps'
id = db.Column(db.Integer, primary_key=True)
computerid = db.Column(
db.Integer,
db.ForeignKey('computers.computerid', ondelete='CASCADE'),
nullable=False
)
appid = db.Column(
db.Integer,
db.ForeignKey('applications.appid'),
nullable=False
)
appversionid = db.Column(
db.Integer,
db.ForeignKey('appversions.appversionid'),
nullable=True
)
# Raw version string from automated collection (when no curated AppVersion)
installedversion = db.Column(db.String(100), nullable=True)
isactive = db.Column(db.Boolean, default=True, nullable=False)
installeddate = db.Column(db.DateTime, default=_utcnow)
# Relationships
computer = db.relationship('Computer', back_populates='installedapps')
application = db.relationship('Application')
appversion = db.relationship('AppVersion')
__table_args__ = (
db.UniqueConstraint('computerid', 'appid', name='uq_computer_app'),
db.Index('idx_compapp_computer', 'computerid'),
db.Index('idx_compapp_app', 'appid'),
)
def to_dict(self):
# Curated AppVersion wins; else the raw collected version string.
version = None
if self.appversion is not None:
version = self.appversion.version
elif self.installedversion:
version = self.installedversion
return {
'id': self.id,
'computerid': self.computerid,
'appid': self.appid,
'appname': self.application.appname if self.application else None,
'appdescription': self.application.appdescription if self.application else None,
'appversionid': self.appversionid,
'installedversion': version,
'installeddate': self.installeddate.isoformat() + 'Z' if self.installeddate else None,
'isactive': self.isactive,
}
class AccessProtocol(db.Model):
"""
Catalog of remote-access protocols a PC can expose (VNC, WinRM, RDP, SSH...).
linktemplate builds a connection URL from placeholders {host}, {port},
{scheme}. {host} is the PC hostname joined to the pc_access_domain setting.
Admin-managed; replaces the old fixed isvnc/iswinrm booleans.
"""
__tablename__ = 'accessprotocols'
protocolid = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), unique=True, nullable=False)
scheme = db.Column(db.String(20), nullable=False)
defaultport = db.Column(db.Integer, nullable=True)
linktemplate = db.Column(db.String(255), nullable=False)
isactive = db.Column(db.Boolean, default=True, nullable=False)
def to_dict(self):
return {
'protocolid': self.protocolid,
'name': self.name,
'scheme': self.scheme,
'defaultport': self.defaultport,
'linktemplate': self.linktemplate,
'isactive': bool(self.isactive),
}
class ComputerAccess(db.Model):
"""A protocol enabled on a specific PC, with an optional port override."""
__tablename__ = 'computeraccess'
id = db.Column(db.Integer, primary_key=True)
computerid = db.Column(
db.Integer,
db.ForeignKey('computers.computerid', ondelete='CASCADE'),
nullable=False
)
protocolid = db.Column(
db.Integer,
db.ForeignKey('accessprotocols.protocolid'),
nullable=False
)
portoverride = db.Column(db.Integer, nullable=True)
isactive = db.Column(db.Boolean, default=True, nullable=False)
protocol = db.relationship('AccessProtocol')
computer = db.relationship('Computer', back_populates='accessmethods')
__table_args__ = (
db.UniqueConstraint('computerid', 'protocolid', name='uq_computer_protocol'),
db.Index('idx_compaccess_computer', 'computerid'),
)
def to_dict(self):
"""Convert to dictionary."""
return {
'id': self.id,
'computerid': self.computerid,
'appid': self.appid,
'appversionid': self.appversionid,
'isactive': self.isactive,
'installeddate': self.installeddate.isoformat() + 'Z' if self.installeddate else None,
'application': {
'appid': self.application.appid,
'appname': self.application.appname,
'appdescription': self.application.appdescription,
} if self.application else None,
'version': self.appversion.version if self.appversion else None
}
def __repr__(self):
return f"<ComputerInstalledApp computer={self.computerid} app={self.appid}>"

View File

@@ -0,0 +1,68 @@
"""PXE/GE-Enforce pc-type -> ComputerType mapping (computers-plugin domain).
The imaging pipeline writes C:\\Enrollment\\pc-type.txt (the gea-shopfloor-*
taxonomy). The collector maps that to a flask ComputerType. Defaults live here;
per-site overrides live in core Settings (pctypemap_<pxetype>, category
'pctypemapping') and are editable in the Settings UI. This indirection means
the imaging taxonomy can change without code edits.
"""
from shopdb.api import Setting
# pxe pc-type -> flask ComputerType name. Defaults; overridable via settings.
DEFAULT_PCTYPE_MAP = {
'gea-shopfloor-collections': 'Shopfloor PC',
'gea-shopfloor-nocollections': 'Shopfloor PC',
'gea-shopfloor-common': 'Shopfloor PC',
'gea-shopfloor-keyence': 'Shopfloor PC',
'gea-shopfloor-cmm': 'CMM PC',
'gea-shopfloor-genspect': 'Shopfloor PC',
'gea-shopfloor-heattreat': 'Shopfloor PC',
'gea-shopfloor-waxtrace': 'Shopfloor PC',
'gea-shopfloor-display': 'Kiosk',
'gea-shopfloor-partmarker': 'Shopfloor PC',
}
# DEPRECATED settings surface: the "Collector PC Types" settings page is retired
# (GE-Enforce scope computertypeid supersedes it, ADR-012). Collector still reads
# this map, so keep the code; only the editor UI card is gone.
_SETTING_PREFIX = 'pctypemap_'
_SETTING_CATEGORY = 'pctypemapping'
# Metrology imaging pc-types: the PC itself stays a shopfloor PC, but it drives
# an attached measuring instrument. When the collector sees one of these, it
# auto-creates a MeasuringTool asset for the device and links the PC to it with
# a "controls" relationship (see ComputersPlugin._sync_measuringtool_link).
# Maps imaging pc-type -> (MeasuringToolType name, type description). The type
# is created on demand if the measuringtools plugin has not seeded it.
METROLOGY_TOOL_MAP = {
'gea-shopfloor-cmm': ('CMM', 'Coordinate measuring machine'),
'gea-shopfloor-keyence': ('Vision System', 'Optical / vision measurement system (Keyence)'),
'gea-shopfloor-genspect': ('Genspect', 'Genspect visual / borescope inspection system'),
'gea-shopfloor-waxtrace': ('Form Tracer', 'Surface / form tracing system (wax and trace)'),
}
def metrology_tool_for(pctype):
"""Return (typename, typedescription) if this pc-type drives a measuring
tool, else None."""
return METROLOGY_TOOL_MAP.get((pctype or '').strip())
def pctype_mapping():
"""Return the live pctype -> ComputerType-name map (settings over defaults)."""
mapping = dict(DEFAULT_PCTYPE_MAP)
for setting in Setting.query.filter_by(category=_SETTING_CATEGORY).all():
if setting.key.startswith(_SETTING_PREFIX):
mapping[setting.key[len(_SETTING_PREFIX):]] = setting.get_typed_value()
return mapping
def seed_pctype_settings():
"""Seed the pctypemap_<pxetype> settings from defaults (idempotent)."""
for pxetype, computertype in DEFAULT_PCTYPE_MAP.items():
key = f'{_SETTING_PREFIX}{pxetype}'
if not Setting.query.filter_by(key=key).first():
Setting.set(key, computertype, valuetype='string',
category=_SETTING_CATEGORY,
description=f'Collector maps pc-type {pxetype} to this ComputerType')

680
plugins/computers/plugin.py Normal file
View File

@@ -0,0 +1,680 @@
"""Computers plugin main class."""
import json
import logging
from pathlib import Path
from typing import List, Dict, Optional, Type
from flask import Flask, Blueprint
import click
from shopdb.plugins.base import BasePlugin, PluginMeta
from shopdb.api import db, AssetType
from .models import Computer, ComputerType, ComputerInstalledApp, AccessProtocol, ComputerAccess
from .api import computers_bp
logger = logging.getLogger(__name__)
# Marker stamped on PC->printer links this collector creates. The stale-link
# archive only touches rows carrying this label, so manually-created printer
# relationships are never removed by a collector push. Stored in the
# assetrelationships.label column (no origin column exists; see BUILD notes).
PRINTER_LINK_ORIGIN = 'collector:printers'
# Marker stamped on PC->measuringtool "controls" links this collector creates
# for metrology PCs (CMM, Keyence, Genspect, wax-and-trace). Same stale-link
# discipline as PRINTER_LINK_ORIGIN: only rows carrying this label are archived
# by a collector push, so hand-made tool links survive.
MEASURINGTOOL_LINK_ORIGIN = 'collector:measuringtool'
class ComputersPlugin(BasePlugin):
"""
Computers plugin - manages PC, server, and workstation assets.
Computers include shopfloor PCs, engineer workstations, servers, etc.
Uses the new Asset architecture with Computer extension table.
"""
def __init__(self):
self._manifest = self._load_manifest()
def _load_manifest(self) -> Dict:
"""Load plugin manifest from JSON file."""
manifestpath = Path(__file__).parent / 'manifest.json'
if manifestpath.exists():
with open(manifestpath, 'r') as f:
return json.load(f)
return {}
@property
def meta(self) -> PluginMeta:
"""Return plugin metadata."""
return PluginMeta(
name=self._manifest.get('name', 'computers'),
version=self._manifest.get('version', '1.0.0'),
description=self._manifest.get(
'description',
'Computer management for PCs, servers, and workstations'
),
author=self._manifest.get('author', 'ShopDB Team'),
dependencies=self._manifest.get('dependencies', []),
core_version=self._manifest.get('core_version', '>=1.0.0'),
api_prefix=self._manifest.get('api_prefix', '/api/computers'),
)
def get_blueprint(self) -> Optional[Blueprint]:
"""Return Flask Blueprint with API routes."""
return computers_bp
def get_models(self) -> List[Type]:
"""Return list of SQLAlchemy model classes."""
return [Computer, ComputerType, ComputerInstalledApp, AccessProtocol, ComputerAccess]
def init_app(self, app: Flask, db_instance) -> None:
"""Initialize plugin with Flask app."""
logger.info(f"Computers plugin initialized (v{self.meta.version})")
# -- ADR-006 collector contract -----------------------------------------
def get_collector_schema(self) -> Optional[Dict]:
"""Schema for the PC collector payload (matched by hostname).
Aligns with the GE-Enforce status shape (transport may change), using
the project naming convention (lowercase concatenated). The caller maps
its own field names to these.
"""
return {
'identityfield': 'hostname',
'fields': {
'hostname': {'type': 'string', 'required': True},
'machinenumber': {'type': 'string'},
'pctype': {'type': 'string'},
'pcsubtype': {'type': 'string'},
'serialnumber': {'type': 'string'},
'loggedinuser': {'type': 'string'},
'lastboottime': {'type': 'string', 'format': 'date-time'},
'lastcheckin': {'type': 'string', 'format': 'date-time'},
'ipaddress': {'type': 'string'},
'vendorname': {'type': 'string'},
'modelnumber': {'type': 'string'},
'osname': {'type': 'string'},
'installedsoftware': {
'type': 'array',
'items': {'name': 'string', 'version': 'string'},
},
# Printer identifiers reported by the GE-Enforce side, which
# runs Get-CimInstance Win32_Printer and marks the default with
# the Default flag. An identifier is the printer's windows name,
# share name, hostname, or port/IP; the collector resolves it
# flexibly to a printer asset. Both optional. Presence of either
# key drives the PC->printer relationship sync (and stale-link
# archive); absence leaves existing printer links untouched.
'defaultprinter': {
'type': 'string',
'description': ('Default printer identifier (Win32_Printer '
'with Default=true): windows name, share '
'name, hostname, or port IP.'),
},
'printers': {
'type': 'array',
'items': {'type': 'string'},
'description': ('All installed network printer identifiers '
'(Win32_Printer): windows name / share / '
'hostname / IP. Unresolved -> warning.'),
},
},
}
def apply_collector_payload(self, payload: Dict) -> Dict:
"""Idempotent upsert of a PC from a collector payload (by hostname)."""
from datetime import datetime, timezone
from shopdb.api import (
Asset, Application, Communication, CommunicationType,
Vendor, Model, OperatingSystem,
)
from .pctypemap import pctype_mapping
warnings = []
hostname = (payload.get('hostname') or '').strip()
if not hostname:
raise ValueError('hostname is required')
# Machine number is the business identifier (Asset.assetnumber). Skip
# the imaging-time placeholder '9999' and fall back to hostname.
machinenumber = (payload.get('machinenumber') or '').strip()
if machinenumber in ('', '9999'):
machinenumber = None
comp = Computer.query.filter(Computer.hostname.ilike(hostname)).first()
if not comp:
comp = (Computer.query.join(Asset, Asset.assetid == Computer.assetid)
.filter(Asset.assetnumber.ilike(hostname)).first())
action = 'updated'
if not comp:
atype = AssetType.query.filter_by(assettype='computer').first()
# statusid=1 is the first seeded asset status ("In Use"); a
# collector-discovered PC is by definition in use.
asset = Asset(assetnumber=machinenumber or hostname,
assettypeid=atype.assettypeid, statusid=1)
db.session.add(asset)
db.session.flush()
comp = Computer(assetid=asset.assetid, hostname=hostname)
db.session.add(comp)
db.session.flush()
action = 'created'
elif machinenumber and comp.asset:
comp.asset.assetnumber = machinenumber
comp.lastreporteddate = datetime.now(timezone.utc).replace(tzinfo=None)
if payload.get('lastboottime'):
try:
comp.lastboottime = datetime.fromisoformat(
payload['lastboottime'].replace('Z', '+00:00'))
except (ValueError, AttributeError):
warnings.append('lastboottime not parseable')
loggedinuser = payload.get('loggedinuser') or payload.get('currentuser')
if loggedinuser:
comp.loggedinuser = loggedinuser
if payload.get('serialnumber') and comp.asset:
comp.asset.serialnumber = payload['serialnumber']
# pc-type -> ComputerType via the configurable settings mapping.
pctype = (payload.get('pctype') or '').strip()
if pctype:
from .models import ComputerType
mapped = pctype_mapping().get(pctype)
if not mapped:
warnings.append(f'no ComputerType mapping for pctype: {pctype}')
else:
ctype = ComputerType.query.filter_by(computertype=mapped).first()
if ctype:
comp.computertypeid = ctype.computertypeid
else:
warnings.append(f'mapped ComputerType not found: {mapped}')
# Vendor / model are free vocab - create if missing.
vendorname = (payload.get('vendorname') or '').strip()
vendor = None
if vendorname:
vendor = Vendor.query.filter(Vendor.vendor.ilike(vendorname)).first()
if not vendor:
vendor = Vendor(vendor=vendorname)
db.session.add(vendor)
db.session.flush()
comp.vendorid = vendor.vendorid
modelnumber = (payload.get('modelnumber') or '').strip()
if modelnumber:
model_query = Model.query.filter(Model.modelnumber.ilike(modelnumber))
if vendor:
model_query = model_query.filter(Model.vendorid == vendor.vendorid)
model = model_query.first()
if not model:
model = Model(modelnumber=modelnumber,
vendorid=vendor.vendorid if vendor else None)
db.session.add(model)
db.session.flush()
comp.modelnumberid = model.modelnumberid
# OS is a controlled vocab - look up only, warn if unknown.
osname = (payload.get('osname') or '').strip()
if osname:
os_row = OperatingSystem.query.filter(
OperatingSystem.osname.ilike(osname)).first()
if os_row:
comp.osid = os_row.osid
else:
warnings.append(f'unknown operating system: {osname}')
if payload.get('pcsubtype'):
warnings.append('pcsubtype received but not stored (no model field)')
if payload.get('ipaddress'):
ip_comtype = CommunicationType.query.filter_by(comtype='IP').first()
primary = Communication.query.filter_by(
assetid=comp.assetid, isprimary=True).first()
if primary:
primary.ipaddress = payload['ipaddress']
elif ip_comtype:
db.session.add(Communication(
assetid=comp.assetid, comtypeid=ip_comtype.comtypeid,
ipaddress=payload['ipaddress'], isprimary=True))
for app_data in payload.get('installedsoftware', []) or []:
name = app_data.get('name')
if not name:
continue
app = Application.query.filter(Application.appname.ilike(name)).first()
if not app:
warnings.append(f'unknown application: {name}')
continue
installed = ComputerInstalledApp.query.filter_by(
computerid=comp.computerid, appid=app.appid).first()
version = app_data.get('version')
if installed:
installed.installedversion = version
installed.isactive = True
else:
db.session.add(ComputerInstalledApp(
computerid=comp.computerid, appid=app.appid,
installedversion=version))
# Printer relationship sync (only when the payload carried printer data).
printerlinks = self._sync_printer_links(comp.asset, payload, warnings)
# Measuring-tool sync: metrology PCs (CMM/Keyence/Genspect/wax-trace)
# get an attached MeasuringTool asset auto-created and linked.
measuringtoollinks = self._sync_measuringtool_link(
comp.asset, pctype, hostname, warnings)
db.session.commit()
return {
'action': action,
'assetid': comp.assetid,
'identityvalue': hostname,
'warnings': warnings,
'extra': {
'printerlinks': printerlinks,
'printerlinkcount': len(printerlinks),
'measuringtoollinks': measuringtoollinks,
'measuringtoollinkcount': len(measuringtoollinks),
},
}
# -- printer relationship sync -----------------------------------------
def _sync_printer_links(self, pcasset, payload, warnings):
"""Idempotently sync PC->printer relationships from collector printer data.
Default printer -> 'defaultprinter' (directional). Other reported
printers -> 'connectedto' (symmetric). Resolves each identifier to a
printer asset by windows name / share / hostname / asset number / name
or a communications IP. Unresolved identifiers add a warning and never
fail the push.
Stale-link archive: on each push, collector-tagged links (label ==
PRINTER_LINK_ORIGIN) whose (target, type) pair is not in the reported
desired set are set inactive. Only tagged rows are touched, so manual
links survive. Runs only when the payload carried a printer key
('defaultprinter' or 'printers'); a PC that reports without printer data
keeps its existing links. Returns the desired-link list (created + kept).
"""
from shopdb.api import (
AssetRelationship, RelationshipType, Asset, Communication)
has_default = 'defaultprinter' in payload
has_list = 'printers' in payload
if not has_default and not has_list:
return []
try:
from plugins.printers.models import Printer
except ImportError:
warnings.append('printers plugin unavailable; printer links skipped')
return []
dp_type = RelationshipType.query.filter_by(
relationshiptype='defaultprinter').first()
ct_type = RelationshipType.query.filter_by(
relationshiptype='connectedto').first()
if not dp_type or not ct_type:
warnings.append('printer relationship types missing; '
'run flask seed reference-data')
return []
def resolve(identifier):
# first match wins: printer text identity, then a printer IP.
ident = (identifier or '').strip()
if not ident:
return None
printer = (
Printer.query.join(Asset, Asset.assetid == Printer.assetid)
.filter(Asset.isactive == True)
.filter(db.or_(
Printer.windowsname.ilike(ident),
Printer.hostname.ilike(ident),
Printer.sharename.ilike(ident),
Asset.assetnumber.ilike(ident),
Asset.name.ilike(ident),
)).first())
if printer:
return printer.asset
comm = (
db.session.query(Communication)
.join(Printer, Printer.assetid == Communication.assetid)
.filter(Communication.ipaddress == ident)
.first())
if comm:
return db.session.get(Asset, comm.assetid)
return None
pcid = pcasset.assetid
desired = set() # (targetassetid, relationshiptypeid) to keep
printerlinks = []
default_id = None
default_ident = (payload.get('defaultprinter') or '').strip()
if default_ident:
target = resolve(default_ident)
if target:
default_id = target.assetid
desired.add((default_id, dp_type.relationshiptypeid))
self._sync_one(pcid, default_id, dp_type)
printerlinks.append({'assetid': default_id,
'relationshiptype': 'defaultprinter'})
else:
warnings.append(f'unresolved default printer: {default_ident}')
for ident in payload.get('printers') or []:
target = resolve(ident)
if not target:
warnings.append(f'unresolved printer: {ident}')
continue
if target.assetid == default_id:
continue # already the default link
desired.add((target.assetid, ct_type.relationshiptypeid))
self._sync_one(pcid, target.assetid, ct_type)
printerlinks.append({'assetid': target.assetid,
'relationshiptype': 'connectedto'})
# Archive collector-tagged links no longer reported (manual links, with
# a NULL/other label, are never matched here).
collector_rows = AssetRelationship.query.filter(
AssetRelationship.sourceassetid == pcid,
AssetRelationship.relationshiptypeid.in_(
[dp_type.relationshiptypeid, ct_type.relationshiptypeid]),
AssetRelationship.isactive == True,
AssetRelationship.label == PRINTER_LINK_ORIGIN,
).all()
for rel in collector_rows:
if (rel.targetassetid, rel.relationshiptypeid) not in desired:
rel.isactive = False
return printerlinks
def _sync_one(self, pcid, printerid, reltype):
"""Reactivate or create one collector PC->printer link (idempotent)."""
from shopdb.api import AssetRelationship
existing = AssetRelationship.query.filter_by(
sourceassetid=pcid, targetassetid=printerid,
relationshiptypeid=reltype.relationshiptypeid).first()
if existing:
# do not re-stamp label: a pre-existing manual row stays manual.
if not existing.isactive:
existing.isactive = True
return existing
rel = AssetRelationship(
sourceassetid=pcid, targetassetid=printerid,
relationshiptypeid=reltype.relationshiptypeid,
label=PRINTER_LINK_ORIGIN)
db.session.add(rel)
return rel
# -- measuring-tool sync -----------------------------------------------
def _sync_measuringtool_link(self, pcasset, pctype, hostname, warnings):
"""Auto-create + link the MeasuringTool a metrology PC drives.
A CMM / Keyence / Genspect / wax-and-trace imaging pc-type means the
shopfloor PC controls an attached measuring instrument. This creates
that instrument once as a MeasuringTool asset and a directional
PC->tool 'controls' relationship, tagged MEASURINGTOOL_LINK_ORIGIN so
it is idempotent and self-archiving. The PC's own ComputerType is left
alone (it stays a shopfloor PC). A non-metrology pc-type archives any
collector-created tool link (e.g. a PC re-imaged to another type) but
never deletes the tool asset, which may carry calibration history.
Returns the desired-link list.
"""
from shopdb.api import AssetRelationship, RelationshipType, Asset
from .pctypemap import metrology_tool_for
tool_spec = metrology_tool_for(pctype)
controls = RelationshipType.query.filter_by(
relationshiptype='controls').first()
if not controls:
# No 'controls' type => no tool links can exist. Only a problem for a
# metrology PC that needs one; stay quiet for ordinary PCs.
if tool_spec:
warnings.append("'controls' relationship type missing; "
'run flask seed reference-data')
return []
# Collector-created tool links already on this PC (active or archived).
existing = AssetRelationship.query.filter(
AssetRelationship.sourceassetid == pcasset.assetid,
AssetRelationship.relationshiptypeid == controls.relationshiptypeid,
AssetRelationship.label == MEASURINGTOOL_LINK_ORIGIN,
).all()
if not tool_spec:
# Not a metrology PC: archive any collector-created tool link.
for rel in existing:
if rel.isactive:
rel.isactive = False
return []
try:
from plugins.measuringtools.models import MeasuringTool
except ImportError:
warnings.append('measuringtools plugin unavailable; '
'tool link skipped')
return []
typename, typedescription = tool_spec
tooltype = self._ensure_measuringtool_type(typename, typedescription)
# Reuse any prior collector link (reactivate + retype) before creating,
# so a re-metrology PC never duplicates the tool asset.
reuse = next((rel for rel in existing if rel.isactive), None) \
or (existing[0] if existing else None)
if reuse:
reuse.isactive = True
toolasset = db.session.get(Asset, reuse.targetassetid)
if toolasset and toolasset.measuringtool and tooltype:
toolasset.measuringtool.measuringtooltypeid = \
tooltype.measuringtooltypeid
targetid = reuse.targetassetid
else:
mt_assettype = AssetType.query.filter_by(
assettype='measuring_tool').first()
if not mt_assettype:
warnings.append('measuring_tool asset type missing; '
'tool link skipped')
return []
suffix = (pctype or '').split('-')[-1].upper()
baseasset = pcasset.assetnumber or hostname
toolasset = Asset(
assetnumber=f'{baseasset}-{suffix}',
name=f'{typename} ({hostname})',
assettypeid=mt_assettype.assettypeid,
statusid=1)
db.session.add(toolasset)
db.session.flush()
db.session.add(MeasuringTool(
assetid=toolasset.assetid,
measuringtooltypeid=tooltype.measuringtooltypeid
if tooltype else None))
db.session.add(AssetRelationship(
sourceassetid=pcasset.assetid,
targetassetid=toolasset.assetid,
relationshiptypeid=controls.relationshiptypeid,
label=MEASURINGTOOL_LINK_ORIGIN))
targetid = toolasset.assetid
# Only one tool link is desired; archive any other collector rows.
for rel in existing:
if rel is not reuse and rel.isactive:
rel.isactive = False
return [{'assetid': targetid, 'relationshiptype': 'controls',
'measuringtooltype': typename}]
def _ensure_measuringtool_type(self, name, description):
"""Find or create a MeasuringToolType (metrology types are not in the
measuringtools starter seed)."""
from plugins.measuringtools.models import MeasuringToolType
tooltype = MeasuringToolType.query.filter_by(name=name).first()
if not tooltype:
tooltype = MeasuringToolType(name=name, description=description)
db.session.add(tooltype)
db.session.flush()
return tooltype
def on_install(self, app: Flask) -> None:
"""Called when plugin is installed."""
with app.app_context():
self._ensure_asset_type()
self._ensure_computer_types()
from .pctypemap import seed_pctype_settings
seed_pctype_settings()
db.session.commit()
logger.info("Computers plugin installed")
def _ensure_asset_type(self) -> None:
"""Ensure computer asset type exists."""
existing = AssetType.query.filter_by(assettype='computer').first()
if not existing:
at = AssetType(
assettype='computer',
pluginname='computers',
tablename='computers',
description='PCs, servers, and workstations',
icon='desktop'
)
db.session.add(at)
logger.debug("Created asset type: computer")
db.session.commit()
def _ensure_computer_types(self) -> None:
"""Ensure basic computer types exist."""
computer_types = [
('Shopfloor PC', 'PC located on the shop floor for machine operation', 'desktop'),
('Engineer Workstation', 'Engineering workstation for CAD/CAM work', 'laptop'),
('CMM PC', 'PC dedicated to CMM operation', 'desktop'),
('Server', 'Server system', 'server'),
('Kiosk', 'Kiosk or info display PC', 'tv'),
('Laptop', 'Laptop computer', 'laptop'),
('Virtual Machine', 'Virtual machine', 'cloud'),
('Other', 'Other computer type', 'desktop'),
]
for name, description, icon in computer_types:
existing = ComputerType.query.filter_by(computertype=name).first()
if not existing:
ct = ComputerType(
computertype=name,
description=description,
icon=icon
)
db.session.add(ct)
logger.debug(f"Created computer type: {name}")
db.session.commit()
def on_uninstall(self, app: Flask) -> None:
"""Called when plugin is uninstalled."""
logger.info("Computers plugin uninstalled")
def get_cli_commands(self) -> List:
"""Return CLI commands for this plugin."""
@click.group('computers')
def computerscli():
"""Computers plugin commands."""
pass
@computerscli.command('list-types')
def list_types():
"""List all computer types."""
from flask import current_app
with current_app.app_context():
types = ComputerType.query.filter_by(isactive=True).all()
if not types:
click.echo('No computer types found.')
return
click.echo('Computer Types:')
for t in types:
click.echo(f" [{t.computertypeid}] {t.computertype}")
@computerscli.command('stats')
def stats():
"""Show computer statistics."""
from flask import current_app
from shopdb.api import Asset
with current_app.app_context():
total = db.session.query(Computer).join(Asset).filter(
Asset.isactive == True
).count()
click.echo(f"Total active computers: {total}")
# Shopfloor count (by the Shopfloor computer type)
sf = ComputerType.query.filter_by(computertype='Shopfloor').first()
shopfloor = db.session.query(Computer).join(Asset).filter(
Asset.isactive == True,
Computer.computertypeid == (sf.computertypeid if sf else -1)
).count()
click.echo(f" Shopfloor PCs: {shopfloor}")
click.echo(f" Other: {total - shopfloor}")
@computerscli.command('find')
@click.argument('hostname')
def find_by_hostname(hostname):
"""Find a computer by hostname."""
from flask import current_app
with current_app.app_context():
comp = Computer.query.filter(
Computer.hostname.ilike(f'%{hostname}%')
).first()
if not comp:
click.echo(f'No computer found matching hostname: {hostname}')
return
click.echo(f'Found: {comp.hostname}')
click.echo(f' Asset: {comp.asset.assetnumber}')
click.echo(f' Type: {comp.computertype.computertype if comp.computertype else "N/A"}')
click.echo(f' OS: {comp.operatingsystem.osname if comp.operatingsystem else "N/A"}')
click.echo(f' Logged in: {comp.loggedinuser or "N/A"}')
return [computerscli]
def get_dashboard_widgets(self) -> List[Dict]:
"""Return dashboard widget definitions."""
return [
{
'name': 'Computer Status',
'component': 'ComputerStatusWidget',
'endpoint': '/api/computers/dashboard/summary',
'size': 'medium',
'position': 6,
},
]
def get_navigation_items(self) -> List[Dict]:
"""Return navigation menu items."""
return [
{
'name': 'PCs',
'icon': 'desktop',
'route': '/pcs',
'position': 15,
},
]
def get_permissions(self) -> List:
"""Return the RBAC permissions this plugin owns."""
return [
('computers.view', 'View computers', 'computers'),
('computers.create', 'Create computers', 'computers'),
('computers.edit', 'Edit computers', 'computers'),
('computers.delete', 'Delete computers', 'computers'),
]