diff --git a/assets/release_notes.md b/assets/release_notes.md index 291fe793..9c3b2dbc 100644 --- a/assets/release_notes.md +++ b/assets/release_notes.md @@ -10,6 +10,7 @@ - Improved role management for BOM items - Bug fix for stock item test results display - Bug fixes for stock adjustment actions +- Handle timeout of label printing and notify the user ### 1.1.0 - November 2026 --- diff --git a/lib/api.dart b/lib/api.dart index 48cfa130..0d7bbb94 100644 --- a/lib/api.dart +++ b/lib/api.dart @@ -297,6 +297,31 @@ class InvenTreeAPI { String get serverVersion => (serverInfo["version"] ?? "") as String; int get apiVersion => (serverInfo["apiVersion"] ?? 1) as int; + // Background worker status (as last reported by the server) + // Assume the worker is running if the server does not report it + bool get workerRunning => serverInfo["worker_running"] != false; + + /* + * Re-query the background worker status from the server. + * Returns the current status, or null if the server could not be queried. + */ + Future refreshWorkerStatus() async { + final APIResponse response = await get("", expectedStatusCode: null); + + if (!response.successful() || response.data is! Map) { + return null; + } + + final dynamic running = (response.data as Map)["worker_running"]; + + if (running is! bool) { + return null; + } + + serverInfo["worker_running"] = running; + return running; + } + /* API Version Checks * These functions are used to determine if the server supports a particular feature */ diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index c5245037..8cc368f4 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -1247,6 +1247,15 @@ "printLabelSuccess": "Label sent to printer", "@printLabelSuccess": {}, + "printLabelInProgress": "Label printing in progress", + "@printLabelInProgress": {}, + + "printLabelTimeout": "Label printing timed out", + "@printLabelTimeout": {}, + + "printLabelWorkerNotRunning": "Label printing timed out: the server's background worker is not running", + "@printLabelWorkerNotRunning": {}, + "profile": "Profile", "@profile": {}, diff --git a/lib/labels.dart b/lib/labels.dart index 8743a4a7..e0ede349 100644 --- a/lib/labels.dart +++ b/lib/labels.dart @@ -164,42 +164,156 @@ class LabelFormWidgetState extends APIFormWidgetState { } } -Future handlePrintingSuccess( - BuildContext context, - Map data, - int repeatCount, -) async { - const int MAX_REPEATS = 60; +// Maximum number of times to poll the server for print job status +const int PRINT_MAX_POLLS = 60; - int id = (data["pk"] ?? -1) as int; - bool complete = (data["complete"] ?? false) as bool; - bool error = data["errors"] != null; - String? output = data["output"] as String?; +// Delay between successive polls of the print job status +const Duration PRINT_POLL_INTERVAL = Duration(seconds: 1); - if (complete) { - if (output != null && output.isNotEmpty) { - // An output was generated - we can download it! - showSnackIcon(L10().downloading, success: true); - InvenTreeAPI().downloadFile(output); - } else { - // Label was offloaded, likely to an external printer - showSnackIcon(L10().printLabelSuccess, success: true); +// Final state of a label print job +enum LabelPrintStatus { + complete, // Job completed (output may be available for download) + failed, // Server reported an error, or the job cannot be tracked + timedOut, // Job did not complete within the polling window +} + +class LabelPrintResult { + const LabelPrintResult(this.status, {this.data = const {}, this.error}); + + final LabelPrintStatus status; + + // Most recent DataOutput data received from the server + final Map data; + + // Error message (if available) + final String? error; + + String get output => (data["output"] ?? "").toString(); +} + +/* + * Extract an error message from the "errors" field of a DataOutput object. + * Returns null if no errors are reported. + */ +String? printOutputError(Map data) { + final dynamic errors = data["errors"]; + + if (errors == null) { + return null; + } + + dynamic error = errors; + + // e.g. {"error": "message"} or {"field": ["message"]} + if (error is Map) { + if (error.isEmpty) return null; + error = error["error"] ?? error.values.first; + } + + if (error is List) { + if (error.isEmpty) return null; + error = error.first; + } + + final String message = error.toString().trim(); + + return message.isEmpty ? null : message; +} + +/* + * Wait for a label print job (DataOutput) to complete on the server. + * + * Polls the job status at [interval], up to [maxPolls] times. + * Transient request failures are retried until the polling window expires. + */ +Future waitForPrintOutput( + Map data, { + Future Function(String url)? fetch, + int maxPolls = PRINT_MAX_POLLS, + Duration interval = PRINT_POLL_INTERVAL, +}) async { + final request = fetch ?? (String url) => InvenTreeAPI().get(url); + + final int id = (data["pk"] is int) ? data["pk"] as int : -1; + + for (int poll = 0; ; poll++) { + final String? error = printOutputError(data); + + if (error != null) { + return LabelPrintResult( + LabelPrintStatus.failed, + data: data, + error: error, + ); } - } else if (error) { - showSnackIcon(L10().printLabelFailure, success: false); - } else if (repeatCount < MAX_REPEATS && id > 0) { - // Printing is not yet complete, but we have a valid output ID - Future.delayed(Duration(milliseconds: 1000), () async { - // Re-query the printing status - InvenTreeAPI().get("data-output/$id/").then((response) { - if (response.statusCode == 200) { - if (response.data is Map) { - final responseData = response.data as Map; - handlePrintingSuccess(context, responseData, repeatCount + 1); - } - } - }); - }); + + if (data["complete"] == true) { + return LabelPrintResult(LabelPrintStatus.complete, data: data); + } + + if (id <= 0) { + // No job ID - cannot track progress + return LabelPrintResult(LabelPrintStatus.failed, data: data); + } + + if (poll >= maxPolls) { + return LabelPrintResult(LabelPrintStatus.timedOut, data: data); + } + + await Future.delayed(interval); + + final APIResponse response = await request("data-output/${id}/"); + + if (response.successful() && response.data is Map) { + data = Map.from(response.data as Map); + } else if (response.isValid() && response.statusCode >= 400) { + // Client error (e.g. job deleted, or permission denied) - stop polling + return LabelPrintResult(LabelPrintStatus.failed, data: data); + } + + // Otherwise (no response or server error), try again + } +} + +/* + * Handle the server response after a label print request is submitted. + * Waits for the print job to complete, and notifies the user of the outcome. + */ +Future handlePrintingSuccess(Map data) async { + if (data["complete"] != true && printOutputError(data) == null) { + // Let the user know that the job has been queued + showSnackIcon(L10().printLabelInProgress, success: true); + } + + final LabelPrintResult result = await waitForPrintOutput(data); + + switch (result.status) { + case LabelPrintStatus.complete: + if (result.output.isNotEmpty) { + // An output was generated - we can download it! + showSnackIcon(L10().downloading, success: true); + InvenTreeAPI().downloadFile(result.output); + } else { + // Label was offloaded, likely to an external printer + showSnackIcon(L10().printLabelSuccess, success: true); + } + case LabelPrintStatus.failed: + showSnackIcon( + result.error == null + ? L10().printLabelFailure + : "${L10().printLabelFailure}: ${result.error}", + success: false, + ); + case LabelPrintStatus.timedOut: + // Check whether the background worker is processing tasks + final bool? running = await InvenTreeAPI().refreshWorkerStatus(); + + showSnackIcon( + running == false + ? L10().printLabelWorkerNotRunning + : L10().printLabelTimeout, + success: false, + ); } } @@ -276,7 +390,7 @@ Future selectAndPrintLabel( modelData: {"plugin": defaultPlugin, "template": defaultTemplate}, formHandler: formHandler, onSuccess: (data) async { - handlePrintingSuccess(context, data, 0); + handlePrintingSuccess(data); }, ); } diff --git a/test/label_print_test.dart b/test/label_print_test.dart new file mode 100644 index 00000000..14745de2 --- /dev/null +++ b/test/label_print_test.dart @@ -0,0 +1,181 @@ +/* + * Tests for label print job handling (regression tests for B19). + * + * Previously, a print job which did not complete within the polling + * window (or could not be polled) failed silently. + * + * The server responses are simulated, so no server is required. + */ + +import "package:flutter_test/flutter_test.dart"; +import "package:inventree/api.dart"; +import "package:inventree/labels.dart"; + +// Simulate a sequence of server responses to "data-output//" requests. +// The final response is repeated once the sequence is exhausted. +class FakeOutputServer { + FakeOutputServer(this.responses); + + final List responses; + final List requests = []; + + Future fetch(String url) async { + requests.add(url); + final int idx = requests.length - 1; + return responses[idx < responses.length ? idx : responses.length - 1]; + } +} + +APIResponse ok(Map data) => + APIResponse(statusCode: 200, data: data); + +Map job({ + bool complete = false, + dynamic errors, + String? output, +}) => {"pk": 12, "complete": complete, "errors": errors, "output": output}; + +void main() { + Future wait( + Map data, + FakeOutputServer server, { + int maxPolls = 5, + }) => waitForPrintOutput( + data, + fetch: server.fetch, + maxPolls: maxPolls, + interval: Duration.zero, + ); + + group("Print Job Status:", () { + test("Complete immediately (synchronous print)", () async { + final server = FakeOutputServer([]); + + final result = await wait( + job(complete: true, output: "/media/label.pdf"), + server, + ); + + expect(result.status, equals(LabelPrintStatus.complete)); + expect(result.output, equals("/media/label.pdf")); + expect(server.requests, isEmpty); + }); + + test("Completes after polling", () async { + final server = FakeOutputServer([ + ok(job()), + ok(job()), + ok(job(complete: true)), + ]); + + final result = await wait(job(), server); + + expect(result.status, equals(LabelPrintStatus.complete)); + expect(result.output, isEmpty); + expect(server.requests, hasLength(3)); + expect(server.requests.first, equals("data-output/12/")); + }); + + test("Server reports an error", () async { + final server = FakeOutputServer([ + ok(job()), + ok(job(errors: {"error": "Printer offline"})), + ]); + + final result = await wait(job(), server); + + expect(result.status, equals(LabelPrintStatus.failed)); + expect(result.error, equals("Printer offline")); + }); + + test("Times out (previously silent)", () async { + final server = FakeOutputServer([ok(job())]); + + final result = await wait(job(), server, maxPolls: 5); + + expect(result.status, equals(LabelPrintStatus.timedOut)); + expect(server.requests, hasLength(5)); + }); + + test("Transient poll failures are retried", () async { + final server = FakeOutputServer([ + APIResponse(), // No response from server + APIResponse(statusCode: 503), + ok(job(complete: true)), + ]); + + final result = await wait(job(), server); + + expect(result.status, equals(LabelPrintStatus.complete)); + expect(server.requests, hasLength(3)); + }); + + test("Persistent poll failures time out", () async { + final server = FakeOutputServer([APIResponse()]); + + final result = await wait(job(), server, maxPolls: 3); + + expect(result.status, equals(LabelPrintStatus.timedOut)); + }); + + test("Job not found stops polling", () async { + final server = FakeOutputServer([APIResponse(statusCode: 404)]); + + final result = await wait(job(), server); + + expect(result.status, equals(LabelPrintStatus.failed)); + expect(server.requests, hasLength(1)); + }); + + test("Missing job ID fails (previously silent)", () async { + final server = FakeOutputServer([]); + + final result = await wait({"complete": false}, server); + + expect(result.status, equals(LabelPrintStatus.failed)); + expect(server.requests, isEmpty); + }); + }); + + group("Print Job Errors:", () { + test("No errors", () { + expect(printOutputError(job()), isNull); + expect(printOutputError(job(errors: {})), isNull); + expect(printOutputError(job(errors: [])), isNull); + expect(printOutputError(job(errors: "")), isNull); + }); + + test("Error formats", () { + expect(printOutputError(job(errors: {"error": "A"})), equals("A")); + expect( + printOutputError( + job( + errors: { + "copies": ["Must be positive"], + }, + ), + ), + equals("Must be positive"), + ); + expect(printOutputError(job(errors: ["B", "C"])), equals("B")); + expect(printOutputError(job(errors: "D")), equals("D")); + }); + }); + + group("Worker Status:", () { + test("Defaults to running when not reported", () { + final api = InvenTreeAPI(); + final saved = Map.from(api.serverInfo); + + api.serverInfo.remove("worker_running"); + expect(api.workerRunning, isTrue); + + api.serverInfo["worker_running"] = false; + expect(api.workerRunning, isFalse); + + api.serverInfo + ..clear() + ..addAll(saved); + }); + }); +}