This commit is contained in:
seb
2026-10-30 17:30:10 +01:00
parent 72f168f188
commit 56d376c9bd
7 changed files with 775 additions and 17 deletions

View File

@@ -0,0 +1,600 @@
import { PureComponent } from 'react';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import Chip from '@mui/material/Chip';
import Divider from '@mui/material/Divider';
import IconButton from '@mui/material/IconButton';
import TextField from '@mui/material/TextField';
import Tooltip from '@mui/material/Tooltip';
import Typography from '@mui/material/Typography';
import AddIcon from '@mui/icons-material/Add';
import ArrowDownwardIcon from '@mui/icons-material/ArrowDownward';
import ArrowUpwardIcon from '@mui/icons-material/ArrowUpward';
import CheckIcon from '@mui/icons-material/Check';
import CloseIcon from '@mui/icons-material/Close';
import ContentCopyIcon from '@mui/icons-material/ContentCopy';
import DeleteOutlinedIcon from '@mui/icons-material/DeleteOutlined';
import EditOutlinedIcon from '@mui/icons-material/EditOutlined';
import LocalPrintshopOutlinedIcon from '@mui/icons-material/LocalPrintshopOutlined';
import CheckCircleOutlinedIcon from '@mui/icons-material/CheckCircleOutlined';
import HourglassEmptyIcon from '@mui/icons-material/HourglassEmpty';
import { enqueueSnackbar } from 'notistack';
import BackendError from '../BackendError';
import companyAutomat from '../../automats/companyAutomat';
import { backendErrorFrom } from '../../utils/backendError';
import { notifyError } from '../../utils/notify';
function formatDateTime(val) {
if (!val) return null;
try {
const d = new Date(val);
if (isNaN(d.getTime())) return null;
return d.toLocaleString('de-DE', {
day: '2-digit',
month: '2-digit',
year: 'numeric',
hour: '2-digit',
minute: '2-digit',
});
} catch {
return null;
}
}
export default class PrinterAgentSettingsPanel extends PureComponent {
constructor(props) {
super(props);
this.state = {
printeragents: Array.isArray(companyAutomat.state.printeragents)
? companyAutomat.state.printeragents
: [],
error: companyAutomat.state.printeragentsError
? backendErrorFrom(companyAutomat.state.printeragentsError)
: null,
newAgentName: '',
creatingAgent: false,
deletingId: null,
patchingAgentId: null,
editingId: null,
editNameDraft: '',
sortDrafts: {},
};
this.handleRetry = this.handleRetry.bind(this);
this.handleCreateAgent = this.handleCreateAgent.bind(this);
this.handleDeleteAgent = this.handleDeleteAgent.bind(this);
this.handleStartRename = this.handleStartRename.bind(this);
this.handleCancelRename = this.handleCancelRename.bind(this);
this.handleSaveRename = this.handleSaveRename.bind(this);
this.handleSortDraftChange = this.handleSortDraftChange.bind(this);
this.handleSortSubmit = this.handleSortSubmit.bind(this);
this.handleMoveAgent = this.handleMoveAgent.bind(this);
}
componentDidMount() {
this.unsub = companyAutomat.subscribe(this, (state) => ({
printeragents: Array.isArray(state.printeragents) ? state.printeragents : [],
error: state.printeragentsError ? backendErrorFrom(state.printeragentsError) : null,
}));
if (companyAutomat.state.printeragentsStatus === 'idle') {
void companyAutomat.actions.loadPrinterAgents().catch(() => {});
}
}
componentWillUnmount() {
this.unsub?.();
}
handleRetry() {
void companyAutomat.actions.loadPrinterAgents().catch(notifyError);
}
async handleCreateAgent() {
const { newAgentName, printeragents } = this.state;
const trimmed = newAgentName.trim();
if (!trimmed) return;
this.setState({ creatingAgent: true });
try {
const nextSort =
printeragents.length > 0
? Math.max(...printeragents.map((a) => Number(a.sort) || 0)) + 1
: 0;
await companyAutomat.actions.createPrinterAgent({
name: trimmed,
sort: nextSort,
});
this.setState({ newAgentName: '' });
enqueueSnackbar('Drucker-Agent hinzugefügt.', { variant: 'success' });
} catch (err) {
notifyError(err);
} finally {
this.setState({ creatingAgent: false });
}
}
async handleDeleteAgent(agent) {
if (!window.confirm(`Möchten Sie den Drucker-Agenten „${agent.name}“ wirklich löschen?`)) {
return;
}
this.setState({ deletingId: agent.id });
try {
await companyAutomat.actions.deletePrinterAgent(agent.id);
enqueueSnackbar('Drucker-Agent gelöscht.', { variant: 'success' });
} catch (err) {
notifyError(err);
} finally {
this.setState({ deletingId: null });
}
}
handleStartRename(agent) {
this.setState({ editingId: agent.id, editNameDraft: agent.name || '' });
}
handleCancelRename() {
this.setState({ editingId: null, editNameDraft: '' });
}
async handleSaveRename(agent) {
const { editNameDraft } = this.state;
const trimmed = editNameDraft.trim();
if (!trimmed || trimmed === agent.name) {
this.handleCancelRename();
return;
}
this.setState({ patchingAgentId: agent.id });
try {
await companyAutomat.actions.updatePrinterAgent(agent.id, { name: trimmed });
enqueueSnackbar('Name aktualisiert.', { variant: 'success' });
this.setState({ editingId: null, editNameDraft: '' });
} catch (err) {
notifyError(err);
} finally {
this.setState({ patchingAgentId: null });
}
}
handleSortDraftChange(agentId, value) {
this.setState((prev) => ({
sortDrafts: { ...prev.sortDrafts, [agentId]: value },
}));
}
async handleSortSubmit(agent) {
const draft = this.state.sortDrafts[agent.id];
if (draft === undefined) return;
const nextSort = Number(draft);
if (isNaN(nextSort) || nextSort === (agent.sort ?? 0)) {
this.setState((prev) => {
const next = { ...prev.sortDrafts };
delete next[agent.id];
return { sortDrafts: next };
});
return;
}
this.setState({ patchingAgentId: agent.id });
try {
await companyAutomat.actions.updatePrinterAgent(agent.id, { sort: nextSort });
this.setState((prev) => {
const next = { ...prev.sortDrafts };
delete next[agent.id];
return { sortDrafts: next };
});
enqueueSnackbar('Reihenfolge gespeichert.', { variant: 'success' });
} catch (err) {
notifyError(err);
} finally {
this.setState({ patchingAgentId: null });
}
}
async handleMoveAgent(agent, direction) {
const { printeragents } = this.state;
const currentIndex = printeragents.findIndex((a) => a.id === agent.id);
if (currentIndex === -1) return;
const targetIndex = direction === 'up' ? currentIndex - 1 : currentIndex + 1;
if (targetIndex < 0 || targetIndex >= printeragents.length) return;
const targetAgent = printeragents[targetIndex];
const currentSort = Number(agent.sort) || 0;
const targetSort = Number(targetAgent.sort) || 0;
let newCurrentSort = targetSort;
let newTargetSort = currentSort;
if (newCurrentSort === newTargetSort) {
newCurrentSort = direction === 'up' ? targetSort - 1 : targetSort + 1;
}
this.setState({ patchingAgentId: agent.id });
try {
await Promise.all([
companyAutomat.actions.updatePrinterAgent(agent.id, { sort: newCurrentSort }),
companyAutomat.actions.updatePrinterAgent(targetAgent.id, { sort: newTargetSort }),
]);
} catch (err) {
notifyError(err);
} finally {
this.setState({ patchingAgentId: null });
}
}
render() {
const {
error,
printeragents,
newAgentName,
creatingAgent,
deletingId,
patchingAgentId,
editingId,
editNameDraft,
} = this.state;
if (error && printeragents.length === 0) {
return (
<Box sx={{ p: 3 }}>
<BackendError error={error} onRetry={this.handleRetry} />
</Box>
);
}
return (
<Box sx={{ p: 3, maxWidth: 900, mx: 'auto' }}>
<Box sx={{ mb: 2 }}>
<Typography variant="h6" fontWeight={600} gutterBottom>
Drucker-Agenten
</Typography>
<Typography variant="body2" color="text.secondary">
Verwalten Sie externe Drucker-Agenten für Druckaufträge. Nach Erstellung eines Agenten
geben Sie die 6-stellige PIN auf dem Agenten-Gerät ein, um die Kopplung abzuschließen.
</Typography>
</Box>
{/* Add new agent row */}
<Box sx={{ display: 'flex', gap: 1.5, mb: 3, alignItems: 'center' }}>
<TextField
size="small"
placeholder="Neuer Drucker-Agent Name (z.B. Bar Receipt Printer)"
value={newAgentName}
onChange={(e) => this.setState({ newAgentName: e.target.value })}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault();
void this.handleCreateAgent();
}
}}
disabled={creatingAgent}
autoComplete="off"
slotProps={{
htmlInput: {
autoComplete: 'off',
autoCorrect: 'off',
autoCapitalize: 'off',
spellCheck: false,
},
input: {
startAdornment: <LocalPrintshopOutlinedIcon sx={{ mr: 1, color: 'text.secondary' }} />,
},
}}
sx={{ flex: 1 }}
/>
<Button
variant="contained"
size="small"
startIcon={<AddIcon />}
onClick={this.handleCreateAgent}
disabled={creatingAgent || !newAgentName.trim()}
>
Hinzufügen
</Button>
</Box>
<Divider sx={{ mb: 2 }} />
{printeragents.length === 0 ? (
<Box sx={{ textAlign: 'center', py: 6, color: 'text.secondary' }}>
<LocalPrintshopOutlinedIcon sx={{ fontSize: 48, mb: 1, opacity: 0.5 }} />
<Typography variant="body2">Keine Drucker-Agenten angelegt.</Typography>
</Box>
) : (
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
{printeragents.map((agent, index) => {
const isDeleting = deletingId === agent.id;
const isPatching = patchingAgentId === agent.id;
const isEditing = editingId === agent.id;
const isPaired = agent.pairedAt != null;
const pairedDateText = formatDateTime(agent.pairedAt);
const lastseenText = formatDateTime(agent.lastseenAt) ?? 'Nie';
const updatedText = formatDateTime(agent.updatedAt) ?? '—';
return (
<Box
key={agent.id}
sx={{
p: 2,
borderRadius: 2,
border: '1px solid',
borderColor: isPaired ? 'divider' : 'warning.light',
bgcolor: 'background.paper',
display: 'flex',
flexDirection: 'column',
gap: 1.5,
transition: 'border-color 0.2s ease',
}}
>
{/* Header: Icon, Name (or Edit input), Status chip, Actions */}
<Box
sx={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
gap: 1,
flexWrap: 'wrap',
}}
>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5, flex: 1, minWidth: 260 }}>
<LocalPrintshopOutlinedIcon
sx={{ color: isPaired ? 'primary.main' : 'warning.main', fontSize: 24 }}
/>
{isEditing ? (
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1, flex: 1 }}>
<TextField
size="small"
value={editNameDraft}
onChange={(e) => this.setState({ editNameDraft: e.target.value })}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault();
void this.handleSaveRename(agent);
} else if (e.key === 'Escape') {
this.handleCancelRename();
}
}}
autoFocus
disabled={isPatching}
autoComplete="off"
slotProps={{
htmlInput: {
autoComplete: 'off',
autoCorrect: 'off',
autoCapitalize: 'off',
spellCheck: false,
},
}}
sx={{ minWidth: 200 }}
/>
<IconButton
size="small"
color="primary"
onClick={() => void this.handleSaveRename(agent)}
disabled={isPatching}
>
<CheckIcon fontSize="small" />
</IconButton>
<IconButton
size="small"
onClick={this.handleCancelRename}
disabled={isPatching}
>
<CloseIcon fontSize="small" />
</IconButton>
</Box>
) : (
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
<Typography variant="subtitle1" fontWeight={600}>
{agent.name}
</Typography>
<Tooltip title="Name bearbeiten">
<IconButton
size="small"
onClick={() => this.handleStartRename(agent)}
disabled={isPatching || isDeleting}
sx={{ p: 0.5, color: 'text.secondary' }}
>
<EditOutlinedIcon sx={{ fontSize: 16 }} />
</IconButton>
</Tooltip>
</Box>
)}
{isPaired ? (
<Chip
icon={<CheckCircleOutlinedIcon />}
label="Gekoppelt"
size="small"
variant="outlined"
color="success"
sx={{ fontWeight: 600, fontSize: '0.75rem' }}
/>
) : (
<Chip
icon={<HourglassEmptyIcon />}
label="Nicht gekoppelt"
size="small"
variant="outlined"
color="warning"
sx={{ fontWeight: 600, fontSize: '0.75rem' }}
/>
)}
</Box>
{/* Delete control */}
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
<IconButton
size="small"
aria-label={`Drucker-Agent ${agent.name} löschen`}
onClick={() => void this.handleDeleteAgent(agent)}
disabled={isDeleting || creatingAgent || isPatching}
color="error"
>
<DeleteOutlinedIcon fontSize="small" />
</IconButton>
</Box>
</Box>
{/* Body: Pairing details or PIN info */}
<Box
sx={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
flexWrap: 'wrap',
gap: 2,
pt: 0.5,
}}
>
{!isPaired ? (
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5, flexWrap: 'wrap' }}>
<Typography variant="body2" color="text.secondary">
Kopplungs-PIN:
</Typography>
<Tooltip title="PIN in die Zwischenablage kopieren">
<Chip
icon={<ContentCopyIcon sx={{ fontSize: 14 }} />}
label={agent.pairingpin || '—'}
onClick={() => {
if (agent.pairingpin) {
navigator.clipboard?.writeText(agent.pairingpin);
enqueueSnackbar('PIN in Zwischenablage kopiert.', { variant: 'info' });
}
}}
clickable
color="warning"
variant="filled"
sx={{
fontFamily: 'monospace',
fontWeight: 700,
fontSize: '0.9rem',
letterSpacing: '0.1em',
px: 0.5,
}}
/>
</Tooltip>
<Typography variant="caption" color="text.secondary">
Geben Sie diesen PIN auf dem Drucker-Agent-Gerät ein.
</Typography>
</Box>
) : (
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5, flexWrap: 'wrap' }}>
{agent.clientserial ? (
<Chip
label={`S/N: ${agent.clientserial}`}
size="small"
variant="outlined"
sx={{ fontFamily: 'monospace', fontSize: '0.75rem' }}
/>
) : null}
{agent.clientmodel ? (
<Chip
label={`Modell: ${agent.clientmodel}`}
size="small"
variant="outlined"
sx={{ fontSize: '0.75rem' }}
/>
) : null}
{agent.agentversion ? (
<Chip
label={`v${agent.agentversion}`}
size="small"
variant="outlined"
color="info"
sx={{ fontFamily: 'monospace', fontWeight: 600, fontSize: '0.75rem' }}
/>
) : null}
{agent.clientstate ? (
<Chip
label={`Status: ${agent.clientstate}`}
size="small"
variant="outlined"
sx={{ fontSize: '0.75rem' }}
/>
) : null}
</Box>
)}
{/* Sort Order Controls */}
<Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5, ml: 'auto' }}>
<Typography variant="body2" color="text.secondary">
Reihenfolge:
</Typography>
<Tooltip title="Nach oben verschieben">
<span>
<IconButton
size="small"
disabled={index === 0 || isPatching || isDeleting}
onClick={() => void this.handleMoveAgent(agent, 'up')}
sx={{ p: 0.25 }}
>
<ArrowUpwardIcon sx={{ fontSize: 16 }} />
</IconButton>
</span>
</Tooltip>
<Tooltip title="Nach unten verschieben">
<span>
<IconButton
size="small"
disabled={index === printeragents.length - 1 || isPatching || isDeleting}
onClick={() => void this.handleMoveAgent(agent, 'down')}
sx={{ p: 0.25 }}
>
<ArrowDownwardIcon sx={{ fontSize: 16 }} />
</IconButton>
</span>
</Tooltip>
<TextField
type="number"
size="small"
disabled={isPatching || isDeleting}
value={this.state.sortDrafts[agent.id] ?? agent.sort ?? 0}
onChange={(e) => this.handleSortDraftChange(agent.id, e.target.value)}
onBlur={() => void this.handleSortSubmit(agent)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault();
e.target.blur();
}
}}
slotProps={{
htmlInput: {
step: 1,
style: { width: 44, padding: '3px 6px', textAlign: 'center', fontSize: '0.8125rem' },
},
}}
sx={{ width: 56 }}
/>
</Box>
</Box>
{/* Dates Row */}
<Divider sx={{ my: 0.25 }} />
<Box
sx={{
display: 'flex',
alignItems: 'center',
flexWrap: 'wrap',
gap: 2.5,
color: 'text.secondary',
}}
>
{isPaired && pairedDateText ? (
<Typography variant="caption">
Gekoppelt am: <strong>{pairedDateText}</strong>
</Typography>
) : null}
<Typography variant="caption">
Zuletzt gesehen: <strong>{lastseenText}</strong>
</Typography>
<Typography variant="caption">
Aktualisiert: <strong>{updatedText}</strong>
</Typography>
</Box>
</Box>
);
})}
</Box>
)}
</Box>
);
}
}

View File

@@ -18,6 +18,7 @@ import authAutomat from '../../automats/authAutomat';
import CompanySettingsPanel from './CompanySettingsPanel';
import NumberSettingsPanel from './NumberSettingsPanel';
import PrinterSettingsPanel from './PrinterSettingsPanel';
import PrinterAgentSettingsPanel from './PrinterAgentSettingsPanel';
import SettingsKeysPanel from './SettingsKeysPanel';
import ImportExportSettingsPanel from './ImportExportSettingsPanel';
import PosTerminalSettingsPanel from './PosTerminalSettingsPanel';
@@ -27,6 +28,7 @@ import HealthSettingsPanel from './HealthSettingsPanel';
import MonitorHeartOutlinedIcon from '@mui/icons-material/MonitorHeartOutlined';
import SecurityIcon from '@mui/icons-material/Security';
import BackupTableOutlinedIcon from '@mui/icons-material/BackupTableOutlined';
import LocalPrintshopOutlinedIcon from '@mui/icons-material/LocalPrintshopOutlined';
import { SURFACE_BASE } from '../../colors';
const TAB_KEYS = {
@@ -35,6 +37,7 @@ const TAB_KEYS = {
keys: 'keys',
numbers: 'numbers',
printers: 'printers',
printeragent: 'printeragent',
importExport: 'importExport',
backup: 'backup',
posterminal: 'posterminal',
@@ -47,6 +50,7 @@ const TABS = [
{ id: TAB_KEYS.keys, label: 'Einstellungen', icon: <TuneIcon />, Panel: SettingsKeysPanel },
{ id: TAB_KEYS.numbers, label: 'Nummernkreise', icon: <NumbersIcon />, Panel: NumberSettingsPanel },
{ id: TAB_KEYS.printers, label: 'Drucker', icon: <PrintOutlinedIcon />, Panel: PrinterSettingsPanel },
{ id: TAB_KEYS.printeragent, label: 'Drucker-Agent', icon: <LocalPrintshopOutlinedIcon />, Panel: PrinterAgentSettingsPanel },
{ id: TAB_KEYS.importExport, label: 'Import/Export', icon: <ImportExportIcon />, Panel: ImportExportSettingsPanel },
{ id: TAB_KEYS.backup, label: 'Backups', icon: <BackupTableOutlinedIcon />, Panel: BackupSettingsPanel },
{ id: TAB_KEYS.posterminal, label: 'POS Terminal', icon: <PointOfSaleIcon />, Panel: PosTerminalSettingsPanel },