Simplify barcode plugin class

This commit is contained in:
Oliver Walters 2020-04-14 22:30:29 +10:00
parent 5de85defa7
commit 94e400d0e1
3 changed files with 28 additions and 16 deletions

View File

@ -68,12 +68,13 @@ class BarcodeScanView(APIView):
# Look for a barcode plugin that knows how to handle the data
for plugin_class in barcode_plugins:
plugin = plugin_class()
# Instantiate the plugin with the provided plugin data
plugin = plugin_class(barcode_data)
if plugin.validate_barcode(barcode_data):
if plugin.validate():
# Plugin should return a dict response
response = plugin.decode_barcode(barcode_data)
response = plugin.decode()
if type(response) is dict:
if 'success' not in response.keys() and 'error' not in response.keys():

View File

@ -8,16 +8,27 @@ class BarcodePlugin(plugin.InvenTreePlugin):
The BarcodePlugin class is the base class for any barcode plugin.
"""
def __init__(self):
def __init__(self, barcode_data):
plugin.InvenTreePlugin.__init__(self)
def validate_barcode(self, barcode_data):
self.data = barcode_data
def hash(self):
"""
Calculate a hash for the barcode data.
This is supposed to uniquely identify the barcode contents,
at least within the bardcode sub-type.
"""
return ""
def validate(self):
"""
Default implementation returns False
"""
return False
def decode_barcode(self, barcode_data):
def decode(self):
"""
Decode the barcode, and craft a response
"""

View File

@ -12,7 +12,7 @@ class InvenTreeBarcodePlugin(barcode.BarcodePlugin):
PLUGIN_NAME = "InvenTreeBarcodePlugin"
def validate_barcode(self, barcode_data):
def validate(self):
"""
An "InvenTree" barcode must include the following tags:
@ -24,20 +24,20 @@ class InvenTreeBarcodePlugin(barcode.BarcodePlugin):
"""
for key in ['tool', 'version']:
if key not in barcode_data.keys():
if key not in self.data.keys():
return False
if not barcode_data['tool'] == 'InvenTree':
if not self.data['tool'] == 'InvenTree':
return False
return True
def decode_barcode(self, barcode_data):
def decode(self):
response = {}
if 'part' in barcode_data.keys():
id = barcode_data['part'].get('id', None)
if 'part' in self.data.keys():
id = self.data['part'].get('id', None)
try:
part = Part.objects.get(id=id)
@ -45,8 +45,8 @@ class InvenTreeBarcodePlugin(barcode.BarcodePlugin):
except (ValueError, Part.DoesNotExist):
response['error'] = _('Part does not exist')
elif 'stocklocation' in barcode_data.keys():
id = barcode_data['stocklocation'].get('id', None)
elif 'stocklocation' in self.data.keys():
id = self.data['stocklocation'].get('id', None)
try:
loc = StockLocation.objects.get(id=id)
@ -54,9 +54,9 @@ class InvenTreeBarcodePlugin(barcode.BarcodePlugin):
except (ValueError, StockLocation.DoesNotExist):
response['error'] = _('StockLocation does not exist')
elif 'stockitem' in barcode_data.keys():
elif 'stockitem' in self.data.keys():
id = barcode_data['stockitem'].get('id', None)
id = self.data['stockitem'].get('id', None)
try:
item = StockItem.objects.get(id=id)