printers: printer installer map + install-batch endpoint

Rebuilds the classic printer-installer feature: pick printers on the shopfloor
map, download a .bat that installs them.

Backend (asset_routes.py): GET /api/printers/install-batch?printerids=1,2,3
returns a .bat attachment. Groups printers the way the classic installprinter.asp
did - HP/Xerox via the universal PrinterInstaller.exe /PRINTER="a,b,c", printers
with a .exe installpath via that installer /SILENT, and anything else (no
installpath, or a .zip) listed for manual install instead of being run blindly.
Download URLs derive from the site_base_url setting + the IIS-served /installers
folder (no hardcoded host). Reuses the existing install-list query shape.

Frontend: PrinterInstallerMap.vue - full-screen Leaflet shopfloor map (reuses
mapConfig), a marker per network printer at its mapx/mapy, click to toggle-select,
sidebar with the selection + an Install button that downloads the batch. Toplevel
route /printer-installer, printersApi.installList(), and an Installer Map button
on the printers list.

Tests: install-batch grouping (universal/specific/manual) + requires-ids.
This commit is contained in:
cproudlock
2026-07-29 12:38:51 -04:00
parent 1ee9328bf9
commit 0d40780f53
6 changed files with 503 additions and 2 deletions

View File

@@ -318,6 +318,10 @@ export const printersApi = {
dashboardSummary() {
return api.get('/printers/dashboard/summary')
},
// Flat network-printer list (with mapx/mapy) for the installer map.
installList() {
return api.get('/printers/install-list')
},
drivers: {
list(params = {}) {
return api.get('/printers/drivers', { params })

View File

@@ -1,11 +1,12 @@
"""Printers API routes - new Asset-based architecture."""
import logging
import re
from flask import Blueprint, request
from flask import Blueprint, request, Response
from flask_jwt_extended import jwt_required
from shopdb.api import db, cache, Asset, AssetType, Vendor, Model, Communication, CommunicationType, AssetRelationship, RelationshipType, success_response, error_response, paginated_response, ErrorCodes, get_pagination_params, paginate_query
from shopdb.api import db, cache, Setting, Asset, AssetType, Vendor, Model, Communication, CommunicationType, AssetRelationship, RelationshipType, success_response, error_response, paginated_response, ErrorCodes, get_pagination_params, paginate_query
from ..models import Printer, PrinterType, ModelSupply, PrinterDriver
from ..models.model_supply import SUPPLY_TYPES, SUPPLY_COLORS, CAPACITY_TIERS
@@ -354,6 +355,180 @@ def printer_install_list():
return success_response(rows)
# Vendors whose printers install through the universal PrinterInstaller.exe
# (single call with a comma-separated /PRINTER list). Everything else installs
# from its own installpath .exe, or is flagged for manual install. Mirrors the
# classic installprinter.asp grouping rule.
UNIVERSAL_INSTALL_VENDORS = frozenset({'HP', 'Xerox'})
def _batch_base_url():
"""Base URL the generated .bat downloads installers from. Prefer the
configured site_base_url (already includes the /shopdb mount); fall back to
the request root so a site that never set it still produces a usable batch."""
base = (Setting.get('site_base_url') or '').strip().rstrip('/')
if base:
return base
return request.url_root.rstrip('/')
def _installer_url(installpath, base):
"""Absolute URL for a specific installer. Full URLs and UNC paths pass
through; a stored relative path ('./installers/printers/X.exe') mounts under
the site base -> base + '/installers/printers/X.exe'."""
path = (installpath or '').strip()
if not path:
return None
if re.match(r'^[a-z][a-z0-9+.-]*:', path, re.I) or path.startswith('\\\\'):
return path
return base + '/' + re.sub(r'^(\.?/)+', '', path)
def _install_name(printer, asset):
"""Name to install the printer as: the standardized Windows Name, else the
share/CSF name, else the asset name/number."""
return ((printer.windowsname or '').strip()
or (printer.sharename or '').strip()
or (asset.name or asset.assetnumber or '').strip())
@printers_asset_bp.route('/install-batch', methods=['GET'])
@jwt_required(optional=True)
def printer_install_batch():
"""Generate a Windows .bat that installs the selected printers.
?printerids=1,2,3 (the printers the user clicked on the installer map). The
batch groups them the same way the classic installprinter.asp did:
- HP / Xerox -> one universal PrinterInstaller.exe /PRINTER="a,b,c" call
- has .exe installpath -> download + run that installer /SILENT
- anything else (no installpath, or a .zip) -> listed as manual install
Downloads use PowerShell Invoke-WebRequest with the caller's Windows creds,
against the site base URL + the IIS-served /installers folder.
"""
raw = (request.args.get('printerids') or '').strip()
ids = []
for token in raw.split(','):
token = token.strip()
if token.isdigit():
ids.append(int(token))
if not ids:
return error_response(ErrorCodes.VALIDATION_ERROR,
'printerids is required (comma-separated)')
base = _batch_base_url()
universal = [] # (name,) install via PrinterInstaller.exe
specific = [] # (name, url) install via own .exe /SILENT
manual = [] # (name, vendor) cannot auto-install
for printer in (db.session.query(Printer).join(Asset)
.filter(Printer.printerid.in_(ids))
.filter(Asset.isactive == True).all()):
asset = printer.asset
if not asset:
continue
name = _install_name(printer, asset)
if not name:
continue
vendor = (printer.vendor.vendor if printer.vendor else '').strip()
installpath = (printer.installpath or '').strip()
if vendor in UNIVERSAL_INSTALL_VENDORS:
universal.append(name)
elif installpath.lower().endswith('.exe'):
specific.append((name, _installer_url(installpath, base)))
else:
# No installer, or a non-.exe payload (e.g. .zip) we will not run
# blindly with /SILENT - surface it for a human instead.
manual.append((name, vendor or 'unknown'))
facility = (Setting.get('facility_name') or 'GE Aerospace').strip() or 'GE Aerospace'
total = len(universal) + len(specific) + len(manual)
bat = _render_install_bat(facility, base, universal, specific, manual, total)
count = total if total else 0
filename = ('Install_%d_Printers.bat' % count) if count != 1 else 'Install_Printer.bat'
return Response(bat, mimetype='application/octet-stream',
headers={'Content-Disposition': 'attachment; filename=%s' % filename})
# PowerShell one-liner that downloads a URL to a temp file using the caller's
# Windows credentials (the installers share/site is integrated-auth on the LAN).
_PS_DOWNLOAD = ("powershell -NoProfile -Command \""
"$ProgressPreference='SilentlyContinue'; "
"[Net.ServicePointManager]::SecurityProtocol=[Net.SecurityProtocolType]::Tls12; "
"Invoke-WebRequest -Uri '%s' -OutFile '%s' "
"-UseBasicParsing -UseDefaultCredentials\"")
def _render_install_bat(facility, base, universal, specific, manual, total):
"""Build the .bat text (CRLF line endings for cmd.exe)."""
out = []
add = out.append
add('@echo off')
add('setlocal enabledelayedexpansion')
add('')
add('echo ========================================')
add('echo %s Printer Installer' % facility)
add('echo ========================================')
add('echo.')
if total == 0:
add('echo No installable printers were selected.')
add('pause')
add('exit /b 1')
return '\r\n'.join(out) + '\r\n'
add('echo Installing %d printer(s)...' % total)
add('echo.')
if manual:
add('echo *** The following require MANUAL installation (no silent installer): ***')
for name, vendor in manual:
add('echo - %s (%s)' % (name, vendor))
add('echo.')
for name, url in specific:
add('echo ----------------------------------------')
add('echo Installing: %s' % name)
add('echo Downloading installer...')
add(_PS_DOWNLOAD % (url, '%TEMP%\\printer_installer.exe'))
add('if exist "%TEMP%\\printer_installer.exe" (')
add(' echo Running installer...')
add(' "%TEMP%\\printer_installer.exe" /SILENT')
add(' del "%TEMP%\\printer_installer.exe" 2>nul')
add(') else (')
add(' echo ERROR: Could not download installer for %s' % name)
add(')')
add('echo.')
if universal:
add('echo ----------------------------------------')
add('echo Installing %d printer(s) via the universal installer:' % len(universal))
for name in universal:
add('echo - %s' % name)
add('echo ----------------------------------------')
add('echo Downloading PrinterInstaller.exe...')
add(_PS_DOWNLOAD % (base + '/installers/PrinterInstaller.exe',
'%TEMP%\\PrinterInstaller.exe'))
add('if exist "%TEMP%\\PrinterInstaller.exe" (')
add(' echo Running installer...')
add(' "%TEMP%\\PrinterInstaller.exe" /PRINTER="' + ','.join(universal) + '"')
add(' del "%TEMP%\\PrinterInstaller.exe" 2>nul')
add(') else (')
add(' echo ERROR: Could not download PrinterInstaller.exe')
add(')')
add('echo.')
add('echo ========================================')
add('echo Installation Complete!')
add('echo ========================================')
add('echo.')
add('pause')
add('')
add(':: Self-delete this batch file')
add('(goto) 2>nul & del "%~f0"')
return '\r\n'.join(out) + '\r\n'
@printers_asset_bp.route('/pc-default', methods=['GET'])
@jwt_required(optional=True)
def pc_default_printer():

View File

@@ -66,6 +66,12 @@ export default [
]
export const toplevel = [
{
path: '/printer-installer',
name: 'printer-installer-map',
component: () => import('./views/PrinterInstallerMap.vue'),
meta: { requiresAuth: true, plugin: 'printers' }
},
{
path: '/print/printer-qr',
name: 'print-printer-qr-batch',

View File

@@ -0,0 +1,238 @@
<template>
<div class="printer-installer">
<div class="map-pane">
<div class="map-header">
<router-link to="/printers" class="back-link">&larr; Printers</router-link>
<h1>Printer Installer</h1>
<span class="hint">Click printers on the map to select, then install.</span>
</div>
<div ref="mapContainer" class="map-canvas"></div>
</div>
<aside class="select-pane">
<h2>Selected <span class="count">{{ selectedList.length }}</span></h2>
<div v-if="!selectedList.length" class="empty">
No printers selected yet. Click a marker on the map.
</div>
<ul v-else class="selected-list">
<li v-for="p in selectedList" :key="p.printerid">
<span class="pname">{{ printerLabel(p) }}</span>
<span class="ploc" v-if="p.locationname">{{ p.locationname }}</span>
<button class="remove" title="Remove" @click="toggle(p.printerid)">&times;</button>
</li>
</ul>
<button class="btn-install" :disabled="!selectedList.length" @click="downloadBatch">
Install {{ selectedList.length }} printer(s)
</button>
<button v-if="selectedList.length" class="btn-clear" @click="clearSelection">
Clear selection
</button>
<p class="note">
Downloads a .bat that installs the selected printers (universal
installer for HP/Xerox, the printer's own installer otherwise). Run it on
the target PC.
</p>
</aside>
</div>
</template>
<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import L from 'leaflet'
import 'leaflet/dist/leaflet.css'
import { loadMapConfig, blueprintUrlFor, state as mapConfig } from '@/composables/mapConfig'
import { printersApi } from '@/api'
import { withBase } from '@/utils/basePath'
import { currentTheme } from '@/stores/theme'
const mapContainer = ref(null)
const printers = ref([])
const selected = ref({}) // printerid -> true
let map = null
let imageOverlay = null
let markers = {} // printerid -> circleMarker
let MAP_WIDTH = mapConfig.width
let MAP_HEIGHT = mapConfig.height
const SELECTED_COLOR = '#e53935'
const NORMAL_COLOR = '#4CAF50'
const selectedList = computed(() =>
printers.value.filter(p => selected.value[p.printerid]))
function printerLabel(p) {
return p.windowsname || p.sharename || p.name || p.machinenumber || ('#' + p.printerid)
}
function markerStyle(isSelected) {
return {
radius: isSelected ? 9 : 6,
color: '#222',
weight: 1,
fillColor: isSelected ? SELECTED_COLOR : NORMAL_COLOR,
fillOpacity: 0.95,
}
}
function toggle(printerid) {
if (selected.value[printerid]) {
delete selected.value[printerid]
} else {
selected.value[printerid] = true
}
const marker = markers[printerid]
if (marker) marker.setStyle(markerStyle(!!selected.value[printerid]))
}
function clearSelection() {
for (const id of Object.keys(selected.value)) {
if (markers[id]) markers[id].setStyle(markerStyle(false))
}
selected.value = {}
}
function downloadBatch() {
const ids = selectedList.value.map(p => p.printerid).join(',')
if (!ids) return
// install-batch is optional-auth, so a plain anchor download works (an anchor
// cannot carry the JWT bearer header). withBase keeps it under the mount.
const url = withBase('/api/printers/install-batch?printerids=' + encodeURIComponent(ids))
const link = document.createElement('a')
link.href = url
link.click()
}
function renderMarkers() {
for (const p of printers.value) {
if (p.mapx == null || p.mapy == null) continue
const leafletY = MAP_HEIGHT - p.mapy
const leafletX = p.mapx
const marker = L.circleMarker([leafletY, leafletX], markerStyle(false))
marker.bindTooltip(printerLabel(p), { direction: 'top' })
marker.on('click', () => toggle(p.printerid))
marker.addTo(map)
markers[p.printerid] = marker
}
}
watch(currentTheme, (theme) => {
if (imageOverlay) imageOverlay.setUrl(blueprintUrlFor(theme))
})
onMounted(async () => {
await loadMapConfig()
MAP_WIDTH = mapConfig.width
MAP_HEIGHT = mapConfig.height
try {
const response = await printersApi.installList()
printers.value = response.data.data || []
} catch (e) {
printers.value = []
}
map = L.map(mapContainer.value, {
crs: L.CRS.Simple,
minZoom: -4,
maxZoom: 2,
attributionControl: false,
})
const bounds = [[0, 0], [MAP_HEIGHT, MAP_WIDTH]]
imageOverlay = L.imageOverlay(blueprintUrlFor(currentTheme.value), bounds).addTo(map)
map.setView([MAP_HEIGHT / 2, MAP_WIDTH / 2], -2)
map.setMaxBounds(bounds)
renderMarkers()
})
onUnmounted(() => {
if (map) map.remove()
})
</script>
<style scoped>
.printer-installer {
display: flex;
height: 100vh;
width: 100vw;
background: var(--bg);
}
.map-pane { flex: 1; display: flex; flex-direction: column; min-width: 0; }
.map-header {
display: flex;
align-items: baseline;
gap: 1rem;
padding: 0.75rem 1rem;
border-bottom: 1px solid var(--border);
background: var(--bg-card);
}
.map-header h1 { font-size: 1.2rem; margin: 0; color: var(--text); }
.back-link { color: var(--link); text-decoration: none; font-size: 0.9rem; }
.hint { color: var(--text-light); font-size: 0.85rem; margin-left: auto; }
.map-canvas { flex: 1; background: var(--bg); }
.select-pane {
width: 320px;
flex-shrink: 0;
border-left: 1px solid var(--border);
background: var(--bg-card);
padding: 1rem;
display: flex;
flex-direction: column;
overflow-y: auto;
}
.select-pane h2 { font-size: 1rem; margin: 0 0 0.75rem; color: var(--text); }
.count {
background: var(--primary);
color: #fff;
border-radius: 10px;
padding: 0.05rem 0.5rem;
font-size: 0.85rem;
margin-left: 0.25rem;
}
.empty { color: var(--text-light); font-size: 0.9rem; padding: 1rem 0; }
.selected-list { list-style: none; margin: 0 0 1rem; padding: 0; }
.selected-list li {
display: flex;
align-items: center;
gap: 0.4rem;
padding: 0.4rem 0;
border-bottom: 1px solid var(--border);
}
.pname { color: var(--text); font-weight: 600; font-size: 0.85rem; }
.ploc { color: var(--text-light); font-size: 0.75rem; }
.remove {
margin-left: auto;
background: none;
border: none;
color: var(--danger);
font-size: 1.1rem;
cursor: pointer;
line-height: 1;
}
.btn-install {
width: 100%;
padding: 0.6rem;
background: var(--primary);
color: #fff;
border: none;
border-radius: 4px;
font-weight: 600;
cursor: pointer;
}
.btn-install:disabled { opacity: 0.5; cursor: not-allowed; }
.btn-clear {
width: 100%;
margin-top: 0.5rem;
padding: 0.4rem;
background: transparent;
color: var(--text-light);
border: 1px solid var(--border);
border-radius: 4px;
cursor: pointer;
}
.note { color: var(--text-light); font-size: 0.75rem; margin-top: 1rem; line-height: 1.4; }
</style>

View File

@@ -3,6 +3,7 @@
<div class="page-header">
<h2>Printers</h2>
<div class="header-actions">
<router-link to="/printer-installer" class="btn btn-secondary" target="_blank">Installer Map</router-link>
<router-link to="/print/printer-qr" class="btn btn-secondary" target="_blank">Batch Print QR</router-link>
<router-link to="/print/asset-label-batch/printer" class="btn btn-secondary" target="_blank">Print Labels</router-link>
<router-link to="/printers/new" class="btn btn-primary">Add Printer</router-link>

View File

@@ -0,0 +1,77 @@
"""Tests for the printer installer batch endpoint (/api/printers/install-batch).
The printer installer map lets a user pick printers on the shopfloor map and
download a .bat that installs them, grouping the same way the classic
installprinter.asp did (HP/Xerox -> universal PrinterInstaller.exe; other
printers with a .exe installpath -> that installer /SILENT; anything else ->
manual).
"""
import pytest
@pytest.fixture
def printer_assettype(db):
from shopdb.core.models import AssetType
at = AssetType(assettype='printer', pluginname='printers',
tablename='printers', description='Printers')
db.session.add(at)
db.session.commit()
return at
def _vendor(db, name):
from shopdb.core.models import Vendor
v = Vendor(vendor=name)
db.session.add(v)
db.session.commit()
return v
def _make_printer(client, auth_headers, **payload):
resp = client.post('/api/printers', json=payload, headers=auth_headers)
assert resp.status_code == 201, resp.get_json()
return resp.get_json()['data']['printer']['printerid']
def test_install_batch_groups_universal_specific_and_manual(
client, db, auth_headers, printer_assettype):
hp = _vendor(db, 'HP')
zebra = _vendor(db, 'Zebra')
epson = _vendor(db, 'Epson')
# HP -> universal installer
hp_id = _make_printer(client, auth_headers, assetnumber='CSF04-WJRP2035-HP',
hostname='wjprn04', vendorid=hp.vendorid)
# Zebra with a .exe installpath -> specific silent install
zebra_id = _make_printer(client, auth_headers, assetnumber='LABELER-ZEBRA',
hostname='wjprn05', vendorid=zebra.vendorid,
installpath='./installers/printers/zddriver.exe')
# Epson with a .zip installpath -> manual (we do not run a .zip /SILENT)
epson_id = _make_printer(client, auth_headers, assetnumber='RECEIPT-EPSON',
hostname='wjprn06', vendorid=epson.vendorid,
installpath='./installers/printers/c350navi.zip')
ids = '%d,%d,%d' % (hp_id, zebra_id, epson_id)
resp = client.get('/api/printers/install-batch?printerids=' + ids,
headers=auth_headers)
assert resp.status_code == 200
assert 'application/octet-stream' in resp.headers['Content-Type']
assert '.bat' in resp.headers['Content-Disposition']
bat = resp.get_data(as_text=True)
# Universal group: HP printer name in a /PRINTER list + PrinterInstaller.exe
assert 'PrinterInstaller.exe' in bat
assert '/PRINTER="CSF04-WJRP2035-HP"' in bat
# Specific: the .exe installpath resolved + run /SILENT
assert 'installers/printers/zddriver.exe' in bat
assert '/SILENT' in bat
# Manual: the .zip printer is flagged, NOT executed
assert 'MANUAL' in bat
assert 'RECEIPT-EPSON' in bat
assert 'c350navi.zip' not in bat # never handed to the runner
def test_install_batch_requires_ids(client, db, auth_headers, printer_assettype):
resp = client.get('/api/printers/install-batch', headers=auth_headers)
assert resp.status_code == 400