Files
qbit-printing/src/main/java/com/kingsrook/qbits/printing/PrintingProcesses.java
T
james.maesandClaude Fable 5.1 e33823bbbd
Shared Java Maven CI / secrets (push) Failing after 1s
Shared Java Maven CI / verify (push) Successful in 4m44s
Shared Java Maven CI / gate (push) Failing after 11s
qrun-release / release (push) Failing after 4m59s
qrun-release / postpublish (push) Skipped
QRun-IO/ci-policy: ci / fork-guard (pull_request) Skipped
QRun-IO/ci-policy: native / fork-deny (pull_request) Skipped
QRun-IO/ci-policy: native / dotnet-0 (pull_request) Skipped
QRun-IO/ci-policy: ci / Scoped workflow [workflow 1b3648d9421543350067e95e54959dfb471b26d5] (pull_request) Successful in 6s
QRun-IO/ci-policy: ci / head-profile (pull_request) Skipped
QRun-IO/ci-policy: ci / repository-policy (pull_request) Skipped
QRun-IO/ci-policy: ci / application-template-0 (pull_request) Skipped
QRun-IO/ci-policy: ci / gradle-1 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-core-2-head (pull_request) Skipped
QRun-IO/ci-policy: ci / java-docker-3 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-docker-3-head (pull_request) Skipped
QRun-IO/ci-policy: ci / java-docker-4 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-frontend-browser-5 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-maven-6 (pull_request) Skipped
QRun-IO/ci-policy: ci / java-maven-6-head (pull_request) Skipped
QRun-IO/ci-policy: ci / java-maven-7-head (pull_request) Skipped
QRun-IO/ci-policy: ci / node-8 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-9 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-10 (pull_request) Skipped
QRun-IO/ci-policy: ci / node-playwright-11 (pull_request) Skipped
QRun-IO/ci-policy: ci / repository-policy-12 (pull_request) Skipped
QRun-IO/ci-policy: ci / source-config-13 (pull_request) Skipped
QRun-IO/ci-policy: ci / source-config-14 (pull_request) Skipped
QRun-IO/ci-policy: ci / android-0 (pull_request) Skipped
QRun-IO/ci-policy: ci / original-business (pull_request) Skipped
QRun-IO/ci-policy: ci / original-mcp (pull_request) Skipped
QRun-IO/ci-policy: ci / original-voyage (pull_request) Skipped
QRun-IO/ci-policy: ci / original-cli (pull_request) Skipped
QRun-IO/ci-policy: ci / not-enrolled (pull_request) Skipped
QRun-IO/ci-policy: ci / shared-pipeline (pull_request) Skipped
QRun-IO/ci-policy: native / native-result (pull_request) Successful in 8s
QRun-IO/ci-policy: Shared Java Maven CI / secrets (pull_request) Successful in 28s
QRun-IO/ci-policy: Shared Java Maven CI / verify (pull_request) Successful in 4m2s
QRun-IO/ci-policy: Shared Java Maven CI / gate (pull_request) Successful in 8s
QRun-IO/ci-policy: ci / java-maven-7 (pull_request) Successful in 4m11s
QRun-IO/ci-policy: ci / ci-result (pull_request) Successful in 3s
feat(printers): remove printers and devices as archives, purged by retention
Add nullable removed_at to printing_printer and printing_device (read-only
"Removed at" on both tables) through the existing idempotent migration.

Remove printers (printingRemoveSelectedPrinters, record and selection) and
PrintingService.removePrinter set removed_at, clear approval and exposure,
and drop the printer from the operator catalog, submissions, claims, the
device/printer selectors and the PRINTERS frame, which is pushed again. A
removed queue that the device shares again returns exposed but not
approved; approval changes on a removed printer are refused.

Remove device (printingRemoveDevices, confirmation required) revokes access
through the existing REVOKE control, then PrintingService.removeDevice
archives the device and all of its printers; an already revoked device is
archived without a new command. Removed devices leave the device list,
every device selector and all authenticated paths; job history stays.

Retention cleanup hard-deletes removed printers that no job references and
removed devices with no jobs and no printers, bounded by the batch size and
logged. Native inventory authorization still covers removed rows so a
re-shared queue can reactivate.

Tests cover hiding, re-sharing, device removal with history, purge bounds
and process metadata. Docs: README, UI walkthrough, storage and retention,
realtime, changelog (1.1.0).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Signed-off-by: James Maes <james@kof22.com>
2026-11-05 16:31:33 -06:00

579 lines
30 KiB
Java

/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.printing;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import com.kingsrook.qqq.backend.core.actions.processes.BackendStep;
import com.kingsrook.qqq.backend.core.actions.tables.GetAction;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.actions.processes.ProcessSummaryLine;
import com.kingsrook.qqq.backend.core.model.actions.processes.ProcessSummaryLineInterface;
import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepInput;
import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepOutput;
import com.kingsrook.qqq.backend.core.model.actions.processes.Status;
import com.kingsrook.qqq.backend.core.model.actions.tables.get.GetInput;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QCriteriaOperator;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QFilterCriteria;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldType;
import com.kingsrook.qqq.backend.core.model.metadata.layout.QAppMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.permissions.QPermissionRules;
import com.kingsrook.qqq.backend.core.model.metadata.possiblevalues.QPossibleValue;
import com.kingsrook.qqq.backend.core.model.metadata.possiblevalues.QPossibleValueSource;
import com.kingsrook.qqq.backend.core.model.metadata.possiblevalues.QPossibleValueSourceType;
import com.kingsrook.qqq.backend.core.model.metadata.processes.QBackendStepMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.processes.QComponentType;
import com.kingsrook.qqq.backend.core.model.metadata.processes.QFrontendComponentMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.processes.QFrontendStepMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.processes.QProcessMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.qbits.QBitMetaData;
import com.kingsrook.qqq.backend.core.processes.implementations.etl.streamedwithfrontend.AbstractLoadStep;
import com.kingsrook.qqq.backend.core.processes.implementations.etl.streamedwithfrontend.AbstractTransformStep;
import com.kingsrook.qqq.backend.core.processes.implementations.etl.streamedwithfrontend.ProcessSummaryProviderInterface;
import com.kingsrook.qqq.backend.core.processes.implementations.etl.streamedwithfrontend.StreamedETLWithFrontendProcess;
import org.json.JSONObject;
import org.jspecify.annotations.Nullable;
/*******************************************************************************
** Native QQQ setup forms and backend steps for the initial printing workflow.
*******************************************************************************/
public class PrintingProcesses implements BackendStep
{
private static final String TEST_REQUEST_ID = "printingTestRequestId";
/***************************************************************************
** Register the setup and test actions in the Printing app.
***************************************************************************/
public static void register(QInstance instance, QAppMetaData app)
{
PrintingJobProcesses.register(instance);
registerProfiles(instance);
add(instance, "printingEnrollDevice", "Enroll a print device", List.of(PrintingFacilities.field(instance), field("deviceName", "Device name")));
add(instance, "printingEnablePrinter", "Set printer approval", List.of(deviceField(), printerField(null), new QFieldMetaData("enabled", QFieldType.BOOLEAN).withLabel("Approved for printing").withIsRequired(true)));
add(instance, "printingTestZpl", "Print a test label", List.of(deviceField(), printerField("ZPL"), profileField(false)));
add(instance, "printingTestPdf", "Print a test page", List.of(deviceField(), printerField("PDF"), profileField(true)));
selected(instance, "printingTestSelectedPdf", "Print a test page", "Each selected PDF printer will receive one test page after you continue.");
selected(instance, "printingTestSelectedZpl", "Print a test label", "Each selected ZPL printer will receive one test label after you continue.");
selected(instance, "printingEnableSelectedPrinters", "Approve printers", "The selected printers will be approved for printing after you continue.");
selected(instance, "printingDisableSelectedPrinters", "Disable printers", "The selected printers will stop receiving new print jobs after you continue.");
selected(instance, "printingRemoveSelectedPrinters", "Remove printers", "The selected printers will be removed from Printers, the operator catalog and their connectors after you continue. Job history is kept; sharing a queue again from its device brings it back awaiting approval.");
}
/***************************************************************************
** Fixed native choices keep physical stock and resolution explicit.
***************************************************************************/
private static void registerProfiles(QInstance instance)
{
ArrayList<QPossibleValue<?>> pdf = new ArrayList<>();
ArrayList<QPossibleValue<?>> zpl = new ArrayList<>();
for(TestPrintProfile profile : TestPrintProfile.values())
{
QPossibleValue<String> option = new QPossibleValue<>(profile.name(), profile.getLabel());
if(profile.getDpi() > 0 && profile.getHeightInches() != 6)
{
// PDF is vector, so the printer resolution is irrelevant: one friendly choice per short stock.
if(profile.getDpi() == 300)
{
pdf.add(new QPossibleValue<>(profile.name(), "4 x " + profile.getHeightInches() + " in label"));
}
}
else
{
pdf.add(option);
}
if(profile.getDpi() > 0)
{
zpl.add(option);
}
}
instance.addPossibleValueSource(new QPossibleValueSource().withName("printing_testProfilePdf").withType(QPossibleValueSourceType.ENUM).withEnumValues(pdf));
instance.addPossibleValueSource(new QPossibleValueSource().withName("printing_testProfileZpl").withType(QPossibleValueSourceType.ENUM).withEnumValues(zpl));
}
/***************************************************************************
** The same profile applies to every selected printer, so group matching stock.
***************************************************************************/
private static QFieldMetaData profileField(boolean pdf)
{
return field("testProfile", "Test stock / printer resolution (match every selected printer)")
.withPossibleValueSourceName(pdf ? "printing_testProfilePdf" : "printing_testProfileZpl")
.withDefaultValue(pdf ? TestPrintProfile.LETTER.name() : TestPrintProfile.LABEL_4X6_203.name());
}
/***************************************************************************
** Shared administrator permission for printing apps and processes.
***************************************************************************/
public static QPermissionRules permissionRules()
{
return new QPermissionRules().withLevel(com.kingsrook.qqq.backend.core.model.metadata.permissions.PermissionLevel.HAS_ACCESS_PERMISSION)
.withCustomPermissionChecker(new QCodeReference(PrintingAdminPermission.class));
}
/***************************************************************************
** The user's tenant-scoped device labels replace raw identifiers.
***************************************************************************/
private static QFieldMetaData deviceField()
{
return field("deviceId", "Print device").withPossibleValueSourceName(PrintingTables.DEVICE)
.withPossibleValueSourceFilter(new QQueryFilter(new QFilterCriteria("removed_at", QCriteriaOperator.IS_BLANK)));
}
/***************************************************************************
** Queue row IDs resolve to the agent's printer ID only after authorization.
***************************************************************************/
private static QFieldMetaData printerField(@Nullable String format)
{
QQueryFilter filter = new QQueryFilter(new QFilterCriteria("device_id", QCriteriaOperator.EQUALS, "${input.deviceId}"))
.withCriteria(new QFilterCriteria("removed_at", QCriteriaOperator.IS_BLANK));
if(format != null)
{
filter.withCriteria(new QFilterCriteria("enabled", QCriteriaOperator.EQUALS, 1));
filter.withCriteria(new QFilterCriteria("available", QCriteriaOperator.EQUALS, 1));
filter.withCriteria(new QFilterCriteria("formats", QCriteriaOperator.CONTAINS, format));
}
return field("printerId", "Printer").withPossibleValueSourceName(PrintingTables.PRINTER)
.withPossibleValueSourceFilter(filter).withPossibleValueSourceDependsOn(List.of("deviceId"));
}
/***************************************************************************
** Build standard forms; actions belong on dashboards, not navigation menus.
***************************************************************************/
private static void add(QInstance instance, String name, String label, List<QFieldMetaData> fields)
{
QProcessMetaData process = new QProcessMetaData().withName(name).withLabel(label).withPermissionRules(permissionRules())
.withStep(new QFrontendStepMetaData().withName("details").withLabel(label).withFormFields(fields).withComponent(new QFrontendComponentMetaData().withType(QComponentType.EDIT_FORM)))
.withStep(new QBackendStepMetaData().withName("execute").withCode(new QCodeReference(PrintingProcesses.class)))
.withStep(new QFrontendStepMetaData().withName("result").withLabel("Result").withViewFields(List.of(field("result", "Result"))).withComponent(new QFrontendComponentMetaData().withType(QComponentType.VIEW_FORM)));
if("printingEnrollDevice".equals(name))
{
process.withTableName(PrintingTables.DEVICE).withMinInputRecords(0);
process.withStep(0, new QBackendStepMetaData().withName("prepareEnrollment").withCode(new QCodeReference(PrepareEnrollment.class)));
}
if(name.startsWith("printingTest"))
{
process.withStep(0, new QBackendStepMetaData().withName("prepareTest").withCode(new QCodeReference(PrepareTest.class)));
}
instance.addProcess(process);
}
/***************************************************************************
** Native ETL supports both table selections and individual record actions.
***************************************************************************/
private static void selected(QInstance instance, String name, String label, String preview)
{
Map<String, Serializable> values = new HashMap<>();
values.put(StreamedETLWithFrontendProcess.FIELD_SOURCE_TABLE, PrintingTables.PRINTER);
values.put(StreamedETLWithFrontendProcess.FIELD_DESTINATION_TABLE, PrintingTables.PRINTER);
values.put(StreamedETLWithFrontendProcess.FIELD_SUPPORTS_FULL_VALIDATION, true);
values.put(StreamedETLWithFrontendProcess.FIELD_DO_FULL_VALIDATION, true);
values.put(StreamedETLWithFrontendProcess.FIELD_PREVIEW_MESSAGE, preview);
QProcessMetaData process = StreamedETLWithFrontendProcess.defineProcessMetaData(PrintingExtract.class, SelectedTransform.class, SelectedLoad.class, values)
.withName(name).withLabel(label).withTableName(PrintingTables.PRINTER).withMinInputRecords(1).withPermissionRules(permissionRules());
if(name.startsWith("printingTest"))
{
process.withStep(0, new QFrontendStepMetaData().withName("testProfile").withLabel("Choose matching stock and resolution")
.withFormFields(List.of(profileField(name.endsWith("Pdf")))).withComponent(new QFrontendComponentMetaData().withType(QComponentType.EDIT_FORM)));
process.withStep(0, new QBackendStepMetaData().withName("prepareTest").withCode(new QCodeReference(PrepareTest.class)));
}
instance.addProcess(process);
}
/***************************************************************************
** Required text field for setup forms.
***************************************************************************/
private static QFieldMetaData field(String name, String label)
{
return new QFieldMetaData(name, QFieldType.STRING).withLabel(label).withIsRequired(true).withMaxLength("deviceName".equals(name) ? 1024 : 200);
}
/***************************************************************************
** Find the current instance's runtime, never a shared global cached service.
***************************************************************************/
public static PrintingService currentService() throws QException
{
for(QBitMetaData metadata : QContext.getQInstance().getQBits().values())
{
if(metadata.getConfig() instanceof PrintingQBitConfig config && config.getService() != null)
{
Map<String, List<Serializable>> keys = QContext.getQSession() == null ? null : QContext.getQSession().getSecurityKeyValues();
List<Serializable> tenants = keys == null ? null : keys.get("printing_tenant");
if(tenants == null || !tenants.contains(config.getService().getTenantId()))
{
throw new com.kingsrook.qqq.backend.core.exceptions.QPermissionDeniedException("The current session cannot manage this printing tenant");
}
return config.getService();
}
}
throw new QException("Printing QBit is not configured");
}
/***************************************************************************
** Execute an authorized setup action and return its user-facing result.
***************************************************************************/
@Override
public void run(RunBackendStepInput input, RunBackendStepOutput output) throws QException
{
new PrintingAdminPermission().checkPermissionsThrowing(input, null);
PrintingService service = currentService();
try
{
switch(input.getProcessName())
{
case "printingEnrollDevice" ->
{
JSONObject enrollment = service.createEnrollment(PrintingFacilities.validate(input.getValueString("facilityId")), input.getValueString("deviceName"),
input.getValueString("printingEnrollmentCode"), input.getValueString("printingEnrollmentExpires"));
output.addValue("result", "Enrollment code: " + enrollment.getString("enrollmentCode") + " (expires " + enrollment.getString("expiresAt") + ")");
}
case "printingEnablePrinter" ->
{
QRecord printer = resolvePrinter(input.getValueString("printerId"), input.getValueString("deviceId"));
service.enablePrinter(printer.getValueString("device_id"), printer.getValueString("printer_id"), Boolean.TRUE.equals(input.getValueBoolean("enabled")));
output.addValue("result", "Printer configuration saved.");
}
case "printingTestZpl", "printingTestPdf" ->
{
QRecord printer = resolvePrinter(input.getValueString("printerId"), input.getValueString("deviceId"));
String job = submitTest(printer, "printingTestPdf".equals(input.getProcessName()), input.getValueString("testProfile"), testRequestKey(input, printer));
output.addValue("result", "Queued print job " + job + ". Check Print jobs for submission status.");
}
default -> throw new QException("Unknown printing action");
}
}
catch(java.sql.SQLException | PrintingException exception)
{
throw new QException("Printing action failed: " + exception.getMessage(), exception);
}
}
/***************************************************************************
** Re-read records with the caller's permissions; form values are not trusted.
***************************************************************************/
static QRecord resolvePrinter(String id, @Nullable String deviceId) throws QException
{
GetInput get = new GetInput();
get.setPermissionEnforcement(com.kingsrook.qqq.backend.core.actions.permissions.PermissionEnforcement.ENFORCE);
get.setTableName(PrintingTables.PRINTER);
get.setPrimaryKey(id);
QRecord printer = new GetAction().execute(get).getRecord();
if(printer == null || (deviceId != null && !deviceId.equals(printer.getValueString("device_id"))))
{
throw new QException("Choose an accessible printer belonging to the selected device");
}
return printer;
}
/***************************************************************************
** Send one native test document through the normal durable queue.
***************************************************************************/
static String submitTest(QRecord printer, boolean pdf) throws QException
{
return submitTest(printer, pdf, null);
}
/***************************************************************************
** All built-in document entrypoints share profile validation and generation.
***************************************************************************/
static String submitTest(QRecord printer, boolean pdf, @Nullable String profileName) throws QException
{
return submitTest(printer, pdf, profileName, "test:" + UUID.randomUUID());
}
/***************************************************************************
** The native process persists its request identity before operator review.
***************************************************************************/
private static String testRequestKey(RunBackendStepInput input, QRecord printer) throws QException
{
String request = input.getValueString(TEST_REQUEST_ID);
if(request == null || request.isBlank())
{
throw new QException("Restart the test-print action to obtain a safe request identity");
}
return "native-test:" + request + ":" + printer.getValueString("id");
}
/***************************************************************************
** Generate one immutable document and deduplicate replays of a process load.
***************************************************************************/
private static String submitTest(QRecord printer, boolean pdf, @Nullable String profileName, String key) throws QException
{
try
{
TestPrintProfile profile = TestPrintProfile.resolve(pdf ? "PDF" : "ZPL", profileName);
byte[] bytes = pdf ? PrintingTestDocuments.pdf(profile) : PrintingTestDocuments.zpl(profile);
JSONObject request = new JSONObject().put("deviceId", printer.getValueString("device_id")).put("printerId", printer.getValueString("printer_id"))
.put("title", "QQQ print test").put("format", pdf ? "PDF" : "ZPL").put("contentBase64", Base64.getEncoder().encodeToString(bytes)).put("idempotencyKey", key);
JSONObject options = profile.jobOptions(pdf ? "PDF" : "ZPL");
if(options != null)
{
request.put("options", options);
}
JSONObject job = currentService().submit(request);
return job.getString("jobId");
}
catch(java.sql.SQLException | PrintingException exception)
{
throw new QException("Could not queue test print: " + exception.getMessage(), exception);
}
}
/***************************************************************************
** Prepare once before forms/review; a replay reuses the persisted identity.
***************************************************************************/
public static class PrepareTest implements BackendStep
{
/************************************************************************
** Direct invocation also requires administrator and tenant access.
************************************************************************/
@Override
public void run(RunBackendStepInput input, RunBackendStepOutput output) throws QException
{
new PrintingAdminPermission().checkPermissionsThrowing(input, null);
currentService();
String request = input.getValueString(TEST_REQUEST_ID);
output.addValue(TEST_REQUEST_ID, request == null || request.isBlank() ? UUID.randomUUID().toString() : request);
keepSelection(input, output);
}
}
/***************************************************************************
** A selection action whose first step is a form loses the init request's
** record selection: the UI API passes it only to the init call (as the
** callback filter) and the extract step, which would store it, runs after
** the form. Keep it as the extract step's own queryFilterJson value.
***************************************************************************/
static void keepSelection(RunBackendStepInput input, RunBackendStepOutput output)
{
String kept = input.getValueString("queryFilterJson");
if((kept == null || kept.isBlank()) && input.getCallback() != null && input.getCallback().getQueryFilter() != null)
{
output.addValue("queryFilterJson", com.kingsrook.qqq.backend.core.utils.JsonUtils.toJson(input.getCallback().getQueryFilter()));
}
}
/***************************************************************************
** Prepare one short-lived credential in the authorized process state. The
** database stores its hash and consumed receipt, never its plaintext value.
***************************************************************************/
public static class PrepareEnrollment implements BackendStep
{
/************************************************************************
** Keep credential and expiry stable across form and backend replay.
************************************************************************/
@Override
public void run(RunBackendStepInput input, RunBackendStepOutput output) throws QException
{
new PrintingAdminPermission().checkPermissionsThrowing(input, null);
currentService();
String code = input.getValueString("printingEnrollmentCode");
String expires = input.getValueString("printingEnrollmentExpires");
if(code == null && expires == null)
{
byte[] random = new byte[32];
new java.security.SecureRandom().nextBytes(random);
code = Base64.getUrlEncoder().withoutPadding().encodeToString(random);
expires = java.time.Instant.now().plusSeconds(900).toString();
}
output.addValue("printingEnrollmentCode", code);
output.addValue("printingEnrollmentExpires", expires);
}
}
/***************************************************************************
** Preview selected queues without printing or changing their approval.
***************************************************************************/
public static class SelectedTransform extends AbstractTransformStep implements ProcessSummaryProviderInterface
{
private final ProcessSummaryLine ready = new ProcessSummaryLine(Status.OK, 0, null)
.withSingularFutureMessage("printer will be processed").withPluralFutureMessage("printers will be processed");
/***************************************************************************
** Check the current queue state before showing the review screen.
***************************************************************************/
@Override
public void runOnePage(RunBackendStepInput input, RunBackendStepOutput output) throws QException
{
new PrintingAdminPermission().checkPermissionsThrowing(input, null);
for(QRecord selected : input.getRecords())
{
QRecord printer = resolvePrinter(selected.getValueString("id"), null);
if(input.getProcessName().startsWith("printingTest"))
{
String format = input.getProcessName().endsWith("Pdf") ? "PDF" : "ZPL";
try
{
TestPrintProfile.resolve(format, input.getValueString("testProfile"));
}
catch(PrintingException exception)
{
throw new QException(exception.getMessage(), exception);
}
if(!Integer.valueOf(1).equals(printer.getValueInteger("enabled")) || !Integer.valueOf(1).equals(printer.getValueInteger("available"))
|| !new org.json.JSONArray(printer.getValueString("formats")).toList().contains(format))
{
throw new QException("Printer " + printer.getValueString("name") + " must be exposed, approved, and support " + format);
}
}
ready.incrementCountAndAddPrimaryKey(printer.getValue("id"));
output.getRecords().add(printer);
}
}
/***************************************************************************
** Standard QQQ review summary.
***************************************************************************/
// QQQ ProcessSummaryProvider requires this concrete return type; retain binary/API compatibility.
@SuppressWarnings("NonApiType")
@Override
public ArrayList<ProcessSummaryLineInterface> getProcessSummary(RunBackendStepOutput output, boolean isForResultScreen)
{
return new ArrayList<>(List.of(ready));
}
}
/***************************************************************************
** Apply selected actions only after QQQ's standard review confirmation.
***************************************************************************/
public static class SelectedLoad extends AbstractLoadStep implements ProcessSummaryProviderInterface
{
private final ProcessSummaryLine done = new ProcessSummaryLine(Status.OK, 0, null)
.withSingularPastMessage("printer was processed").withPluralPastMessage("printers were processed");
/***************************************************************************
** Resolve each selection again so withdrawn access is respected.
***************************************************************************/
@Override
public void runOnePage(RunBackendStepInput input, RunBackendStepOutput output) throws QException
{
new PrintingAdminPermission().checkPermissionsThrowing(input, null);
for(QRecord selected : input.getRecords())
{
QRecord printer = resolvePrinter(selected.getValueString("id"), null);
try
{
switch(input.getProcessName())
{
case "printingTestSelectedPdf" -> submitTest(printer, true, input.getValueString("testProfile"), testRequestKey(input, printer));
case "printingTestSelectedZpl" -> submitTest(printer, false, input.getValueString("testProfile"), testRequestKey(input, printer));
case "printingEnableSelectedPrinters", "printingDisableSelectedPrinters" -> currentService().enablePrinter(printer.getValueString("device_id"), printer.getValueString("printer_id"), "printingEnableSelectedPrinters".equals(input.getProcessName()));
case "printingRemoveSelectedPrinters" -> currentService().removePrinter(printer.getValueString("device_id"), printer.getValueString("printer_id"));
default -> throw new QException("Unknown selected printing action");
}
done.incrementCountAndAddPrimaryKey(printer.getValue("id"));
output.getRecords().add(printer);
}
catch(java.sql.SQLException | PrintingException exception)
{
throw new QException("Selected printing action failed: " + exception.getMessage(), exception);
}
}
}
/***************************************************************************
** Standard QQQ result summary links back to the selected queues.
***************************************************************************/
// QQQ ProcessSummaryProvider requires this concrete return type; retain binary/API compatibility.
@SuppressWarnings("NonApiType")
@Override
public ArrayList<ProcessSummaryLineInterface> getProcessSummary(RunBackendStepOutput output, boolean isForResultScreen)
{
return new ArrayList<>(List.of(done));
}
}
/***************************************************************************
** Generate a small valid PDF test page using the existing QQQ PDF dependency.
***************************************************************************/
static byte[] testPdf() throws QException
{
return PrintingTestDocuments.pdf();
}
}