diff --git a/assets/release_notes.md b/assets/release_notes.md index 22fb951b..1c06fbd6 100644 --- a/assets/release_notes.md +++ b/assets/release_notes.md @@ -3,6 +3,8 @@ - Fix incorrect allocation count in build detail widget - Fix "new version available" notice showing in "About" view when app is up to date +- Improved allocation display for build orders +- Multiple bug fixes for build order support ### 1.1.0 - November 2026 --- diff --git a/lib/inventree/build.dart b/lib/inventree/build.dart index b484299a..fc854b35 100644 --- a/lib/inventree/build.dart +++ b/lib/inventree/build.dart @@ -14,6 +14,9 @@ import "package:inventree/inventree/part.dart"; import "package:inventree/inventree/stock.dart"; import "package:inventree/widget/build/build_detail.dart"; +/// Result of a build order action which may run as a background task +enum BuildTaskOutcome { complete, queued, failed } + /* * Class representing a Build Order */ @@ -86,27 +89,20 @@ class InvenTreeBuildOrder extends InvenTreeOrder { // External build bool get external => getBool("external"); - // Return the location where the items will be sourced from - int? get sourceLocationId => getInt("take_from"); + // Return the location where the items will be sourced from (null if not set) + int? get sourceLocationId { + final int id = getInt("take_from"); + return id > 0 ? id : null; + } - // Return the location where the completed items will be stored - int? get destinationId => getInt("destination"); + // Return the location where the completed items will be stored (null if not set) + int? get destinationId { + final int id = getInt("destination"); + return id > 0 ? id : null; + } - String get destinationName => getString("name", subKey: "destination_detail"); - - // Line item information - @override - int get lineItemCount => getInt("item_count", backup: 0); - - // Allocated line item count - int get allocatedLineItemCount => getInt("allocated_line_count", backup: 0); - - // All line items are allocated - bool get areAllLinesAllocated => - lineItemCount > 0 && lineItemCount == allocatedLineItemCount; - - // Output count - int get outputCount => getInt("output_count", backup: 0); + // Note: The server's BuildSerializer does not provide line or output counts. + // These are queried separately (see BuildOrderDetailWidget). // Status code handling // Note: These map to BuildStatus in backend/status_codes.py @@ -122,9 +118,12 @@ class InvenTreeBuildOrder extends InvenTreeOrder { api.BuildOrderStatus.isNameIn(logicalStatus, ["ON_HOLD"]); // Can this build order be completed? - bool get canCompleteOrder { - return isInProgress && outputCount > 0; - } + // Matches the server web UI: offered for any in-production build, + // and the server validates the rest (incomplete outputs, child builds, etc) + bool get canCompleteOrder => isInProgress; + + // API endpoint for marking this build order as complete + String get finishUrl => "${URL}${pk}/finish/"; // Can this build order be issued? bool get canIssue { @@ -173,25 +172,6 @@ class InvenTreeBuildOrder extends InvenTreeOrder { ); } - // Complete a build order - Future completeOrder({ - bool acceptIncomplete = false, - bool acceptUnallocated = false, - bool acceptOverallocated = false, - }) async { - Map data = { - "accept_incomplete": acceptIncomplete.toString(), - "accept_unallocated": acceptUnallocated.toString(), - "accept_overallocated": acceptOverallocated.toString(), - }; - - return await InvenTreeAPI().post( - "${URL}${pk}/complete/", - body: data, - expectedStatusCode: 201, - ); - } - // Put a build order on hold Future hold() async { return await InvenTreeAPI().post( @@ -211,14 +191,41 @@ class InvenTreeBuildOrder extends InvenTreeOrder { } // Auto-allocate stock items for this build order + // The status code is checked by the caller (see autoAllocateOutcome) Future autoAllocate() async { return await InvenTreeAPI().post( "${URL}${pk}/auto-allocate/", body: {}, - expectedStatusCode: 201, + expectedStatusCode: null, ); } + /* + * Interpret the response from the auto-allocate endpoint: + * - API < 465: returns 201 once allocation has completed + * - API >= 465: returns task details (200) - the task is either + * offloaded to the background worker, or run synchronously + */ + static BuildTaskOutcome autoAllocateOutcome(APIResponse response) { + if (response.statusCode == 201) { + return BuildTaskOutcome.complete; + } + + if (response.statusCode != 200) { + return BuildTaskOutcome.failed; + } + + final Map data = response.asMap(); + + if (data["complete"] == true) { + return data["success"] == true + ? BuildTaskOutcome.complete + : BuildTaskOutcome.failed; + } + + return BuildTaskOutcome.queued; + } + // Unallocate all stock from this build order Future unallocateAll() async { return await InvenTreeAPI().post( diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 1a200bee..775f9d8c 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -107,6 +107,9 @@ "allocateAutoDetail": "Automatically allocate required stock items to this order", "@allocateAutoDetail": {}, + "allocateAutoInProgress": "Auto-allocate task in progress", + "@allocateAutoInProgress": {}, + "allocateStock": "Allocate Stock", "@allocateStock": {}, diff --git a/lib/widget/build/build_detail.dart b/lib/widget/build/build_detail.dart index 04e3c711..0789c419 100644 --- a/lib/widget/build/build_detail.dart +++ b/lib/widget/build/build_detail.dart @@ -3,6 +3,7 @@ import "package:flutter_speed_dial/flutter_speed_dial.dart"; import "package:flutter_tabler_icons/flutter_tabler_icons.dart"; import "package:inventree/api.dart"; +import "package:inventree/api_form.dart"; import "package:inventree/app_colors.dart"; import "package:inventree/inventree/stock.dart"; import "package:inventree/l10.dart"; @@ -16,6 +17,7 @@ import "package:inventree/widget/link_icon.dart"; import "package:inventree/widget/notes_list_widget.dart"; import "package:inventree/widget/history_widget.dart"; import "package:inventree/widget/refreshable_state.dart"; +import "package:inventree/widget/snacks.dart"; import "package:inventree/widget/build/build_line_list.dart"; import "package:inventree/widget/build/build_item_list.dart"; import "package:inventree/widget/build/build_output_list.dart"; @@ -39,7 +41,6 @@ class _BuildOrderDetailState extends RefreshableState { int allocatedLineCount = 0; int allocatedItemCount = 0; int totalLineCount = 0; - int outputCount = 0; int attachmentCount = 0; bool showCameraShortcut = true; @@ -152,8 +153,7 @@ class _BuildOrderDetailState extends RefreshableState { } // Unallocate action (if there are allocated items) - if (widget.order.isInProgress && - widget.order.allocatedLineItemCount > 0) { + if (widget.order.isInProgress && allocatedItemCount > 0) { actions.add( SpeedDialChild( child: Icon(TablerIcons.arrow_autofit_up, color: COLOR_DANGER), @@ -205,17 +205,24 @@ class _BuildOrderDetailState extends RefreshableState { } /// Complete this build order + /// Uses a form so the user can choose how to handle unallocated, + /// over-allocated and incomplete stock, and sees any server validation errors Future _completeOrder(BuildContext context) async { - confirmationDialog( + Map> fields = { + "accept_overallocated": {}, + "accept_unallocated": {}, + "accept_incomplete": {}, + }; + + launchApiForm( + context, L10().completeOrder, - L10().completeOrderConfirm, + widget.order.finishUrl, + fields, + method: "POST", icon: TablerIcons.check, - color: COLOR_SUCCESS, - acceptText: L10().complete, - onAccept: () async { - widget.order.completeOrder().then((dynamic) { - refresh(context); - }); + onSuccess: (data) async { + refresh(context); }, ); } @@ -261,9 +268,38 @@ class _BuildOrderDetailState extends RefreshableState { color: Theme.of(context).colorScheme.secondary, acceptText: L10().allocate, onAccept: () async { - widget.order.autoAllocate().then((dynamic) { + final APIResponse response = await widget.order.autoAllocate(); + + // No response (e.g. connection error) - already reported + if (!response.isValid()) { + return; + } + + switch (InvenTreeBuildOrder.autoAllocateOutcome(response)) { + case BuildTaskOutcome.complete: + showSnackIcon(L10().requestSuccessful, success: true); + case BuildTaskOutcome.queued: + showSnackIcon( + L10().allocateAutoInProgress, + icon: TablerIcons.clock, + success: true, + ); + case BuildTaskOutcome.failed: + if (response.successful()) { + // Task ran, but did not succeed + showSnackIcon(L10().requestFailed, success: false); + } else { + showStatusCodeError( + response.url, + response.statusCode, + details: response.data, + ); + } + } + + if (mounted) { refresh(context); - }); + } }, ); } @@ -303,13 +339,33 @@ class _BuildOrderDetailState extends RefreshableState { return; } + final String buildId = widget.order.pk.toString(); + // Count the stock items allocated against this build order - InvenTreeBuildItem() - .count(filters: {"build": widget.order.pk.toString()}) + InvenTreeBuildItem().count(filters: {"build": buildId}).then((int n) { + if (mounted) { + setState(() { + allocatedItemCount = n; + }); + } + }); + + // Count the required line items for this build order + InvenTreeBuildLine().count(filters: {"build": buildId}).then((int n) { + if (mounted) { + setState(() { + totalLineCount = n; + }); + } + }); + + // Count the fully allocated line items for this build order + InvenTreeBuildLine() + .count(filters: {"build": buildId, "allocated": "true"}) .then((int n) { if (mounted) { setState(() { - allocatedItemCount = n; + allocatedLineCount = n; }); } }); @@ -452,33 +508,34 @@ class _BuildOrderDetailState extends RefreshableState { ), ); - // Line items tile - /* - * TODO: Reimplement this item - Color lineColor = Colors.red; - if (widget.order.areAllLinesAllocated) { - lineColor = Colors.green; - } else if (widget.order.allocatedLineItemCount > 0) { - lineColor = Colors.orange; - } + // Line items tile (fully allocated lines / total lines) + if (totalLineCount > 0) { + Color lineColor = COLOR_DANGER; - tiles.add( - ListTile( - title: Text(L10().requiredParts), - subtitle: LinearProgressIndicator( - value: widget.order.lineItemCount > 0 - ? widget.order.allocatedLineItemCount / widget.order.lineItemCount - : 0, - color: lineColor, + if (allocatedLineCount >= totalLineCount) { + lineColor = COLOR_SUCCESS; + } else if (allocatedLineCount > 0) { + lineColor = COLOR_WARNING; + } + + tiles.add( + ListTile( + title: Text(L10().requiredParts), + subtitle: LinearProgressIndicator( + value: allocatedLineCount / totalLineCount, + color: lineColor, + backgroundColor: Theme.of( + context, + ).colorScheme.surfaceContainerHighest, + ), + leading: const Icon(TablerIcons.clipboard_check), + trailing: Text( + "${allocatedLineCount} / ${totalLineCount}", + style: TextStyle(color: lineColor), + ), ), - leading: const Icon(TablerIcons.clipboard_check), - trailing: Text( - "${widget.order.allocatedLineItemCount} / ${widget.order.lineItemCount}", - style: TextStyle(color: lineColor), - ), - ), - ); - */ + ); + } // Output items tiles.add( diff --git a/test/order_models_test.dart b/test/order_models_test.dart index 332b57e4..4173bc43 100644 --- a/test/order_models_test.dart +++ b/test/order_models_test.dart @@ -83,16 +83,10 @@ void main() { var build = InvenTreeBuildOrder.fromJson({ "quantity": 10, "completed": 4, - "item_count": 3, - "allocated_line_count": 3, - "output_count": 2, }); expect(build.progressPercent, equals(40)); expect(build.remaining, equals(6)); - expect(build.lineItemCount, equals(3)); - expect(build.areAllLinesAllocated, isTrue); - expect(build.outputCount, equals(2)); // Progress is clamped build = InvenTreeBuildOrder.fromJson({"quantity": 10, "completed": 15}); @@ -100,22 +94,64 @@ void main() { build = InvenTreeBuildOrder.fromJson({"quantity": 0, "completed": 1}); expect(build.progressPercent, equals(0)); + }); - // No line items - expect(InvenTreeBuildOrder.fromJson({}).areAllLinesAllocated, isFalse); + test("Auto-allocate outcome", () async { + BuildTaskOutcome outcome(int code, [Map? data]) => + InvenTreeBuildOrder.autoAllocateOutcome( + APIResponse(statusCode: code, data: data ?? {}), + ); + + // Older servers (API < 465) complete synchronously with 201 + expect(outcome(201), equals(BuildTaskOutcome.complete)); + + // Task offloaded to the background worker + expect( + outcome(200, { + "task_id": "abc", + "pending": true, + "complete": false, + "success": false, + }), + equals(BuildTaskOutcome.queued), + ); + + // Task run synchronously + expect( + outcome(200, {"task_id": "", "complete": true, "success": true}), + equals(BuildTaskOutcome.complete), + ); + expect( + outcome(200, {"task_id": "", "complete": true, "success": false}), + equals(BuildTaskOutcome.failed), + ); + + // Task could not be run, or request rejected + expect(outcome(404, {"complete": false}), BuildTaskOutcome.failed); + expect(outcome(400), equals(BuildTaskOutcome.failed)); }); test("Details", () async { var build = InvenTreeBuildOrder.fromJson({ "parent": 3, "part_detail": {"name": "Assembly"}, - "destination_detail": {"name": "Store"}, + "take_from": 5, + "destination": 7, }); expect(build.isParentBuild, isTrue); expect(build.parentBuildId, equals(3)); expect(build.partDetail?.name, equals("Assembly")); - expect(build.destinationName, equals("Store")); + expect(build.sourceLocationId, equals(5)); + expect(build.destinationId, equals(7)); + + // Unset locations are null (not 0 or -1) + build = InvenTreeBuildOrder.fromJson({ + "take_from": null, + "destination": null, + }); + expect(build.sourceLocationId, isNull); + expect(build.destinationId, isNull); build = InvenTreeBuildOrder.fromJson({}); expect(build.isParentBuild, isFalse); @@ -139,12 +175,14 @@ void main() { expect(production.canHold, isTrue); expect(production.canCompleteOrder, isTrue); - // Cannot complete without any outputs + // Completion is offered without output counts (the server validates) expect( InvenTreeBuildOrder.fromJson({"status": 20}).canCompleteOrder, - isFalse, + isTrue, ); + expect(production.finishUrl, endsWith("/finish/")); + final onHold = build(25); expect(onHold.isOnHold, isTrue); expect(onHold.canIssue, isTrue);