Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Oliver Walters 2020-08-18 10:39:24 +10:00
commit badc306f33
36 changed files with 1925 additions and 1091 deletions

View File

@ -242,7 +242,7 @@ def WrapWithQuotes(text, quote='"'):
return text
def MakeBarcode(object_name, object_data):
def MakeBarcode(object_name, object_pk, object_data, **kwargs):
""" Generate a string for a barcode. Adds some global InvenTree parameters.
Args:
@ -255,12 +255,20 @@ def MakeBarcode(object_name, object_data):
json string of the supplied data plus some other data
"""
data = {
'tool': 'InvenTree',
'version': inventreeVersion(),
'instance': inventreeInstanceName(),
object_name: object_data
}
brief = kwargs.get('brief', False)
data = {}
if brief:
data[object_name] = object_pk
else:
data['tool'] = 'InvenTree'
data['version'] = inventreeVersion()
data['instance'] = inventreeInstanceName()
# Ensure PK is included
object_data['id'] = object_pk
data[object_name] = object_data
return json.dumps(data, sort_keys=True)
@ -383,3 +391,56 @@ def ExtractSerialNumbers(serials, expected_quantity):
raise ValidationError([_("Number of unique serial number ({s}) must match quantity ({q})".format(s=len(numbers), q=expected_quantity))])
return numbers
def validateFilterString(value):
"""
Validate that a provided filter string looks like a list of comma-separated key=value pairs
These should nominally match to a valid database filter based on the model being filtered.
e.g. "category=6, IPN=12"
e.g. "part__name=widget"
The ReportTemplate class uses the filter string to work out which items a given report applies to.
For example, an acceptance test report template might only apply to stock items with a given IPN,
so the string could be set to:
filters = "IPN = ACME0001"
Returns a map of key:value pairs
"""
# Empty results map
results = {}
value = str(value).strip()
if not value or len(value) == 0:
return results
groups = value.split(',')
for group in groups:
group = group.strip()
pair = group.split('=')
if not len(pair) == 2:
raise ValidationError(
"Invalid group: {g}".format(g=group)
)
k, v = pair
k = k.strip()
v = v.strip()
if not k or not v:
raise ValidationError(
"Invalid group: {g}".format(g=group)
)
results[k] = v
return results

View File

@ -91,6 +91,8 @@ class QueryCountMiddleware(object):
To enable this middleware, set 'log_queries: True' in the local InvenTree config file.
Reference: https://www.dabapps.com/blog/logging-sql-queries-django-13/
Note: 2020-08-15 - This is no longer used, instead we now rely on the django-debug-toolbar addon
"""
def __init__(self, get_response):

View File

@ -130,6 +130,7 @@ INSTALLED_APPS = [
'build.apps.BuildConfig',
'common.apps.CommonConfig',
'company.apps.CompanyConfig',
'label.apps.LabelConfig',
'order.apps.OrderConfig',
'part.apps.PartConfig',
'report.apps.ReportConfig',
@ -172,11 +173,15 @@ MIDDLEWARE = [
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'InvenTree.middleware.AuthRequiredMiddleware',
'InvenTree.middleware.AuthRequiredMiddleware'
]
if CONFIG.get('log_queries', False):
MIDDLEWARE.append('InvenTree.middleware.QueryCountMiddleware')
# If the debug toolbar is enabled, add the modules
if DEBUG and CONFIG.get('debug_toolbar', False):
print("Running with DEBUG_TOOLBAR enabled")
INSTALLED_APPS.append('debug_toolbar')
MIDDLEWARE.append('debug_toolbar.middleware.DebugToolbarMiddleware')
ROOT_URLCONF = 'InvenTree.urls'
@ -377,3 +382,8 @@ DBBACKUP_STORAGE = 'django.core.files.storage.FileSystemStorage'
DBBACKUP_STORAGE_OPTIONS = {
'location': CONFIG.get('backup_dir', tempfile.gettempdir()),
}
# Internal IP addresses allowed to see the debug toolbar
INTERNAL_IPS = [
'127.0.0.1',
]

View File

@ -138,6 +138,7 @@ class TestMakeBarcode(TestCase):
bc = helpers.MakeBarcode(
"part",
3,
{
"id": 3,
"url": "www.google.com",

View File

@ -6,6 +6,7 @@ Passes URL lookup downstream to each app as required.
from django.conf.urls import url, include
from django.urls import path
from django.contrib import admin
from django.contrib.auth import views as auth_views
from qr_code import urls as qr_code_urls
@ -135,5 +136,12 @@ urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
# Media file access
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# Debug toolbar access (if in DEBUG mode)
if settings.DEBUG and 'debug_toolbar' in settings.INSTALLED_APPS:
import debug_toolbar
urlpatterns = [
path('__debug/', include(debug_toolbar.urls)),
] + urlpatterns
# Send any unknown URLs to the parts page
urlpatterns += [url(r'^.*$', RedirectView.as_view(url='/index/', permanent=False), name='index')]

View File

@ -6,7 +6,7 @@ import subprocess
from common.models import InvenTreeSetting
import django
INVENTREE_SW_VERSION = "0.1.1 pre"
INVENTREE_SW_VERSION = "0.1.3 pre"
def inventreeInstanceName():

View File

@ -47,12 +47,12 @@ class InvenTreeBarcodePlugin(BarcodePlugin):
else:
return False
for key in ['tool', 'version']:
if key not in self.data.keys():
return False
# If any of the following keys are in the JSON data,
# let's go ahead and assume that the code is a valid InvenTree one...
if not self.data['tool'] == 'InvenTree':
return False
for key in ['tool', 'version', 'InvenTree', 'stockitem', 'location', 'part']:
if key in self.data.keys():
return True
return True
@ -60,6 +60,18 @@ class InvenTreeBarcodePlugin(BarcodePlugin):
for k in self.data.keys():
if k.lower() == 'stockitem':
data = self.data[k]
pk = None
# Initially try casting to an integer
try:
pk = int(data)
except (TypeError, ValueError):
pk = None
if pk is None:
try:
pk = self.data[k]['id']
except (AttributeError, KeyError):
@ -77,6 +89,17 @@ class InvenTreeBarcodePlugin(BarcodePlugin):
for k in self.data.keys():
if k.lower() == 'stocklocation':
pk = None
# First try simple integer lookup
try:
pk = int(self.data[k])
except (TypeError, ValueError):
pk = None
if pk is None:
# Lookup by 'id' field
try:
pk = self.data[k]['id']
except (AttributeError, KeyError):
@ -94,6 +117,16 @@ class InvenTreeBarcodePlugin(BarcodePlugin):
for k in self.data.keys():
if k.lower() == 'part':
pk = None
# Try integer lookup first
try:
pk = int(self.data[k])
except (TypeError, ValueError):
pk = None
if pk is None:
try:
pk = self.data[k]['id']
except (AttributeError, KeyError):

View File

@ -99,6 +99,10 @@ class SupplierPartSerializer(InvenTreeModelSerializer):
if manufacturer_detail is not True:
self.fields.pop('manufacturer_detail')
supplier = serializers.PrimaryKeyRelatedField(queryset=Company.objects.filter(is_supplier=True))
manufacturer = serializers.PrimaryKeyRelatedField(queryset=Company.objects.filter(is_manufacturer=True))
class Meta:
model = SupplierPart
fields = [

View File

@ -58,9 +58,10 @@ static_root: '../inventree_static'
# - git
# - ssh
# Logging options
# If debug mode is enabled, set log_queries to True to show aggregate database queries in the debug console
log_queries: False
# Set debug_toolbar to True to enable a debugging toolbar for InvenTree
# Note: This will only be displayed if DEBUG mode is enabled,
# and only if InvenTree is accessed from a local IP (127.0.0.1)
debug_toolbar: False
# Backup options
# Set the backup_dir parameter to store backup files in a specific location

View File

14
InvenTree/label/admin.py Normal file
View File

@ -0,0 +1,14 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from .models import StockItemLabel
class StockItemLabelAdmin(admin.ModelAdmin):
list_display = ('name', 'description', 'label')
admin.site.register(StockItemLabel, StockItemLabelAdmin)

5
InvenTree/label/apps.py Normal file
View File

@ -0,0 +1,5 @@
from django.apps import AppConfig
class LabelConfig(AppConfig):
name = 'label'

View File

@ -0,0 +1,30 @@
# Generated by Django 3.0.7 on 2020-08-15 23:27
import InvenTree.helpers
import django.core.validators
from django.db import migrations, models
import label.models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='StockItemLabel',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(help_text='Label name', max_length=100, unique=True)),
('description', models.CharField(blank=True, help_text='Label description', max_length=250, null=True)),
('label', models.FileField(help_text='Label template file', upload_to=label.models.rename_label, validators=[django.core.validators.FileExtensionValidator(allowed_extensions=['html'])])),
('filters', models.CharField(blank=True, help_text='Query filters (comma-separated list of key=value pairs', max_length=250, validators=[InvenTree.helpers.validateFilterString])),
],
options={
'abstract': False,
},
),
]

View File

149
InvenTree/label/models.py Normal file
View File

@ -0,0 +1,149 @@
"""
Label printing models
"""
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
import io
from blabel import LabelWriter
from django.db import models
from django.core.validators import FileExtensionValidator
from django.utils.translation import gettext_lazy as _
from InvenTree.helpers import validateFilterString, normalize
from stock.models import StockItem
def rename_label(instance, filename):
""" Place the label file into the correct subdirectory """
filename = os.path.basename(filename)
return os.path.join('label', 'template', instance.SUBDIR, filename)
class LabelTemplate(models.Model):
"""
Base class for generic, filterable labels.
"""
class Meta:
abstract = True
# Each class of label files will be stored in a separate subdirectory
SUBDIR = "label"
@property
def template(self):
return self.label.path
def __str__(self):
return "{n} - {d}".format(
n=self.name,
d=self.description
)
name = models.CharField(
unique=True,
blank=False, max_length=100,
help_text=_('Label name'),
)
description = models.CharField(max_length=250, help_text=_('Label description'), blank=True, null=True)
label = models.FileField(
upload_to=rename_label,
blank=False, null=False,
help_text=_('Label template file'),
validators=[FileExtensionValidator(allowed_extensions=['html'])],
)
filters = models.CharField(
blank=True, max_length=250,
help_text=_('Query filters (comma-separated list of key=value pairs'),
validators=[validateFilterString]
)
def get_record_data(self, items):
"""
Return a list of dict objects, one for each item.
"""
return []
def render_to_file(self, filename, items, **kwargs):
"""
Render labels to a PDF file
"""
records = self.get_record_data(items)
writer = LabelWriter(self.template)
writer.write_labels(records, filename)
def render(self, items, **kwargs):
"""
Render labels to an in-memory PDF object, and return it
"""
records = self.get_record_data(items)
writer = LabelWriter(self.template)
buffer = io.BytesIO()
writer.write_labels(records, buffer)
return buffer
class StockItemLabel(LabelTemplate):
"""
Template for printing StockItem labels
"""
SUBDIR = "stockitem"
def matches_stock_item(self, item):
"""
Test if this label template matches a given StockItem object
"""
filters = validateFilterString(self.filters)
items = StockItem.objects.filter(**filters)
items = items.filter(pk=item.pk)
return items.exists()
def get_record_data(self, items):
"""
Generate context data for each provided StockItem
"""
records = []
for item in items:
# Add some basic information
records.append({
'item': item,
'part': item.part,
'name': item.part.name,
'ipn': item.part.IPN,
'quantity': normalize(item.quantity),
'serial': item.serial,
'uid': item.uid,
'pk': item.pk,
'qr_data': item.format_barcode(brief=True),
'tests': item.testResultMap()
})
return records

1
InvenTree/label/tests.py Normal file
View File

@ -0,0 +1 @@
# Create your tests here.

1
InvenTree/label/views.py Normal file
View File

@ -0,0 +1 @@
# Create your views here.

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -604,6 +604,19 @@ class BomList(generics.ListCreateAPIView):
serializer_class = part_serializers.BomItemSerializer
def list(self, request, *args, **kwargs):
queryset = self.filter_queryset(self.get_queryset())
serializer = self.get_serializer(queryset, many=True)
data = serializer.data
if request.is_ajax():
return JsonResponse(data, safe=False)
else:
return Response(data)
def get_serializer(self, *args, **kwargs):
# Do we wish to include extra detail?
@ -622,8 +635,10 @@ class BomList(generics.ListCreateAPIView):
return self.serializer_class(*args, **kwargs)
def get_queryset(self):
def get_queryset(self, *args, **kwargs):
queryset = BomItem.objects.all()
queryset = self.get_serializer_class().setup_eager_loading(queryset)
return queryset

View File

@ -40,7 +40,7 @@ def MakeBomTemplate(fmt):
return DownloadFile(data, filename)
def ExportBom(part, fmt='csv', cascade=False):
def ExportBom(part, fmt='csv', cascade=False, max_levels=None):
""" Export a BOM (Bill of Materials) for a given part.
Args:
@ -59,7 +59,7 @@ def ExportBom(part, fmt='csv', cascade=False):
# Add items at a given layer
for item in items:
item.level = '-' * level
item.level = str(int(level))
# Avoid circular BOM references
if item.pk in uids:
@ -68,6 +68,7 @@ def ExportBom(part, fmt='csv', cascade=False):
bom_items.append(item)
if item.sub_part.assembly:
if max_levels is None or level < max_levels:
add_items(item.sub_part.bom_items.all().order_by('id'), level + 1)
if cascade:

View File

@ -56,6 +56,8 @@ class BomExportForm(forms.Form):
cascading = forms.BooleanField(label=_("Cascading"), required=False, initial=False, help_text=_("Download cascading / multi-level BOM"))
levels = forms.IntegerField(label=_("Levels"), required=True, initial=0, help_text=_("Select maximum number of BOM levels to export (0 = all levels)"))
def get_choices(self):
""" BOM export format choices """

View File

@ -560,16 +560,17 @@ class Part(MPTTModel):
responsible = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True, related_name='parts_responible')
def format_barcode(self):
def format_barcode(self, **kwargs):
""" Return a JSON string for formatting a barcode for this Part object """
return helpers.MakeBarcode(
"part",
self.id,
{
"id": self.id,
"name": self.full_name,
"url": reverse('api-part-detail', kwargs={'pk': self.id}),
}
},
**kwargs
)
@property

View File

@ -236,6 +236,9 @@ class PartSerializer(InvenTreeModelSerializer):
thumbnail = serializers.CharField(source='get_thumbnail_url', read_only=True)
starred = serializers.SerializerMethodField()
# PrimaryKeyRelated fields (Note: enforcing field type here results in much faster queries, somehow...)
category = serializers.PrimaryKeyRelatedField(queryset=PartCategory.objects.all())
# TODO - Include annotation for the following fields:
# allocated_stock = serializers.FloatField(source='allocation_count', read_only=True)
# bom_items = serializers.IntegerField(source='bom_count', read_only=True)
@ -303,7 +306,12 @@ class BomItemSerializer(InvenTreeModelSerializer):
quantity = serializers.FloatField()
part = serializers.PrimaryKeyRelatedField(queryset=Part.objects.filter(assembly=True))
part_detail = PartBriefSerializer(source='part', many=False, read_only=True)
sub_part = serializers.PrimaryKeyRelatedField(queryset=Part.objects.filter(component=True))
sub_part_detail = PartBriefSerializer(source='sub_part', many=False, read_only=True)
validated = serializers.BooleanField(read_only=True, source='is_line_valid')
@ -328,6 +336,7 @@ class BomItemSerializer(InvenTreeModelSerializer):
queryset = queryset.prefetch_related('part')
queryset = queryset.prefetch_related('part__category')
queryset = queryset.prefetch_related('part__stock_items')
queryset = queryset.prefetch_related('sub_part')
queryset = queryset.prefetch_related('sub_part__category')
queryset = queryset.prefetch_related('sub_part__stock_items')

View File

@ -1392,10 +1392,22 @@ class BomDownload(AjaxView):
cascade = str2bool(request.GET.get('cascade', False))
levels = request.GET.get('levels', None)
if levels is not None:
try:
levels = int(levels)
if levels <= 0:
levels = None
except ValueError:
levels = None
if not IsValidBOMFormat(export_format):
export_format = 'csv'
return ExportBom(part, fmt=export_format, cascade=cascade)
return ExportBom(part, fmt=export_format, cascade=cascade, max_levels=levels)
def get_data(self):
return {
@ -1419,6 +1431,7 @@ class BomExport(AjaxView):
# Extract POSTed form data
fmt = request.POST.get('file_format', 'csv').lower()
cascade = str2bool(request.POST.get('cascading', False))
levels = request.POST.get('levels', None)
try:
part = Part.objects.get(pk=self.kwargs['pk'])
@ -1434,6 +1447,9 @@ class BomExport(AjaxView):
url += '?file_format=' + fmt
url += '&cascade=' + str(cascade)
if levels:
url += '&levels=' + str(levels)
data = {
'form_valid': part is not None,
'url': url,

View File

@ -338,11 +338,6 @@ class StockList(generics.ListCreateAPIView):
queryset = self.filter_queryset(self.get_queryset())
page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(queryset, many=True)
data = serializer.data
@ -363,6 +358,7 @@ class StockList(generics.ListCreateAPIView):
part_ids.add(part)
sp = item['supplier_part']
if sp:
supplier_part_ids.add(sp)
@ -434,6 +430,7 @@ class StockList(generics.ListCreateAPIView):
def get_queryset(self, *args, **kwargs):
queryset = super().get_queryset(*args, **kwargs)
queryset = StockItemSerializer.prefetch_queryset(queryset)
queryset = StockItemSerializer.annotate_queryset(queryset)

View File

@ -178,6 +178,37 @@ class SerializeStockForm(HelperForm):
]
class StockItemLabelSelectForm(HelperForm):
""" Form for selecting a label template for a StockItem """
label = forms.ChoiceField(
label=_('Label'),
help_text=_('Select test report template')
)
class Meta:
model = StockItem
fields = [
'label',
]
def get_label_choices(self, labels):
choices = []
if len(labels) > 0:
for label in labels:
choices.append((label.pk, label))
return choices
def __init__(self, labels, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['label'].choices = self.get_label_choices(labels)
class TestReportFormatForm(HelperForm):
""" Form for selection a test report template """

View File

@ -45,16 +45,17 @@ class StockLocation(InvenTreeTree):
def get_absolute_url(self):
return reverse('stock-location-detail', kwargs={'pk': self.id})
def format_barcode(self):
def format_barcode(self, **kwargs):
""" Return a JSON string for formatting a barcode for this StockLocation object """
return helpers.MakeBarcode(
'stocklocation',
self.pk,
{
"id": self.id,
"name": self.name,
"url": reverse('api-location-detail', kwargs={'pk': self.id}),
}
},
**kwargs
)
def get_stock_items(self, cascade=True):
@ -283,7 +284,7 @@ class StockItem(MPTTModel):
def get_part_name(self):
return self.part.full_name
def format_barcode(self):
def format_barcode(self, **kwargs):
""" Return a JSON string for formatting a barcode for this StockItem.
Can be used to perform lookup of a stockitem using barcode
@ -296,10 +297,11 @@ class StockItem(MPTTModel):
return helpers.MakeBarcode(
"stockitem",
self.id,
{
"id": self.id,
"url": reverse('api-stock-detail', kwargs={'pk': self.id}),
}
},
**kwargs
)
uid = models.CharField(blank=True, max_length=128, help_text=("Unique identifier field"))

View File

@ -99,15 +99,34 @@ class StockItemSerializer(InvenTreeModelSerializer):
return queryset
belongs_to = serializers.PrimaryKeyRelatedField(read_only=True)
build_order = serializers.PrimaryKeyRelatedField(read_only=True)
customer = serializers.PrimaryKeyRelatedField(read_only=True)
location = serializers.PrimaryKeyRelatedField(read_only=True)
in_stock = serializers.BooleanField(read_only=True)
sales_order = serializers.PrimaryKeyRelatedField(read_only=True)
status_text = serializers.CharField(source='get_status_display', read_only=True)
part_detail = PartBriefSerializer(source='part', many=False, read_only=True)
location_detail = LocationBriefSerializer(source='location', many=False, read_only=True)
supplier_part = serializers.PrimaryKeyRelatedField(read_only=True)
supplier_part_detail = SupplierPartSerializer(source='supplier_part', many=False, read_only=True)
part = serializers.PrimaryKeyRelatedField(read_only=True)
part_detail = PartBriefSerializer(source='part', many=False, read_only=True)
location_detail = LocationBriefSerializer(source='location', many=False, read_only=True)
tracking_items = serializers.IntegerField(source='tracking_info_count', read_only=True, required=False)
quantity = serializers.FloatField()
allocated = serializers.FloatField(source='allocation_count', required=False)
serial = serializers.IntegerField(required=False)
@ -140,9 +159,9 @@ class StockItemSerializer(InvenTreeModelSerializer):
fields = [
'allocated',
'batch',
'build_order',
'belongs_to',
'customer',
'build_order',
'in_stock',
'link',
'location',
@ -155,10 +174,10 @@ class StockItemSerializer(InvenTreeModelSerializer):
'required_tests',
'sales_order',
'serial',
'supplier_part',
'supplier_part_detail',
'status',
'status_text',
'supplier_part',
'supplier_part_detail',
'tracking_items',
'uid',
]

View File

@ -78,7 +78,7 @@ InvenTree | {% trans "Stock Item" %} - {{ item }}
<button id='barcode-options' title='{% trans "Barcode actions" %}' class='btn btn-default dropdown-toggle' type='button' data-toggle='dropdown'><span class='fas fa-qrcode'></span> <span class='caret'></span></button>
<ul class='dropdown-menu' role='menu'>
<li><a href='#' id='show-qr-code'><span class='fas fa-qrcode'></span> {% trans "Show QR Code" %}</a></li>
<li class='disabled'><a href='#' id='print-label'><span class='fas fa-tag'></span> {% trans "Print Label" %}</a></li>
<li><a href='#' id='print-label'><span class='fas fa-tag'></span> {% trans "Print Label" %}</a></li>
{% if item.uid %}
<li><a href='#' id='unlink-barcode'><span class='fas fa-unlink'></span> {% trans "Unlink Barcode" %}</a></li>
{% else %}
@ -126,7 +126,7 @@ InvenTree | {% trans "Stock Item" %} - {{ item }}
</div>
{% if item.part.has_test_report_templates %}
<button type='button' class='btn btn-default' id='stock-test-report' title='{% trans "Generate test report" %}'>
<span class='fas fa-tasks'/>
<span class='fas fa-file-invoice'/>
</button>
{% endif %}
</div>
@ -314,6 +314,15 @@ $("#stock-test-report").click(function() {
});
{% endif %}
$("#print-label").click(function() {
launchModalForm(
"{% url 'stock-item-label-select' item.id %}",
{
follow: true,
}
)
});
$("#stock-duplicate").click(function() {
launchModalForm(
"{% url 'stock-item-create' %}",

View File

@ -29,6 +29,7 @@ stock_item_detail_urls = [
url(r'^add_tracking/', views.StockItemTrackingCreate.as_view(), name='stock-tracking-create'),
url(r'^test-report-select/', views.StockItemTestReportSelect.as_view(), name='stock-item-test-report-select'),
url(r'^label-select/', views.StockItemSelectLabels.as_view(), name='stock-item-label-select'),
url(r'^test/', views.StockItemDetail.as_view(template_name='stock/item_tests.html'), name='stock-item-test-results'),
url(r'^children/', views.StockItemDetail.as_view(template_name='stock/item_childs.html'), name='stock-item-children'),
@ -59,6 +60,7 @@ stock_urls = [
url(r'^item/new/?', views.StockItemCreate.as_view(), name='stock-item-create'),
url(r'^item/test-report-download/', views.StockItemTestReportDownload.as_view(), name='stock-item-test-report-download'),
url(r'^item/print-stock-labels/', views.StockItemPrintLabels.as_view(), name='stock-item-print-labels'),
# URLs for StockItem attachments
url(r'^item/attachment/', include([

View File

@ -28,6 +28,7 @@ from datetime import datetime
from company.models import Company, SupplierPart
from part.models import Part
from report.models import TestReport
from label.models import StockItemLabel
from .models import StockItem, StockLocation, StockItemTracking, StockItemAttachment, StockItemTestResult
from .admin import StockItemResource
@ -295,6 +296,88 @@ class StockItemReturnToStock(AjaxUpdateView):
return self.renderJsonResponse(request, self.get_form(), data)
class StockItemSelectLabels(AjaxView):
"""
View for selecting a template for printing labels for one (or more) StockItem objects
"""
model = StockItem
ajax_form_title = _('Select Label Template')
def get_form(self):
item = StockItem.objects.get(pk=self.kwargs['pk'])
labels = []
for label in StockItemLabel.objects.all():
if label.matches_stock_item(item):
labels.append(label)
return StockForms.StockItemLabelSelectForm(labels)
def post(self, request, *args, **kwargs):
label = request.POST.get('label', None)
try:
label = StockItemLabel.objects.get(pk=label)
except (ValueError, StockItemLabel.DoesNotExist):
raise ValidationError({'label': _("Select valid label")})
stock_item = StockItem.objects.get(pk=self.kwargs['pk'])
url = reverse('stock-item-print-labels')
url += '?label={pk}'.format(pk=label.pk)
url += '&items[]={pk}'.format(pk=stock_item.pk)
data = {
'form_valid': True,
'url': url,
}
return self.renderJsonResponse(request, self.get_form(), data=data)
class StockItemPrintLabels(AjaxView):
"""
View for printing labels and returning a PDF
Requires the following arguments to be passed as URL params:
items: List of valid StockItem pk values
label: Valid pk of a StockItemLabel template
"""
def get(self, request, *args, **kwargs):
label = request.GET.get('label', None)
try:
label = StockItemLabel.objects.get(pk=label)
except (ValueError, StockItemLabel.DoesNotExist):
raise ValidationError({'label': 'Invalid label ID'})
item_pks = request.GET.getlist('items[]')
items = []
for pk in item_pks:
try:
item = StockItem.objects.get(pk=pk)
items.append(item)
except (ValueError, StockItem.DoesNotExist):
pass
if len(items) == 0:
raise ValidationError({'items': 'Must provide valid stockitems'})
pdf = label.render(items).getbuffer()
return DownloadFile(pdf, 'stock_labels.pdf', content_type='application/pdf')
class StockItemDeleteTestData(AjaxUpdateView):
"""
View for deleting all test data

View File

@ -51,12 +51,12 @@ style:
# Run unit tests
test:
cd InvenTree && python3 manage.py check
cd InvenTree && python3 manage.py test barcode build common company order part report stock InvenTree
cd InvenTree && python3 manage.py test barcode build common company label order part report stock InvenTree
# Run code coverage
coverage:
cd InvenTree && python3 manage.py check
coverage run InvenTree/manage.py test barcode build common company order part report stock InvenTree
coverage run InvenTree/manage.py test barcode build common company label order part report stock InvenTree
coverage html
# Install packages required to generate code docs

View File

@ -1,6 +1,7 @@
wheel>=0.34.2 # Wheel
Django==3.0.7 # Django package
pillow==7.1.0 # Image manipulation
blabel==0.1.3 # Simple PDF label printing
djangorestframework==3.10.3 # DRF framework
django-dbbackup==3.3.0 # Database backup / restore functionality
django-cors-headers==3.2.0 # CORS headers extension for DRF
@ -22,3 +23,4 @@ rapidfuzz==0.7.6 # Fuzzy string matching
django-stdimage==5.1.1 # Advanced ImageField management
django-tex==1.1.7 # LaTeX PDF export
django-weasyprint==1.0.1 # HTML PDF export
django-debug-toolbar==2.2 # Debug / profiling toolbar