Jun 27 MT-7

This commit is contained in:
2026-06-27 20:04:37 -04:00
parent 7505e82ab4
commit b46c1a7dd5
8 changed files with 864 additions and 1 deletions
+24
View File
@@ -97,6 +97,17 @@ def create_app(config_name='default'):
from flask_wtf.csrf import generate_csrf
app.jinja_env.globals['csrf_token'] = generate_csrf
app.jinja_env.globals['enumerate'] = enumerate
def _hex_to_rgb(hex_color):
"""Convert #rrggbb → 'r,g,b' string for CSS rgb() / Bootstrap var."""
h = hex_color.lstrip('#')
if len(h) != 6:
return '26,86,219'
try:
return ','.join(str(int(h[i:i+2], 16)) for i in (0, 2, 4))
except ValueError:
return '26,86,219'
app.jinja_env.filters['hex_to_rgb'] = _hex_to_rgb
# SLA helpers available in all templates
from app.utils.sla import sla_status, sla_deadline, sla_hours_remaining, SLA_HOURS
@@ -138,6 +149,17 @@ def create_app(config_name='default'):
except Exception:
pass
return {'unread_notification_count': 0, 'pending_verification_count': 0, 'open_support_tickets_count': 0}
@app.context_processor
def inject_tenant_branding():
"""MT-7: push tenant branding into every template as `tenant_branding`."""
try:
from app.models.tenant_settings import TenantSettings
settings = TenantSettings.get_or_default()
return {'tenant_branding': settings}
except Exception:
pass
return {'tenant_branding': None}
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
@@ -151,6 +173,7 @@ def create_app(config_name='default'):
from app.routes import support # Support chat + admin tickets
from app.routes import broadcast # Admin broadcast messages
from app.routes import devices # Admin device management
from app.routes import tenant_settings # MT-7 — tenant self-service
app.register_blueprint(auth.bp)
app.register_blueprint(dashboard.bp)
@@ -167,6 +190,7 @@ def create_app(config_name='default'):
app.register_blueprint(support.bp)
app.register_blueprint(broadcast.bp)
app.register_blueprint(devices.bp)
app.register_blueprint(tenant_settings.bp)
# ── Mobile API (Phase 7 / Phase A / Phase B / Phase C) ───────────────────
# The /api/v1 blueprint group uses JWT Bearer tokens — no CSRF cookies needed.
+53
View File
@@ -0,0 +1,53 @@
"""
app/models/tenant_settings.py
------------------------------
Per-tenant branding / self-service settings (MT-7).
One row per tenant DB. Created on first save; reads fall back to defaults
when no row exists so tenant-zero needs zero data migration.
"""
from app import db
from app.utils.time_utils import now_eastern
class TenantSettings(db.Model):
__tablename__ = 'tenant_settings'
id = db.Column(db.Integer, primary_key=True)
company_name = db.Column(db.String(150), nullable=True)
logo_url = db.Column(db.String(500), nullable=True)
primary_color = db.Column(db.String(7), nullable=False, default='#1a56db')
accent_color = db.Column(db.String(7), nullable=False, default='#16a34a')
support_email = db.Column(db.String(255), nullable=True)
updated_at = db.Column(db.DateTime, nullable=False, default=now_eastern)
updated_by = db.Column(db.Integer, db.ForeignKey('users.id', ondelete='SET NULL'),
nullable=True)
# ── Defaults ──────────────────────────────────────────────────────────────
DEFAULTS = {
'company_name': 'Janitorial QC',
'logo_url': None,
'primary_color': '#1a56db',
'accent_color': '#16a34a',
'support_email': None,
}
@classmethod
def get_or_default(cls):
"""Return the settings row, or a default-filled instance (not persisted)."""
row = cls.query.first()
if row is not None:
return row
# Return a transient default so templates always get a real object.
obj = cls()
for k, v in cls.DEFAULTS.items():
setattr(obj, k, v)
return obj
@property
def display_name(self):
return self.company_name or self.DEFAULTS['company_name']
def __repr__(self):
return f'<TenantSettings company={self.company_name}>'
+332
View File
@@ -0,0 +1,332 @@
"""
app/routes/tenant_settings.py
------------------------------
Tenant self-service settings (MT-7). Admin-only blueprint at /settings/.
Routes
------
GET /settings/ → redirect to /settings/branding
GET /settings/branding → branding form (company name, logo, colours)
POST /settings/branding → save branding
GET /settings/plan → read-only plan + live quota usage
GET /settings/domains → domain list + add-custom-domain form
POST /settings/domains/request → add an unverified custom domain request
POST /settings/domains/<id>/delete → remove a non-primary custom domain request
"""
import logging
import os
import re
from flask import (
Blueprint, render_template, redirect, url_for,
request, flash, current_app,
)
from flask_login import login_required, current_user
from app import db
from app.models.tenant_settings import TenantSettings
from app.utils.decorators import admin_required
from app.utils.audit import log_action, ACTION_UPDATE, ACTION_CREATE, ACTION_DELETE
from app.utils.time_utils import now_eastern
logger = logging.getLogger(__name__)
bp = Blueprint('tenant_settings', __name__, url_prefix='/settings')
_HEX_RE = re.compile(r'^#[0-9a-fA-F]{6}$')
_DOMAIN_RE = re.compile(
r'^(?:[a-z0-9](?:[a-z0-9\-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$'
)
# ── helpers ───────────────────────────────────────────────────────────────────
def _save_logo(file_obj):
"""Save uploaded logo to static/uploads/logos/; return relative URL or None."""
if not file_obj or not file_obj.filename:
return None
allowed = {'png', 'jpg', 'jpeg', 'gif', 'svg', 'webp'}
ext = file_obj.filename.rsplit('.', 1)[-1].lower()
if ext not in allowed:
return None
# Read magic bytes — reject non-image files (SVG is text, skip magic check)
if ext != 'svg':
header = file_obj.read(8)
file_obj.seek(0)
magic = {
b'\xff\xd8\xff': 'jpg',
b'\x89PNG': 'png',
b'GIF87a': 'gif',
b'GIF89a': 'gif',
b'RIFF': 'webp',
}
if not any(header.startswith(m) for m in magic):
return None
import secrets
logos_dir = os.path.join(current_app.config['UPLOAD_FOLDER'], 'logos')
os.makedirs(logos_dir, exist_ok=True)
filename = f'{secrets.token_hex(12)}.{ext}'
file_obj.save(os.path.join(logos_dir, filename))
return f'uploads/logos/{filename}'
def _mt_enabled():
return current_app.config.get('MULTI_TENANT_ENABLED', False)
# ── root redirect ─────────────────────────────────────────────────────────────
@bp.route('/')
@login_required
@admin_required
def index():
return redirect(url_for('tenant_settings.branding'))
# ── branding ──────────────────────────────────────────────────────────────────
@bp.route('/branding', methods=['GET', 'POST'])
@login_required
@admin_required
def branding():
from flask import g
# Feature gate: branding is only available on Pro/Enterprise.
# Soft check — show the form but warn if not on a branding plan.
branding_allowed = True
if _mt_enabled():
tenant = getattr(g, 'tenant', None)
if tenant is not None:
branding_allowed = tenant.allow_branding
settings = TenantSettings.get_or_default()
if request.method == 'POST':
if not branding_allowed:
flash('Branding customisation requires a Pro or Enterprise plan.', 'warning')
return redirect(url_for('tenant_settings.branding'))
company_name = request.form.get('company_name', '').strip()[:150] or None
primary_color = request.form.get('primary_color', '').strip()
accent_color = request.form.get('accent_color', '').strip()
support_email = request.form.get('support_email', '').strip()[:255] or None
if primary_color and not _HEX_RE.match(primary_color):
flash('Primary colour must be a valid hex code (e.g. #1a56db).', 'danger')
return render_template('tenant_settings/branding.html',
settings=settings, branding_allowed=branding_allowed)
if accent_color and not _HEX_RE.match(accent_color):
flash('Accent colour must be a valid hex code (e.g. #16a34a).', 'danger')
return render_template('tenant_settings/branding.html',
settings=settings, branding_allowed=branding_allowed)
# Logo upload (optional)
logo_file = request.files.get('logo')
new_logo_url = _save_logo(logo_file)
# Upsert: one row only
row = TenantSettings.query.first()
if row is None:
row = TenantSettings()
db.session.add(row)
row.company_name = company_name
row.primary_color = primary_color or '#1a56db'
row.accent_color = accent_color or '#16a34a'
row.support_email = support_email
if new_logo_url:
row.logo_url = new_logo_url
elif request.form.get('clear_logo'):
row.logo_url = None
row.updated_at = now_eastern()
row.updated_by = current_user.id
db.session.commit()
log_action(ACTION_UPDATE, 'TenantSettings', row.id, 'branding',
f'company_name={company_name}')
flash('Branding settings saved.', 'success')
return redirect(url_for('tenant_settings.branding'))
return render_template('tenant_settings/branding.html',
settings=settings, branding_allowed=branding_allowed)
# ── plan + usage ──────────────────────────────────────────────────────────────
@bp.route('/plan')
@login_required
@admin_required
def plan():
from flask import g
plan_info = None
quota_usage = {}
if _mt_enabled():
tenant = getattr(g, 'tenant', None)
if tenant is not None:
from control.base import control_session
from control.models import Plan
with control_session() as s:
p = s.get(Plan, tenant.plan_id)
if p:
plan_info = {
'name': p.name,
'code': p.code,
'max_users': p.max_users,
'max_facilities': p.max_facilities,
'max_inspections_month': p.max_inspections_month,
'max_issues_month': p.max_issues_month,
'allow_mobile_api': p.allow_mobile_api,
'allow_scheduled_reports': p.allow_scheduled_reports,
'allow_branding': p.allow_branding,
'allow_custom_domain': p.allow_custom_domain,
}
# Live counts (tenant DB)
from app.tenancy.quota import (
count_active_users, count_active_facilities,
count_inspections_this_month, count_issues_this_month,
)
try:
quota_usage = {
'users': count_active_users(),
'facilities': count_active_facilities(),
'inspections': count_inspections_this_month(),
'issues': count_issues_this_month(),
}
except Exception as exc:
logger.error('tenant_settings.plan: quota count failed: %s', exc)
return render_template('tenant_settings/plan.html',
plan_info=plan_info, quota_usage=quota_usage)
# ── custom domains ────────────────────────────────────────────────────────────
@bp.route('/domains')
@login_required
@admin_required
def domains():
from flask import g
domain_allowed = False
tenant_domains = []
tenant_slug = None
if _mt_enabled():
tenant = getattr(g, 'tenant', None)
if tenant is not None:
domain_allowed = tenant.allow_custom_domain
tenant_slug = tenant.slug
from control.base import control_session
from control.models import TenantDomain
with control_session() as s:
rows = (s.query(TenantDomain)
.filter_by(tenant_id=tenant.id)
.order_by(TenantDomain.id)
.all())
tenant_domains = [
{
'id': d.id,
'domain': d.domain,
'kind': d.kind,
'is_primary': d.is_primary,
'verified': d.verified,
'tls_status': d.tls_status,
'verification_token': d.verification_token,
}
for d in rows
]
return render_template('tenant_settings/domains.html',
domain_allowed=domain_allowed,
tenant_domains=tenant_domains,
tenant_slug=tenant_slug,
base_domain=os.environ.get('TENANT_BASE_DOMAIN', 'jqc.app'))
@bp.route('/domains/request', methods=['POST'])
@login_required
@admin_required
def request_domain():
from flask import g
if not _mt_enabled():
flash('Custom domains require multi-tenancy to be enabled.', 'warning')
return redirect(url_for('tenant_settings.domains'))
tenant = getattr(g, 'tenant', None)
if tenant is None or not tenant.allow_custom_domain:
flash('Custom domains are not available on your current plan.', 'warning')
return redirect(url_for('tenant_settings.domains'))
raw = (request.form.get('domain') or '').strip().lower()
if not raw or not _DOMAIN_RE.match(raw):
flash('Enter a valid domain name (e.g. jqc.acme.com).', 'danger')
return redirect(url_for('tenant_settings.domains'))
import secrets as _secrets
from control.base import control_session
from control.models import TenantDomain
with control_session() as s:
existing = s.query(TenantDomain).filter_by(domain=raw).first()
if existing:
flash(f'{raw} is already registered.', 'warning')
return redirect(url_for('tenant_settings.domains'))
token = _secrets.token_hex(24)
s.add(TenantDomain(
tenant_id=tenant.id,
domain=raw,
kind='custom',
is_primary=False,
verified=False,
verification_token=token,
tls_status='pending',
created_at=now_eastern(),
))
log_action(ACTION_CREATE, 'TenantDomain', None, raw,
f'tenant_id={tenant.id} requested custom domain')
logger.info('SETTINGS | domain_request | tenant=%s domain=%s', tenant.slug, raw)
flash(
f'Domain {raw} added. Add the DNS TXT record shown below to verify ownership.',
'success',
)
return redirect(url_for('tenant_settings.domains'))
@bp.route('/domains/<int:domain_id>/delete', methods=['POST'])
@login_required
@admin_required
def delete_domain(domain_id):
from flask import g
if not _mt_enabled():
flash('Multi-tenancy not enabled.', 'warning')
return redirect(url_for('tenant_settings.domains'))
tenant = getattr(g, 'tenant', None)
if tenant is None:
flash('Tenant not resolved.', 'danger')
return redirect(url_for('tenant_settings.domains'))
from control.base import control_session
from control.models import TenantDomain
with control_session() as s:
d = s.get(TenantDomain, domain_id)
if d is None or d.tenant_id != tenant.id:
flash('Domain not found.', 'danger')
return redirect(url_for('tenant_settings.domains'))
if d.is_primary:
flash('Cannot remove the primary subdomain.', 'danger')
return redirect(url_for('tenant_settings.domains'))
if d.kind != 'custom':
flash('Only custom domain requests can be removed here.', 'danger')
return redirect(url_for('tenant_settings.domains'))
domain_str = d.domain
s.delete(d)
log_action(ACTION_DELETE, 'TenantDomain', domain_id, domain_str)
flash(f'Domain {domain_str} removed.', 'success')
return redirect(url_for('tenant_settings.domains'))
+26 -1
View File
@@ -13,6 +13,18 @@
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&display=swap">
<link rel="stylesheet" href="{{ url_for('static', filename='css/theme.css') }}">
<link rel="stylesheet" href="{{ url_for('static', filename='css/ipad_responsive.css') }}">
{% if tenant_branding %}
<style>
:root {
--bs-primary: {{ tenant_branding.primary_color or '#1a56db' }};
--bs-primary-rgb: {{ tenant_branding.primary_color|hex_to_rgb if tenant_branding.primary_color else '26,86,219' }};
--jqc-accent: {{ tenant_branding.accent_color or '#16a34a' }};
}
.bg-primary { background-color: {{ tenant_branding.primary_color or '#1a56db' }} !important; }
.btn-primary { background-color: {{ tenant_branding.primary_color or '#1a56db' }} !important;
border-color: {{ tenant_branding.primary_color or '#1a56db' }} !important; }
</style>
{% endif %}
{% block extra_css %}{% endblock %}
<style>
/* ── Notification bell styles ── */
@@ -65,7 +77,14 @@
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
<div class="container-fluid">
<a class="navbar-brand" href="{{ url_for('dashboard.index') }}">
<i class="bi bi-clipboard-check"></i> Janitorial QC
{% if tenant_branding and tenant_branding.logo_url %}
<img src="{{ url_for('static', filename=tenant_branding.logo_url) }}"
alt="{{ tenant_branding.display_name }}"
style="max-height:32px; border-radius:4px; margin-right:.35rem;">
{% else %}
<i class="bi bi-clipboard-check"></i>
{% endif %}
{{ tenant_branding.display_name if tenant_branding else 'Janitorial QC' }}
</a>
<!-- ── Bell + toggler always visible on mobile/tablet ── -->
<div class="d-flex align-items-center gap-2 ms-auto me-2 d-lg-none">
@@ -214,6 +233,12 @@
<i class="bi bi-tablet"></i> Devices
</a>
</li>
<li>
<a class="dropdown-item {{ 'active' if request.endpoint and request.endpoint.startswith('tenant_settings.') else '' }}"
href="{{ url_for('tenant_settings.branding') }}">
<i class="bi bi-gear me-1"></i> Workspace Settings
</a>
</li>
{% endif %}
</ul>
<ul class="navbar-nav align-items-center">
+156
View File
@@ -0,0 +1,156 @@
{% extends "base.html" %}
{% block title %}Branding — Settings{% endblock %}
{% block content %}
<div class="d-flex justify-content-between align-items-center mb-3">
<h4 class="mb-0"><i class="bi bi-palette me-2"></i>Branding</h4>
<div class="btn-group btn-group-sm">
<a href="{{ url_for('tenant_settings.branding') }}" class="btn btn-primary">Branding</a>
<a href="{{ url_for('tenant_settings.plan') }}" class="btn btn-outline-secondary">Plan &amp; Usage</a>
<a href="{{ url_for('tenant_settings.domains') }}" class="btn btn-outline-secondary">Domains</a>
</div>
</div>
{% if not branding_allowed %}
<div class="alert alert-warning">
<i class="bi bi-lock me-1"></i>
Branding customisation is available on <strong>Pro</strong> and <strong>Enterprise</strong> plans.
Changes below won't take effect until you upgrade.
</div>
{% endif %}
<div class="row">
<div class="col-lg-7">
<div class="card border-0 shadow-sm">
<div class="card-body">
<form method="POST" action="{{ url_for('tenant_settings.branding') }}" enctype="multipart/form-data">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<div class="mb-3">
<label class="form-label fw-semibold">Company / Workspace Name</label>
<input type="text" name="company_name" class="form-control"
value="{{ settings.company_name or '' }}" maxlength="150"
placeholder="e.g. Acme Janitorial">
<div class="form-text">Shown in the navbar and email footers.</div>
</div>
<div class="mb-3">
<label class="form-label fw-semibold">Logo</label>
{% if settings.logo_url %}
<div class="mb-2">
<img src="{{ url_for('static', filename=settings.logo_url) }}"
alt="Current logo" style="max-height:48px; border-radius:6px;">
<div class="form-check mt-1">
<input class="form-check-input" type="checkbox" name="clear_logo" id="clear_logo">
<label class="form-check-label text-muted small" for="clear_logo">Remove current logo</label>
</div>
</div>
{% endif %}
<input type="file" name="logo" class="form-control"
accept=".png,.jpg,.jpeg,.gif,.svg,.webp">
<div class="form-text">PNG, JPG, SVG or WebP. Displayed at 40px height in the navbar.</div>
</div>
<div class="row g-3 mb-3">
<div class="col-6">
<label class="form-label fw-semibold">Primary Colour</label>
<div class="input-group">
<input type="color" name="primary_color" class="form-control form-control-color"
value="{{ settings.primary_color or '#1a56db' }}" title="Primary colour">
<input type="text" class="form-control font-monospace"
value="{{ settings.primary_color or '#1a56db' }}"
pattern="^#[0-9a-fA-F]{6}$"
oninput="this.previousElementSibling.value=this.value"
id="primary_color_text">
</div>
<div class="form-text">Navbar background.</div>
</div>
<div class="col-6">
<label class="form-label fw-semibold">Accent Colour</label>
<div class="input-group">
<input type="color" name="accent_color" class="form-control form-control-color"
value="{{ settings.accent_color or '#16a34a' }}" title="Accent colour">
<input type="text" class="form-control font-monospace"
value="{{ settings.accent_color or '#16a34a' }}"
pattern="^#[0-9a-fA-F]{6}$"
oninput="this.previousElementSibling.value=this.value"
id="accent_color_text">
</div>
<div class="form-text">Buttons and highlights.</div>
</div>
</div>
<div class="mb-4">
<label class="form-label fw-semibold">Support Email</label>
<input type="email" name="support_email" class="form-control"
value="{{ settings.support_email or '' }}"
placeholder="support@yourcompany.com">
<div class="form-text">Shown to users on the support page.</div>
</div>
<button type="submit" class="btn btn-primary" {{ 'disabled' if not branding_allowed }}>
<i class="bi bi-check-lg me-1"></i> Save Branding
</button>
</form>
</div>
</div>
</div>
<div class="col-lg-5 mt-3 mt-lg-0">
<div class="card border-0 shadow-sm">
<div class="card-header bg-white py-2">
<span class="fw-semibold" style="font-size:.9rem;">Preview</span>
</div>
<div class="card-body p-0">
<nav class="navbar navbar-dark px-3 py-2" id="preview-navbar"
style="background-color: {{ settings.primary_color or '#1a56db' }}; border-radius:0 0 6px 6px;">
{% if settings.logo_url %}
<img src="{{ url_for('static', filename=settings.logo_url) }}"
alt="logo" style="max-height:32px; margin-right:.5rem; border-radius:4px;">
{% else %}
<i class="bi bi-clipboard-check me-2"></i>
{% endif %}
<span class="navbar-brand mb-0 h1" style="font-size:1rem;" id="preview-name">
{{ settings.display_name }}
</span>
</nav>
<div class="p-3" style="font-size:.82rem; color:#64748b;">
Navbar and button colours update as you pick them.
</div>
</div>
</div>
</div>
</div>
<script>
// Live preview sync
(function () {
const navbar = document.getElementById('preview-navbar');
const nameEl = document.getElementById('preview-name');
document.querySelector('input[name="company_name"]').addEventListener('input', function () {
nameEl.textContent = this.value || 'Janitorial QC';
});
function wireColor(colorInput, textInput) {
colorInput.addEventListener('input', function () {
textInput.value = this.value;
if (colorInput.name === 'primary_color') navbar.style.backgroundColor = this.value;
});
textInput.addEventListener('input', function () {
if (/^#[0-9a-fA-F]{6}$/.test(this.value)) {
colorInput.value = this.value;
if (colorInput.name === 'primary_color') navbar.style.backgroundColor = this.value;
}
});
}
const pColor = document.querySelector('input[name="primary_color"]');
const pText = document.getElementById('primary_color_text');
const aColor = document.querySelector('input[name="accent_color"]');
const aText = document.getElementById('accent_color_text');
if (pColor && pText) wireColor(pColor, pText);
if (aColor && aText) wireColor(aColor, aText);
})();
</script>
{% endblock %}
+127
View File
@@ -0,0 +1,127 @@
{% extends "base.html" %}
{% block title %}Domains — Settings{% endblock %}
{% block content %}
<div class="d-flex justify-content-between align-items-center mb-3">
<h4 class="mb-0"><i class="bi bi-globe me-2"></i>Domains</h4>
<div class="btn-group btn-group-sm">
<a href="{{ url_for('tenant_settings.branding') }}" class="btn btn-outline-secondary">Branding</a>
<a href="{{ url_for('tenant_settings.plan') }}" class="btn btn-outline-secondary">Plan &amp; Usage</a>
<a href="{{ url_for('tenant_settings.domains') }}" class="btn btn-primary">Domains</a>
</div>
</div>
{% if not domain_allowed %}
<div class="alert alert-warning">
<i class="bi bi-lock me-1"></i>
Custom domains are available on <strong>Pro</strong> and <strong>Enterprise</strong> plans.
<a href="{{ url_for('tenant_settings.plan') }}" class="alert-link">View your plan</a>.
</div>
{% endif %}
<div class="card border-0 shadow-sm mb-3">
<div class="table-responsive">
<table class="table table-hover mb-0 align-middle" style="font-size:.85rem;">
<thead class="table-light">
<tr>
<th>Domain</th>
<th>Type</th>
<th>Status</th>
<th>TLS</th>
<th></th>
</tr>
</thead>
<tbody>
{% for d in tenant_domains %}
<tr>
<td class="font-monospace fw-medium">{{ d.domain }}</td>
<td>
<span class="badge {{ 'bg-primary' if d.kind == 'subdomain' else 'bg-secondary' }}">
{{ d.kind }}
</span>
{% if d.is_primary %}
<span class="badge bg-light text-dark border ms-1">primary</span>
{% endif %}
</td>
<td>
{% if d.verified %}
<span class="text-success"><i class="bi bi-check-circle-fill me-1"></i>Verified</span>
{% else %}
<span class="text-warning"><i class="bi bi-clock me-1"></i>Pending DNS</span>
{% endif %}
</td>
<td>
<span class="badge {{ 'bg-success' if d.tls_status == 'active' else ('bg-danger' if d.tls_status == 'failed' else 'bg-secondary') }}">
{{ d.tls_status }}
</span>
</td>
<td>
{% if not d.is_primary and d.kind == 'custom' %}
<form method="POST"
action="{{ url_for('tenant_settings.delete_domain', domain_id=d.id) }}"
class="d-inline"
onsubmit="return confirm('Remove {{ d.domain }}?')">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<button class="btn btn-outline-danger btn-sm">
<i class="bi bi-trash"></i>
</button>
</form>
{% endif %}
</td>
</tr>
{# DNS verification instructions for unverified custom domains #}
{% if not d.verified and d.kind == 'custom' and d.verification_token %}
<tr class="table-warning">
<td colspan="5" style="font-size:.82rem;">
<strong><i class="bi bi-info-circle me-1"></i>DNS Verification required for {{ d.domain }}</strong><br>
Add one of these DNS records at your DNS provider, then contact support to activate:
<div class="mt-2 font-monospace" style="background:#f8fafc; padding:.5rem .75rem; border-radius:6px; font-size:.78rem;">
<strong>Option A — TXT record</strong><br>
Name: <code>_jqc-verify.{{ d.domain }}</code><br>
Value: <code>jqc-verify={{ d.verification_token }}</code>
<br><br>
<strong>Option B — CNAME record</strong><br>
Name: <code>{{ d.domain }}</code><br>
Value: <code>{{ tenant_slug }}.{{ base_domain }}</code>
</div>
</td>
</tr>
{% endif %}
{% else %}
<tr><td colspan="5" class="text-muted py-3 text-center">No domains configured.</td></tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
{% if domain_allowed %}
<div class="card border-0 shadow-sm">
<div class="card-header bg-white py-2">
<span class="fw-semibold" style="font-size:.9rem;">Request Custom Domain</span>
</div>
<div class="card-body">
<p class="text-muted" style="font-size:.85rem;">
Enter the custom domain you want to use (e.g. <code>jqc.yourcompany.com</code>).
You'll need to add a DNS record to verify ownership before it goes live.
</p>
<form method="POST" action="{{ url_for('tenant_settings.request_domain') }}"
class="row g-2 align-items-end">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<div class="col-auto">
<input type="text" name="domain" class="form-control"
placeholder="jqc.yourcompany.com" style="width:280px;"
pattern="^(?:[a-z0-9](?:[a-z0-9\-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$">
</div>
<div class="col-auto">
<button class="btn btn-primary">
<i class="bi bi-plus-circle me-1"></i> Add Domain
</button>
</div>
</form>
</div>
</div>
{% endif %}
{% endblock %}
+97
View File
@@ -0,0 +1,97 @@
{% extends "base.html" %}
{% block title %}Plan & Usage — Settings{% endblock %}
{% block content %}
<div class="d-flex justify-content-between align-items-center mb-3">
<h4 class="mb-0"><i class="bi bi-patch-check me-2"></i>Plan &amp; Usage</h4>
<div class="btn-group btn-group-sm">
<a href="{{ url_for('tenant_settings.branding') }}" class="btn btn-outline-secondary">Branding</a>
<a href="{{ url_for('tenant_settings.plan') }}" class="btn btn-primary">Plan &amp; Usage</a>
<a href="{{ url_for('tenant_settings.domains') }}" class="btn btn-outline-secondary">Domains</a>
</div>
</div>
{% if plan_info %}
<div class="row g-3">
<div class="col-lg-5">
<div class="card border-0 shadow-sm h-100">
<div class="card-header bg-white py-2">
<span class="fw-semibold" style="font-size:.9rem;">Current Plan</span>
</div>
<div class="card-body">
<div class="d-flex align-items-center gap-2 mb-3">
<span class="badge bg-primary fs-6 px-3 py-2">{{ plan_info.name }}</span>
<span class="text-muted" style="font-size:.85rem;">{{ plan_info.code }}</span>
</div>
<table class="table table-sm mb-0" style="font-size:.85rem;">
<tbody>
<tr>
<td class="text-muted">Mobile API (iPad)</td>
<td>{% if plan_info.allow_mobile_api %}<i class="bi bi-check-circle-fill text-success"></i>{% else %}<i class="bi bi-x-circle-fill text-danger"></i>{% endif %}</td>
</tr>
<tr>
<td class="text-muted">Scheduled Reports</td>
<td>{% if plan_info.allow_scheduled_reports %}<i class="bi bi-check-circle-fill text-success"></i>{% else %}<i class="bi bi-x-circle-fill text-danger"></i>{% endif %}</td>
</tr>
<tr>
<td class="text-muted">Branding / White-label</td>
<td>{% if plan_info.allow_branding %}<i class="bi bi-check-circle-fill text-success"></i>{% else %}<i class="bi bi-x-circle-fill text-danger"></i>{% endif %}</td>
</tr>
<tr>
<td class="text-muted">Custom Domain</td>
<td>{% if plan_info.allow_custom_domain %}<i class="bi bi-check-circle-fill text-success"></i>{% else %}<i class="bi bi-x-circle-fill text-danger"></i>{% endif %}</td>
</tr>
</tbody>
</table>
<div class="mt-3">
<a href="mailto:support@jqc.app?subject=Plan upgrade request"
class="btn btn-sm btn-outline-primary">
<i class="bi bi-arrow-up-circle me-1"></i> Request Plan Upgrade
</a>
</div>
</div>
</div>
</div>
<div class="col-lg-7">
<div class="card border-0 shadow-sm h-100">
<div class="card-header bg-white py-2">
<span class="fw-semibold" style="font-size:.9rem;">Usage This Month</span>
</div>
<div class="card-body">
{% set axes = [
('inspections', 'Inspections / month', plan_info.max_inspections_month),
('issues', 'Issues / month', plan_info.max_issues_month),
('users', 'Active Users (total)', plan_info.max_users),
('facilities', 'Active Facilities (total)', plan_info.max_facilities),
] %}
{% for key, label, limit in axes %}
{% set current = quota_usage.get(key, 0) %}
{% set pct = ((current / limit * 100) | int) if limit else 0 %}
{% set over = limit and current >= limit %}
<div class="mb-3">
<div class="d-flex justify-content-between mb-1" style="font-size:.85rem;">
<span>{{ label }}</span>
<span class="{{ 'text-danger fw-semibold' if over else 'text-muted' }}">
{{ current }}{% if limit %} / {{ limit }}{% else %} / <em>unlimited</em>{% endif %}
</span>
</div>
{% if limit %}
<div class="progress" style="height:6px;">
<div class="progress-bar {{ 'bg-danger' if over else ('bg-warning' if pct >= 80 else 'bg-success') }}"
role="progressbar" style="width:{{ [pct,100]|min }}%"></div>
</div>
{% endif %}
</div>
{% endfor %}
</div>
</div>
</div>
</div>
{% else %}
<div class="alert alert-info">
Plan information is only available when multi-tenancy is enabled.
</div>
{% endif %}
{% endblock %}
@@ -0,0 +1,49 @@
"""phase33 — tenant_settings table for per-tenant branding (MT-7)
Adds a single-row-per-tenant settings store in the tenant database.
Tenant-zero starts with defaults (no visual change until admin edits them).
Revision: phase33_tenant_settings
Down: phase32_device_token_columns
"""
revision = 'phase33_tenant_settings'
down_revision = 'phase32_device_token_columns'
branch_labels = None
depends_on = None
import sqlalchemy as sa
from alembic import op
def _table_exists(bind, table_name):
result = bind.execute(sa.text(
"SELECT COUNT(*) FROM information_schema.tables "
"WHERE table_schema = DATABASE() AND table_name = :t"
), {'t': table_name})
return result.scalar() > 0
def upgrade():
bind = op.get_bind()
if not _table_exists(bind, 'tenant_settings'):
op.execute(sa.text("""
CREATE TABLE tenant_settings (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
company_name VARCHAR(150) NULL,
logo_url VARCHAR(500) NULL,
primary_color VARCHAR(7) NOT NULL DEFAULT '#1a56db',
accent_color VARCHAR(7) NOT NULL DEFAULT '#16a34a',
support_email VARCHAR(255) NULL,
updated_at DATETIME NOT NULL,
updated_by INT NULL,
CONSTRAINT fk_tenant_settings_user
FOREIGN KEY (updated_by) REFERENCES users(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
"""))
def downgrade():
bind = op.get_bind()
if _table_exists(bind, 'tenant_settings'):
op.execute(sa.text('DROP TABLE tenant_settings'))