Files
shopdb-flask/shopdb/core/models/setting.py
cproudlock b8c22244a1
Some checks failed
CI / backend (push) Failing after 2s
CI / naming (push) Successful in 1s
CI / frontend (push) Successful in 7s
Multi-site distribution readiness: settings-driven site config, security closeout, release engineering, v0.5.0
Make the app distributable to other GE Aerospace sites (one self-hosted
instance per site, ADR-004). GE values remain the shipped defaults; every
site-specific behavior is now a Setting an admin can change in the UI.

Settings-driven site config:
- Branding: site/QR/badge logos, favicon, primary color (upload endpoints
  mirror the map-blueprint pattern; new Settings > Branding section).
- ServiceNow: search/incident/change URL templates ({ticket}), ticket
  prefixes, enable toggle. Defaults point at the current
  geaerospaceqa.service-now.com global search. Disabled = plain-text tickets.
- Employee-id regex (employeeid_pattern), printer hostname template,
  QR label targets (qr_target_printer / qr_target_usb, blank = asset page,
  else URL template with placeholders), usb_label_style (barcode|qr).
- West Jefferson floor-plan PNGs removed from the tree; generic placeholder
  ships as the map default and sites upload their own blueprint.

Security closeout:
- dashboarddefaults writes now require admin.
- Collector: generic error messages (no str(exc) leak); API key accepted
  via X-API-Key header only (BREAKING: querystring api_key removed).
- IP-based login rate limiting (AUTH_RATELIMIT_* knobs) atop account lockout.
- Setting.set() creation race fixed (IntegrityError retry).

Release engineering and docs:
- __version__ 0.5.0 (distinct from __contract_version__, ADR-007),
  CHANGELOG.md, Gitea Actions CI config, frontend version aligned.
- One wizard-first install story across README/DEPLOY; new CONFIG.md,
  UPGRADE.md, BACKUP-RESTORE.md; CLAUDE.md and ROADMAP de-staled.
- Dockerfile multi-stage build now bundles the frontend; compose binds
  MySQL to 127.0.0.1; stale database/schema.sql and one-off SQL removed.

Debt and fixes:
- .query.get() -> db.session.get() sweep; datetime.utcnow() removed
  (naive-UTC via timezone-aware now); users.py on authz decorators.
- Fixed 4 stale tests (slides feed shape, shopfloor splitperemployee,
  plugin contract purity) and the USB label page field mapping (both usb
  modes emit the cmmc shape: device_id/device_desc).
- Health endpoint reports the real version.

248 tests pass; naming/style check green; frontend builds; fresh-DB
flask db upgrade + seeds verified; QR targets verified by decoding
rendered codes.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 15:02:07 -04:00

103 lines
3.8 KiB
Python

"""System settings model for key-value configuration storage."""
from datetime import datetime, timezone
from sqlalchemy.exc import IntegrityError
from shopdb.extensions import db
def _utcnow():
"""Naive UTC now for column defaults (matches the app's naive datetime cols)."""
return datetime.now(timezone.utc).replace(tzinfo=None)
class Setting(db.Model):
"""
Key-value store for system settings.
Settings can be managed via the admin UI and are cached
for performance.
"""
__tablename__ = 'settings'
settingid = db.Column(db.Integer, primary_key=True, autoincrement=True)
key = db.Column(db.String(100), unique=True, nullable=False, index=True)
value = db.Column(db.Text, nullable=True)
valuetype = db.Column(db.String(20), default='string') # string, boolean, integer, json
category = db.Column(db.String(50), default='general') # For grouping in UI
description = db.Column(db.String(255), nullable=True)
createddate = db.Column(db.DateTime, default=_utcnow)
modifieddate = db.Column(db.DateTime, default=_utcnow, onupdate=_utcnow)
def to_dict(self):
return {
'settingid': self.settingid,
'key': self.key,
'value': self.get_typed_value(),
'valuetype': self.valuetype,
'category': self.category,
'description': self.description,
'createddate': self.createddate.isoformat() + 'Z' if self.createddate else None,
'modifieddate': self.modifieddate.isoformat() + 'Z' if self.modifieddate else None,
}
def get_typed_value(self):
"""Return value converted to its proper type."""
if self.value is None:
return None
if self.valuetype == 'boolean':
return self.value.lower() in ('true', '1', 'yes')
if self.valuetype == 'integer':
try:
return int(self.value)
except (ValueError, TypeError):
return 0
return self.value
@classmethod
def get(cls, key: str, default=None):
"""Get a setting value by key."""
setting = cls.query.filter_by(key=key).first()
if setting:
return setting.get_typed_value()
return default
@staticmethod
def _stringify(value):
"""Convert a value to its stored string form."""
if isinstance(value, bool):
return 'true' if value else 'false'
return str(value) if value is not None else None
@classmethod
def set(cls, key: str, value, valuetype: str = 'string', category: str = 'general', description: str = None):
"""Set a setting value, creating if it doesn't exist.
Handles the create race: two concurrent callers can both find no row and
both try to INSERT the same unique key. The loser's commit raises
IntegrityError; we roll back, re-fetch the row the winner created, and
apply our value to it.
"""
setting = cls.query.filter_by(key=key).first()
if setting:
setting.value = cls._stringify(value)
db.session.commit()
return setting
setting = cls(key=key, valuetype=valuetype, category=category,
description=description, value=cls._stringify(value))
db.session.add(setting)
try:
db.session.commit()
return setting
except IntegrityError:
db.session.rollback()
# Another transaction inserted this key first; update that row.
setting = cls.query.filter_by(key=key).first()
if setting is None:
raise
setting.value = cls._stringify(value)
db.session.commit()
return setting