mirror of
https://github.com/inventree/inventree-app.git
synced 2025-08-01 18:21:36 +00:00
Barcode refactor (#363)
* Move barcode.dart * Fix * Refactoring barcode scanner code: - Abstract the "controller" class (for future development) - Break barcode scanning code out into multiple files - Add CameraBarcodeController class (qr_code_scanner) * Add await * Make barcode scan delay configurable * remove unused import * Handle camera exceptions * Improve sequencing for camera scanner - Show loading overlay - Prevent reload if view is no longer mounted * Update docstring * Update release notes
This commit is contained in:
582
lib/barcode/barcode.dart
Normal file
582
lib/barcode/barcode.dart
Normal file
@@ -0,0 +1,582 @@
|
||||
import "package:flutter/material.dart";
|
||||
|
||||
import "package:flutter_speed_dial/flutter_speed_dial.dart";
|
||||
import "package:font_awesome_flutter/font_awesome_flutter.dart";
|
||||
import "package:one_context/one_context.dart";
|
||||
|
||||
|
||||
import "package:inventree/api.dart";
|
||||
import "package:inventree/helpers.dart";
|
||||
import "package:inventree/l10.dart";
|
||||
|
||||
import "package:inventree/barcode/camera_controller.dart";
|
||||
import "package:inventree/barcode/controller.dart";
|
||||
import "package:inventree/barcode/handler.dart";
|
||||
import "package:inventree/barcode/tones.dart";
|
||||
|
||||
import "package:inventree/inventree/company.dart";
|
||||
import "package:inventree/inventree/part.dart";
|
||||
import "package:inventree/inventree/purchase_order.dart";
|
||||
import "package:inventree/inventree/stock.dart";
|
||||
|
||||
import "package:inventree/widget/dialogs.dart";
|
||||
import "package:inventree/widget/location_display.dart";
|
||||
import "package:inventree/widget/part_detail.dart";
|
||||
import "package:inventree/widget/purchase_order_detail.dart";
|
||||
import "package:inventree/widget/refreshable_state.dart";
|
||||
import "package:inventree/widget/snacks.dart";
|
||||
import "package:inventree/widget/stock_detail.dart";
|
||||
import "package:inventree/widget/supplier_part_detail.dart";
|
||||
|
||||
|
||||
/*
|
||||
* Return a new BarcodeController instance
|
||||
*/
|
||||
InvenTreeBarcodeController barcodeController(BarcodeHandler handler) {
|
||||
// TODO: Make this configurable
|
||||
return CameraBarcodeController(handler);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Class for general barcode scanning.
|
||||
* Scan *any* barcode without context, and then redirect app to correct view.
|
||||
*
|
||||
* Handles scanning of:
|
||||
*
|
||||
* - StockLocation
|
||||
* - StockItem
|
||||
* - Part
|
||||
* - SupplierPart
|
||||
* - PurchaseOrder
|
||||
*/
|
||||
class BarcodeScanHandler extends BarcodeHandler {
|
||||
|
||||
@override
|
||||
String getOverlayText(BuildContext context) => L10().barcodeScanGeneral;
|
||||
|
||||
@override
|
||||
Future<void> onBarcodeUnknown(Map<String, dynamic> data) async {
|
||||
|
||||
barcodeFailureTone();
|
||||
|
||||
showSnackIcon(
|
||||
L10().barcodeNoMatch,
|
||||
icon: FontAwesomeIcons.circleExclamation,
|
||||
success: false,
|
||||
);
|
||||
}
|
||||
|
||||
/*
|
||||
* Response when a "Part" instance is scanned
|
||||
*/
|
||||
Future<void> handlePart(int pk) async {
|
||||
|
||||
var part = await InvenTreePart().get(pk);
|
||||
|
||||
if (part is InvenTreePart) {
|
||||
OneContext().pop();
|
||||
OneContext().push(MaterialPageRoute(builder: (context) => PartDetailWidget(part)));
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Response when a "StockItem" instance is scanned
|
||||
*/
|
||||
Future<void> handleStockItem(int pk) async {
|
||||
|
||||
var item = await InvenTreeStockItem().get(pk);
|
||||
|
||||
if (item is InvenTreeStockItem) {
|
||||
OneContext().pop();
|
||||
OneContext().push(MaterialPageRoute(
|
||||
builder: (context) => StockDetailWidget(item)));
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Response when a "StockLocation" instance is scanned
|
||||
*/
|
||||
Future<void> handleStockLocation(int pk) async {
|
||||
|
||||
var loc = await InvenTreeStockLocation().get(pk);
|
||||
|
||||
if (loc is InvenTreeStockLocation) {
|
||||
OneContext().pop();
|
||||
OneContext().navigator.push(MaterialPageRoute(
|
||||
builder: (context) => LocationDisplayWidget(loc)));
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Response when a "SupplierPart" instance is scanned
|
||||
*/
|
||||
Future<void> handleSupplierPart(int pk) async {
|
||||
|
||||
var supplierpart = await InvenTreeSupplierPart().get(pk);
|
||||
|
||||
if (supplierpart is InvenTreeSupplierPart) {
|
||||
OneContext().pop();
|
||||
OneContext().push(MaterialPageRoute(
|
||||
builder: (context) => SupplierPartDetailWidget(supplierpart)));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Response when a "PurchaseOrder" instance is scanned
|
||||
*/
|
||||
Future<void> handlePurchaseOrder(int pk) async {
|
||||
var order = await InvenTreePurchaseOrder().get(pk);
|
||||
|
||||
if (order is InvenTreePurchaseOrder) {
|
||||
OneContext().pop();
|
||||
OneContext().push(MaterialPageRoute(
|
||||
builder: (context) => PurchaseOrderDetailWidget(order)));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@override
|
||||
Future<void> onBarcodeMatched(Map<String, dynamic> data) async {
|
||||
int pk = -1;
|
||||
|
||||
String model = "";
|
||||
|
||||
// The following model types can be matched with barcodes
|
||||
List<String> validModels = [
|
||||
"part",
|
||||
"stockitem",
|
||||
"stocklocation",
|
||||
"supplierpart",
|
||||
];
|
||||
|
||||
|
||||
if (InvenTreeAPI().supportsOrderBarcodes) {
|
||||
validModels.add("purchaseorder");
|
||||
}
|
||||
|
||||
for (var key in validModels) {
|
||||
if (data.containsKey(key)) {
|
||||
pk = (data[key]?["pk"] ?? -1) as int;
|
||||
|
||||
// Break on the first valid match found
|
||||
if (pk > 0) {
|
||||
model = key;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A valid result has been found
|
||||
if (pk > 0 && model.isNotEmpty) {
|
||||
|
||||
barcodeSuccessTone();
|
||||
|
||||
switch (model) {
|
||||
case "part":
|
||||
await handlePart(pk);
|
||||
return;
|
||||
case "stockitem":
|
||||
await handleStockItem(pk);
|
||||
return;
|
||||
case "stocklocation":
|
||||
await handleStockLocation(pk);
|
||||
return;
|
||||
case "supplierpart":
|
||||
await handleSupplierPart(pk);
|
||||
return;
|
||||
case "purchaseorder":
|
||||
await handlePurchaseOrder(pk);
|
||||
return;
|
||||
default:
|
||||
// Fall through to failure state
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// If we get here, we have not found a valid barcode result!
|
||||
barcodeFailureTone();
|
||||
|
||||
showSnackIcon(
|
||||
L10().barcodeUnknown,
|
||||
success: false,
|
||||
onAction: () {
|
||||
|
||||
OneContext().showDialog(
|
||||
builder: (BuildContext context) => SimpleDialog(
|
||||
title: Text(L10().unknownResponse),
|
||||
children: <Widget>[
|
||||
ListTile(
|
||||
title: Text(L10().responseData),
|
||||
subtitle: Text(data.toString()),
|
||||
)
|
||||
],
|
||||
)
|
||||
);
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Generic class for scanning a StockLocation.
|
||||
*
|
||||
* - Validates that the scanned barcode matches a valid StockLocation
|
||||
* - Runs a "callback" function if a valid StockLocation is found
|
||||
*/
|
||||
class BarcodeScanStockLocationHandler extends BarcodeHandler {
|
||||
|
||||
@override
|
||||
String getOverlayText(BuildContext context) => L10().barcodeScanLocation;
|
||||
|
||||
@override
|
||||
Future<void> onBarcodeMatched(Map<String, dynamic> data) async {
|
||||
|
||||
// We expect that the barcode points to a 'stocklocation'
|
||||
if (data.containsKey("stocklocation")) {
|
||||
int _loc = (data["stocklocation"]["pk"] ?? -1) as int;
|
||||
|
||||
// A valid stock location!
|
||||
if (_loc > 0) {
|
||||
|
||||
debug("Scanned stock location ${_loc}");
|
||||
|
||||
final bool result = await onLocationScanned(_loc);
|
||||
|
||||
if (result && OneContext.hasContext) {
|
||||
OneContext().pop();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If we get to this point, something went wrong during the scan process
|
||||
barcodeFailureTone();
|
||||
|
||||
showSnackIcon(
|
||||
L10().invalidStockLocation,
|
||||
success: false,
|
||||
);
|
||||
}
|
||||
|
||||
// Callback function which runs when a valid StockLocation is scanned
|
||||
// If this function returns 'true' the barcode scanning dialog will be closed
|
||||
Future<bool> onLocationScanned(int locationId) async {
|
||||
// Re-implement this for particular subclass
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Generic class for scanning a StockItem
|
||||
*
|
||||
* - Validates that the scanned barcode matches a valid StockItem
|
||||
* - Runs a "callback" function if a valid StockItem is found
|
||||
*/
|
||||
class BarcodeScanStockItemHandler extends BarcodeHandler {
|
||||
|
||||
@override
|
||||
String getOverlayText(BuildContext context) => L10().barcodeScanItem;
|
||||
|
||||
@override
|
||||
Future<void> onBarcodeMatched(Map<String, dynamic> data) async {
|
||||
// We expect that the barcode points to a 'stockitem'
|
||||
if (data.containsKey("stockitem")) {
|
||||
int _item = (data["stockitem"]["pk"] ?? -1) as int;
|
||||
|
||||
// A valid stock location!
|
||||
if (_item > 0) {
|
||||
|
||||
barcodeSuccessTone();
|
||||
|
||||
bool result = await onItemScanned(_item);
|
||||
|
||||
if (result && OneContext.hasContext) {
|
||||
OneContext().pop();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If we get to this point, something went wrong during the scan process
|
||||
barcodeFailureTone();
|
||||
|
||||
showSnackIcon(
|
||||
L10().invalidStockItem,
|
||||
success: false,
|
||||
);
|
||||
}
|
||||
|
||||
// Callback function which runs when a valid StockItem is scanned
|
||||
Future<bool> onItemScanned(int itemId) async {
|
||||
// Re-implement this for particular subclass
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Barcode handler for scanning a provided StockItem into a scanned StockLocation.
|
||||
*
|
||||
* - The class is initialized by passing a valid StockItem object
|
||||
* - Expects to scan barcode for a StockLocation
|
||||
* - The StockItem is transferred into the scanned location
|
||||
*/
|
||||
class StockItemScanIntoLocationHandler extends BarcodeScanStockLocationHandler {
|
||||
|
||||
StockItemScanIntoLocationHandler(this.item);
|
||||
|
||||
final InvenTreeStockItem item;
|
||||
|
||||
@override
|
||||
Future<bool> onLocationScanned(int locationId) async {
|
||||
|
||||
final result = await item.transferStock(locationId);
|
||||
|
||||
if (result) {
|
||||
barcodeSuccessTone();
|
||||
showSnackIcon(L10().barcodeScanIntoLocationSuccess, success: true);
|
||||
} else {
|
||||
barcodeFailureTone();
|
||||
showSnackIcon(L10().barcodeScanIntoLocationFailure, success: false);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Barcode handler for scanning stock item(s) into the specified StockLocation.
|
||||
*
|
||||
* - The class is initialized by passing a valid StockLocation object
|
||||
* - Expects to scan a barcode for a StockItem
|
||||
* - The scanned StockItem is transferred into the provided StockLocation
|
||||
*/
|
||||
class StockLocationScanInItemsHandler extends BarcodeScanStockItemHandler {
|
||||
|
||||
StockLocationScanInItemsHandler(this.location);
|
||||
|
||||
final InvenTreeStockLocation location;
|
||||
|
||||
@override
|
||||
String getOverlayText(BuildContext context) => L10().barcodeScanItem;
|
||||
|
||||
@override
|
||||
Future<bool> onItemScanned(int itemId) async {
|
||||
|
||||
final InvenTreeStockItem? item = await InvenTreeStockItem().get(itemId) as InvenTreeStockItem?;
|
||||
|
||||
bool result = false;
|
||||
|
||||
if (item != null) {
|
||||
|
||||
// Item is already *in* the specified location
|
||||
if (item.locationId == location.pk) {
|
||||
barcodeFailureTone();
|
||||
showSnackIcon(L10().itemInLocation, success: true);
|
||||
return false;
|
||||
} else {
|
||||
result = await item.transferStock(location.pk);
|
||||
}
|
||||
}
|
||||
|
||||
showSnackIcon(
|
||||
result ? L10().barcodeScanIntoLocationSuccess : L10().barcodeScanIntoLocationFailure,
|
||||
success: result
|
||||
);
|
||||
|
||||
// We always return false here, to ensure the barcode scan dialog remains open
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Barcode handler class for scanning a StockLocation into another StockLocation
|
||||
*
|
||||
* - The class is initialized by passing a valid StockLocation object
|
||||
* - Expects to scan barcode for another *parent* StockLocation
|
||||
* - The scanned StockLocation is set as the "parent" of the provided StockLocation
|
||||
*/
|
||||
class ScanParentLocationHandler extends BarcodeScanStockLocationHandler {
|
||||
|
||||
ScanParentLocationHandler(this.location);
|
||||
|
||||
final InvenTreeStockLocation location;
|
||||
|
||||
@override
|
||||
Future<bool> onLocationScanned(int locationId) async {
|
||||
|
||||
final response = await location.update(
|
||||
values: {
|
||||
"parent": locationId.toString(),
|
||||
},
|
||||
expectedStatusCode: null,
|
||||
);
|
||||
|
||||
switch (response.statusCode) {
|
||||
case 200:
|
||||
case 201:
|
||||
barcodeSuccessTone();
|
||||
showSnackIcon(L10().barcodeScanIntoLocationSuccess, success: true);
|
||||
return true;
|
||||
case 400: // Invalid parent location chosen
|
||||
barcodeFailureTone();
|
||||
showSnackIcon(L10().invalidStockLocation, success: false);
|
||||
return false;
|
||||
default:
|
||||
barcodeFailureTone();
|
||||
showSnackIcon(
|
||||
L10().barcodeScanIntoLocationFailure,
|
||||
success: false,
|
||||
actionText: L10().details,
|
||||
onAction: () {
|
||||
showErrorDialog(
|
||||
L10().barcodeError,
|
||||
response: response,
|
||||
);
|
||||
}
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Barcode handler for finding a "unique" barcode (one that does not match an item in the database)
|
||||
*/
|
||||
class UniqueBarcodeHandler extends BarcodeHandler {
|
||||
|
||||
UniqueBarcodeHandler(this.callback, {this.overlayText = ""});
|
||||
|
||||
// Callback function when a "unique" barcode hash is found
|
||||
final Function(String) callback;
|
||||
|
||||
final String overlayText;
|
||||
|
||||
@override
|
||||
String getOverlayText(BuildContext context) {
|
||||
if (overlayText.isEmpty) {
|
||||
return L10().barcodeScanAssign;
|
||||
} else {
|
||||
return overlayText;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> onBarcodeMatched(Map<String, dynamic> data) async {
|
||||
|
||||
barcodeFailureTone();
|
||||
|
||||
// If the barcode is known, we can"t assign it to the stock item!
|
||||
showSnackIcon(
|
||||
L10().barcodeInUse,
|
||||
icon: Icons.qr_code,
|
||||
success: false
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> onBarcodeUnknown(Map<String, dynamic> data) async {
|
||||
// If the barcode is unknown, we *can* assign it to the stock item!
|
||||
|
||||
if (!data.containsKey("hash") && !data.containsKey("barcode_hash")) {
|
||||
showServerError(
|
||||
"barcode/",
|
||||
L10().missingData,
|
||||
L10().barcodeMissingHash,
|
||||
);
|
||||
} else {
|
||||
String barcode;
|
||||
|
||||
if (InvenTreeAPI().supportModernBarcodes) {
|
||||
barcode = (data["barcode_data"] ?? "") as String;
|
||||
} else {
|
||||
// Legacy barcode API
|
||||
barcode = (data["hash"] ?? data["barcode_hash"] ?? "") as String;
|
||||
}
|
||||
|
||||
if (barcode.isEmpty) {
|
||||
barcodeFailureTone();
|
||||
|
||||
showSnackIcon(
|
||||
L10().barcodeError,
|
||||
success: false,
|
||||
);
|
||||
} else {
|
||||
|
||||
barcodeSuccessTone();
|
||||
|
||||
// Close the barcode scanner
|
||||
if (OneContext.hasContext) {
|
||||
OneContext().pop();
|
||||
}
|
||||
|
||||
callback(barcode);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Future<void> scanQrCode(BuildContext context) async {
|
||||
Navigator.push(context, MaterialPageRoute(builder: (context) => barcodeController(BarcodeScanHandler())));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
SpeedDialChild customBarcodeAction(BuildContext context, RefreshableState state, String barcode, String model, int pk) {
|
||||
|
||||
if (barcode.isEmpty) {
|
||||
return SpeedDialChild(
|
||||
label: L10().barcodeAssign,
|
||||
child: Icon(Icons.barcode_reader),
|
||||
onTap: () {
|
||||
var handler = UniqueBarcodeHandler((String barcode) {
|
||||
InvenTreeAPI().linkBarcode({
|
||||
model: pk.toString(),
|
||||
"barcode": barcode,
|
||||
}).then((bool result) {
|
||||
showSnackIcon(
|
||||
result ? L10().barcodeAssigned : L10().barcodeNotAssigned,
|
||||
success: result
|
||||
);
|
||||
|
||||
state.refresh(context);
|
||||
});
|
||||
});
|
||||
|
||||
Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (context) => barcodeController(handler)
|
||||
)
|
||||
);
|
||||
}
|
||||
);
|
||||
} else {
|
||||
return SpeedDialChild(
|
||||
child: Icon(Icons.barcode_reader),
|
||||
label: L10().barcodeUnassign,
|
||||
onTap: () {
|
||||
InvenTreeAPI().unlinkBarcode({
|
||||
model: pk.toString()
|
||||
}).then((bool result) {
|
||||
showSnackIcon(
|
||||
result ? L10().requestSuccessful : L10().requestFailed,
|
||||
success: result,
|
||||
);
|
||||
|
||||
state.refresh(context);
|
||||
});
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
154
lib/barcode/camera_controller.dart
Normal file
154
lib/barcode/camera_controller.dart
Normal file
@@ -0,0 +1,154 @@
|
||||
import "dart:io";
|
||||
import "package:flutter/material.dart";
|
||||
|
||||
import "package:qr_code_scanner/qr_code_scanner.dart";
|
||||
|
||||
import "package:inventree/l10.dart";
|
||||
|
||||
import "package:inventree/barcode/handler.dart";
|
||||
import "package:inventree/barcode/controller.dart";
|
||||
|
||||
/*
|
||||
* Barcode controller which uses the device's camera to scan barcodes.
|
||||
* Under the hood it uses the qr_code_scanner package.
|
||||
*/
|
||||
class CameraBarcodeController extends InvenTreeBarcodeController {
|
||||
|
||||
const CameraBarcodeController(BarcodeHandler handler, {Key? key}) : super(handler, key: key);
|
||||
|
||||
@override
|
||||
State<StatefulWidget> createState() => _CameraBarcodeControllerState();
|
||||
|
||||
}
|
||||
|
||||
|
||||
class _CameraBarcodeControllerState extends InvenTreeBarcodeControllerState {
|
||||
|
||||
_CameraBarcodeControllerState() : super();
|
||||
|
||||
QRViewController? _controller;
|
||||
|
||||
bool flash_status = false;
|
||||
|
||||
/* Callback function when the Barcode scanner view is initially created */
|
||||
void _onViewCreated(BuildContext context, QRViewController controller) {
|
||||
_controller = controller;
|
||||
|
||||
controller.scannedDataStream.listen((barcode) {
|
||||
handleBarcodeData(barcode.code);
|
||||
});
|
||||
}
|
||||
|
||||
// In order to get hot reload to work we need to pause the camera if the platform
|
||||
// is android, or resume the camera if the platform is iOS.
|
||||
@override
|
||||
void reassemble() {
|
||||
super.reassemble();
|
||||
|
||||
if (mounted) {
|
||||
if (Platform.isAndroid) {
|
||||
_controller!.pauseCamera();
|
||||
}
|
||||
|
||||
_controller!.resumeCamera();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_controller?.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> pauseScan() async {
|
||||
try {
|
||||
await _controller?.pauseCamera();
|
||||
} on CameraException {
|
||||
// do nothing
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> resumeScan() async {
|
||||
try {
|
||||
await _controller?.resumeCamera();
|
||||
} on CameraException {
|
||||
// do nothing
|
||||
}
|
||||
}
|
||||
|
||||
// Toggle the status of the camera flash
|
||||
Future<void> updateFlashStatus() async {
|
||||
final bool? status = await _controller?.getFlashStatus();
|
||||
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
flash_status = status != null && status;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: Text(L10().scanBarcode),
|
||||
actions: [
|
||||
IconButton(
|
||||
icon: Icon(Icons.flip_camera_android),
|
||||
onPressed: () {
|
||||
_controller?.flipCamera();
|
||||
}
|
||||
),
|
||||
IconButton(
|
||||
icon: flash_status ? Icon(Icons.flash_off) : Icon(Icons.flash_on),
|
||||
onPressed: () {
|
||||
_controller?.toggleFlash();
|
||||
updateFlashStatus();
|
||||
},
|
||||
)
|
||||
],
|
||||
),
|
||||
body: Stack(
|
||||
children: <Widget>[
|
||||
Column(
|
||||
children: [
|
||||
Expanded(
|
||||
child: QRView(
|
||||
key: barcodeControllerKey,
|
||||
onQRViewCreated: (QRViewController controller) {
|
||||
_onViewCreated(context, controller);
|
||||
},
|
||||
overlay: QrScannerOverlayShape(
|
||||
borderColor: Colors.red,
|
||||
borderRadius: 10,
|
||||
borderLength: 30,
|
||||
borderWidth: 10,
|
||||
cutOutSize: 300,
|
||||
),
|
||||
)
|
||||
)
|
||||
]
|
||||
),
|
||||
Center(
|
||||
child: Column(
|
||||
children: [
|
||||
Spacer(),
|
||||
Padding(
|
||||
child: Text(widget.handler.getOverlayText(context),
|
||||
style: TextStyle(
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Colors.white),
|
||||
),
|
||||
padding: EdgeInsets.all(20),
|
||||
),
|
||||
]
|
||||
)
|
||||
)
|
||||
],
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
108
lib/barcode/controller.dart
Normal file
108
lib/barcode/controller.dart
Normal file
@@ -0,0 +1,108 @@
|
||||
import "package:flutter/material.dart";
|
||||
import "package:one_context/one_context.dart";
|
||||
|
||||
import "package:inventree/preferences.dart";
|
||||
|
||||
import "package:inventree/barcode/handler.dart";
|
||||
|
||||
import "package:inventree/widget/progress.dart";
|
||||
|
||||
/*
|
||||
* Generic class which provides a barcode scanner interface.
|
||||
*
|
||||
* When the controller is instantiated, it is passed a "handler" class,
|
||||
* which is used to process the scanned barcode.
|
||||
*/
|
||||
class InvenTreeBarcodeController extends StatefulWidget {
|
||||
|
||||
const InvenTreeBarcodeController(this.handler, {Key? key}) : super(key: key);
|
||||
|
||||
final BarcodeHandler handler;
|
||||
|
||||
@override
|
||||
State<StatefulWidget> createState() => InvenTreeBarcodeControllerState();
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Base state widget for the barcode controller.
|
||||
* This defines the basic interface for the barcode controller.
|
||||
*/
|
||||
class InvenTreeBarcodeControllerState extends State<InvenTreeBarcodeController> {
|
||||
|
||||
InvenTreeBarcodeControllerState() : super();
|
||||
|
||||
final GlobalKey barcodeControllerKey = GlobalKey(debugLabel: "barcodeController");
|
||||
|
||||
// Internal state flag to test if we are currently processing a barcode
|
||||
bool processingBarcode = false;
|
||||
|
||||
/*
|
||||
* Method to handle scanned data.
|
||||
* Any implementing class should call this method when a barcode is scanned.
|
||||
* Barcode data should be passed as a string
|
||||
*/
|
||||
Future<void> handleBarcodeData(String? data) async {
|
||||
|
||||
// Check that the data is valid, and this view is still mounted
|
||||
if (!mounted || data == null || data.isEmpty) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Currently processing a barcode - ignore this one
|
||||
if (processingBarcode) {
|
||||
return;
|
||||
}
|
||||
|
||||
setState(() {
|
||||
processingBarcode = true;
|
||||
});
|
||||
|
||||
BuildContext? context = OneContext().context;
|
||||
|
||||
showLoadingOverlay(context!);
|
||||
await pauseScan();
|
||||
|
||||
await widget.handler.processBarcode(data);
|
||||
|
||||
// processBarcode may have popped the context
|
||||
if (!mounted) {
|
||||
hideLoadingOverlay();
|
||||
return;
|
||||
}
|
||||
|
||||
int delay = await InvenTreeSettingsManager().getValue(INV_BARCODE_SCAN_DELAY, 500) as int;
|
||||
|
||||
Future.delayed(Duration(milliseconds: delay), () {
|
||||
hideLoadingOverlay();
|
||||
if (mounted) {
|
||||
resumeScan().then((_) {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
processingBarcode = false;
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Hook function to "pause" the barcode scanner
|
||||
Future<void> pauseScan() async {
|
||||
// Implement this function in subclass
|
||||
}
|
||||
|
||||
// Hook function to "resume" the barcode scanner
|
||||
Future<void> resumeScan() async {
|
||||
// Implement this function in subclass
|
||||
}
|
||||
|
||||
/*
|
||||
* Implementing classes are in control of building out the widget
|
||||
*/
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container();
|
||||
}
|
||||
|
||||
}
|
121
lib/barcode/handler.dart
Normal file
121
lib/barcode/handler.dart
Normal file
@@ -0,0 +1,121 @@
|
||||
|
||||
import "package:flutter/material.dart";
|
||||
|
||||
import "package:font_awesome_flutter/font_awesome_flutter.dart";
|
||||
|
||||
import "package:inventree/api.dart";
|
||||
import "package:inventree/helpers.dart";
|
||||
import "package:inventree/l10.dart";
|
||||
|
||||
import "package:inventree/barcode/tones.dart";
|
||||
|
||||
import "package:inventree/inventree/sentry.dart";
|
||||
|
||||
import "package:inventree/widget/dialogs.dart";
|
||||
import "package:inventree/widget/snacks.dart";
|
||||
|
||||
|
||||
/* Generic class which "handles" a barcode, by communicating with the InvenTree server,
|
||||
* and handling match / unknown / error cases.
|
||||
*
|
||||
* Override functionality of this class to perform custom actions,
|
||||
* based on the response returned from the InvenTree server
|
||||
*/
|
||||
class BarcodeHandler {
|
||||
|
||||
BarcodeHandler();
|
||||
|
||||
// Return the text to display on the barcode overlay
|
||||
// Note: Will be overridden by child classes
|
||||
String getOverlayText(BuildContext context) => "Barcode Overlay";
|
||||
|
||||
// Called when the server "matches" a barcode
|
||||
Future<void> onBarcodeMatched(Map<String, dynamic> data) async {
|
||||
// Override this function
|
||||
}
|
||||
|
||||
// Called when the server does not know about a barcode
|
||||
Future<void> onBarcodeUnknown(Map<String, dynamic> data) async {
|
||||
// Override this function
|
||||
|
||||
barcodeFailureTone();
|
||||
|
||||
showSnackIcon(
|
||||
L10().barcodeNoMatch,
|
||||
success: false,
|
||||
icon: Icons.qr_code,
|
||||
);
|
||||
}
|
||||
|
||||
// Called when the server returns an unhandled response
|
||||
Future<void> onBarcodeUnhandled(Map<String, dynamic> data) async {
|
||||
barcodeFailureTone();
|
||||
showServerError("barcode/", L10().responseUnknown, data.toString());
|
||||
}
|
||||
|
||||
/*
|
||||
* Base function to capture and process barcode data.
|
||||
*
|
||||
* Returns true only if the barcode scanner should remain open
|
||||
*/
|
||||
Future<void> processBarcode(String barcode, {String url = "barcode/"}) async {
|
||||
|
||||
debug("Scanned barcode data: '${barcode}'");
|
||||
|
||||
barcode = barcode.trim();
|
||||
|
||||
// Empty barcode is invalid
|
||||
if (barcode.isEmpty) {
|
||||
|
||||
barcodeFailureTone();
|
||||
|
||||
showSnackIcon(
|
||||
L10().barcodeError,
|
||||
icon: FontAwesomeIcons.circleExclamation,
|
||||
success: false
|
||||
);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
var response = await InvenTreeAPI().post(
|
||||
url,
|
||||
body: {
|
||||
"barcode": barcode,
|
||||
},
|
||||
expectedStatusCode: null, // Do not show an error on "unexpected code"
|
||||
);
|
||||
|
||||
debug("Barcode scan response" + response.data.toString());
|
||||
|
||||
Map<String, dynamic> data = response.asMap();
|
||||
|
||||
// Handle strange response from the server
|
||||
if (!response.isValid() || !response.isMap()) {
|
||||
onBarcodeUnknown({});
|
||||
|
||||
showSnackIcon(L10().serverError, success: false);
|
||||
|
||||
// We want to know about this one!
|
||||
await sentryReportMessage(
|
||||
"BarcodeHandler.processBarcode returned unexpected value",
|
||||
context: {
|
||||
"data": response.data?.toString() ?? "null",
|
||||
"barcode": barcode,
|
||||
"url": url,
|
||||
"statusCode": response.statusCode.toString(),
|
||||
"valid": response.isValid().toString(),
|
||||
"error": response.error,
|
||||
"errorDetail": response.errorDetail,
|
||||
"className": "${this}",
|
||||
}
|
||||
);
|
||||
} else if (data.containsKey("success")) {
|
||||
await onBarcodeMatched(data);
|
||||
} else if ((response.statusCode >= 400) || data.containsKey("error")) {
|
||||
await onBarcodeUnknown(data);
|
||||
} else {
|
||||
await onBarcodeUnhandled(data);
|
||||
}
|
||||
}
|
||||
}
|
23
lib/barcode/tones.dart
Normal file
23
lib/barcode/tones.dart
Normal file
@@ -0,0 +1,23 @@
|
||||
import "package:inventree/helpers.dart";
|
||||
import "package:inventree/preferences.dart";
|
||||
|
||||
/*
|
||||
* Play an audible 'success' alert to the user.
|
||||
*/
|
||||
Future<void> barcodeSuccessTone() async {
|
||||
|
||||
final bool en = await InvenTreeSettingsManager().getValue(INV_SOUNDS_BARCODE, true) as bool;
|
||||
|
||||
if (en) {
|
||||
playAudioFile("sounds/barcode_scan.mp3");
|
||||
}
|
||||
}
|
||||
|
||||
Future <void> barcodeFailureTone() async {
|
||||
|
||||
final bool en = await InvenTreeSettingsManager().getValue(INV_SOUNDS_BARCODE, true) as bool;
|
||||
|
||||
if (en) {
|
||||
playAudioFile("sounds/barcode_error.mp3");
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user