2
0
mirror of https://github.com/inventree/InvenTree.git synced 2025-07-01 03:00:54 +00:00

Merge remote-tracking branch 'inventree/master'

This commit is contained in:
Oliver Walters
2020-05-17 00:42:03 +10:00
57 changed files with 1916 additions and 203 deletions

View File

@ -10,6 +10,7 @@ import import_export.widgets as widgets
from .models import StockLocation, StockItem, StockItemAttachment
from .models import StockItemTracking
from .models import StockItemTestResult
from build.models import Build
from company.models import SupplierPart
@ -117,7 +118,13 @@ class StockTrackingAdmin(ImportExportModelAdmin):
list_display = ('item', 'date', 'title')
class StockItemTestResultAdmin(admin.ModelAdmin):
list_display = ('stock_item', 'test', 'result', 'value')
admin.site.register(StockLocation, LocationAdmin)
admin.site.register(StockItem, StockItemAdmin)
admin.site.register(StockItemTracking, StockTrackingAdmin)
admin.site.register(StockItemAttachment, StockAttachmentAdmin)
admin.site.register(StockItemTestResult, StockItemTestResultAdmin)

View File

@ -15,6 +15,7 @@ from django.db.models import Q
from .models import StockLocation, StockItem
from .models import StockItemTracking
from .models import StockItemAttachment
from .models import StockItemTestResult
from part.models import Part, PartCategory
from part.serializers import PartBriefSerializer
@ -26,6 +27,7 @@ from .serializers import StockItemSerializer
from .serializers import LocationSerializer, LocationBriefSerializer
from .serializers import StockTrackingSerializer
from .serializers import StockItemAttachmentSerializer
from .serializers import StockItemTestResultSerializer
from InvenTree.views import TreeSerializer
from InvenTree.helpers import str2bool, isNull
@ -536,11 +538,10 @@ class StockList(generics.ListCreateAPIView):
try:
part = Part.objects.get(pk=part_id)
# If the part is a Template part, select stock items for any "variant" parts under that template
if part.is_template:
queryset = queryset.filter(part__in=[part.id for part in Part.objects.filter(variant_of=part_id)])
else:
queryset = queryset.filter(part=part_id)
# Filter by any parts "under" the given part
parts = part.get_descendants(include_self=True)
queryset = queryset.filter(part__in=parts)
except (ValueError, Part.DoesNotExist):
raise ValidationError({"part": "Invalid Part ID specified"})
@ -654,11 +655,89 @@ class StockAttachmentList(generics.ListCreateAPIView, AttachmentMixin):
queryset = StockItemAttachment.objects.all()
serializer_class = StockItemAttachmentSerializer
filter_backends = [
DjangoFilterBackend,
filters.OrderingFilter,
filters.SearchFilter,
]
filter_fields = [
'stock_item',
]
class StockItemTestResultList(generics.ListCreateAPIView):
"""
API endpoint for listing (and creating) a StockItemTestResult object.
"""
queryset = StockItemTestResult.objects.all()
serializer_class = StockItemTestResultSerializer
permission_classes = [
permissions.IsAuthenticated,
]
filter_backends = [
DjangoFilterBackend,
filters.SearchFilter,
filters.OrderingFilter,
]
filter_fields = [
'stock_item',
'test',
'user',
'result',
'value',
]
def get_serializer(self, *args, **kwargs):
try:
kwargs['user_detail'] = str2bool(self.request.query_params.get('user_detail', False))
except:
pass
try:
kwargs['attachment_detail'] = str2bool(self.request.query_params.get('attachment_detail', False))
except:
pass
kwargs['context'] = self.get_serializer_context()
return self.serializer_class(*args, **kwargs)
def perform_create(self, serializer):
"""
Create a new test result object.
Also, check if an attachment was uploaded alongside the test result,
and save it to the database if it were.
"""
# Capture the user information
test_result = serializer.save()
test_result.user = self.request.user
# Check if a file has been attached to the request
attachment_file = self.request.FILES.get('attachment', None)
if attachment_file:
# Create a new attachment associated with the stock item
attachment = StockItemAttachment(
attachment=attachment_file,
stock_item=test_result.stock_item,
user=test_result.user
)
attachment.save()
# Link the attachment back to the test result
test_result.attachment = attachment
test_result.save()
class StockTrackingList(generics.ListCreateAPIView):
""" API endpoint for list view of StockItemTracking objects.
@ -769,6 +848,11 @@ stock_api_urls = [
url(r'^$', StockAttachmentList.as_view(), name='api-stock-attachment-list'),
])),
# Base URL for StockItemTestResult API endpoints
url(r'^test/', include([
url(r'^$', StockItemTestResultList.as_view(), name='api-stock-test-result-list'),
])),
url(r'track/?', StockTrackingList.as_view(), name='api-stock-track'),
url(r'^tree/?', StockCategoryTree.as_view(), name='api-stock-tree'),

View File

@ -68,4 +68,172 @@
level: 0
tree_id: 0
lft: 0
rght: 0
- model: stock.stockitem
pk: 105
fields:
part: 25
location: 7
quantity: 1
serial: 1000
level: 0
tree_id: 0
lft: 0
rght: 0
# Stock items for template / variant parts
- model: stock.stockitem
pk: 500
fields:
part: 10001
location: 7
quantity: 5
level: 0
tree_id: 0
lft: 0
rght: 0
- model: stock.stockitem
pk: 501
fields:
part: 10001
location: 7
quantity: 1
serial: 1
level: 0
tree_id: 0
lft: 0
rght: 0
- model: stock.stockitem
pk: 501
fields:
part: 10001
location: 7
quantity: 1
serial: 1
level: 0
tree_id: 0
lft: 0
rght: 0
- model: stock.stockitem
pk: 502
fields:
part: 10001
location: 7
quantity: 1
serial: 2
level: 0
tree_id: 0
lft: 0
rght: 0
- model: stock.stockitem
pk: 503
fields:
part: 10001
location: 7
quantity: 1
serial: 3
level: 0
tree_id: 0
lft: 0
rght: 0
- model: stock.stockitem
pk: 504
fields:
part: 10001
location: 7
quantity: 1
serial: 4
level: 0
tree_id: 0
lft: 0
rght: 0
- model: stock.stockitem
pk: 505
fields:
part: 10001
location: 7
quantity: 1
serial: 5
level: 0
tree_id: 0
lft: 0
rght: 0
- model: stock.stockitem
pk: 510
fields:
part: 10002
location: 7
quantity: 1
serial: 10
level: 0
tree_id: 0
lft: 0
rght: 0
- model: stock.stockitem
pk: 511
fields:
part: 10002
location: 7
quantity: 1
serial: 11
level: 0
tree_id: 0
lft: 0
rght: 0
- model: stock.stockitem
pk: 512
fields:
part: 10002
location: 7
quantity: 1
serial: 12
level: 0
tree_id: 0
lft: 0
rght: 0
- model: stock.stockitem
pk: 520
fields:
part: 10004
location: 7
quantity: 1
serial: 20
level: 0
tree_id: 0
lft: 0
rght: 0
- model: stock.stockitem
pk: 521
fields:
part: 10004
location: 7
quantity: 1
serial: 21
level: 0
tree_id: 0
lft: 0
rght: 0
- model: stock.stockitem
pk: 522
fields:
part: 10004
location: 7
quantity: 1
serial: 22
level: 0
tree_id: 0
lft: 0
rght: 0

View File

@ -0,0 +1,31 @@
- model: stock.stockitemtestresult
fields:
stock_item: 105
test: "Firmware Version"
value: "0xA1B2C3D4"
result: True
date: 2020-02-02
- model: stock.stockitemtestresult
fields:
stock_item: 105
test: "Settings Checksum"
value: "0xAABBCCDD"
result: True
date: 2020-02-02
- model: stock.stockitemtestresult
fields:
stock_item: 105
test: "Temperature Test"
result: False
date: 2020-05-16
notes: 'Got too hot or something'
- model: stock.stockitemtestresult
fields:
stock_item: 105
test: "Temperature Test"
result: True
date: 2020-05-17
notes: 'Passed temperature test by making it cooler'

View File

@ -13,7 +13,11 @@ from mptt.fields import TreeNodeChoiceField
from InvenTree.helpers import GetExportFormats
from InvenTree.forms import HelperForm
from .models import StockLocation, StockItem, StockItemTracking, StockItemAttachment
from InvenTree.fields import RoundingDecimalFormField
from .models import StockLocation, StockItem, StockItemTracking
from .models import StockItemAttachment
from .models import StockItemTestResult
class EditStockItemAttachmentForm(HelperForm):
@ -30,6 +34,22 @@ class EditStockItemAttachmentForm(HelperForm):
]
class EditStockItemTestResultForm(HelperForm):
"""
Form for creating / editing a StockItemTestResult object.
"""
class Meta:
model = StockItemTestResult
fields = [
'stock_item',
'test',
'result',
'value',
'notes',
]
class EditStockLocationForm(HelperForm):
""" Form for editing a StockLocation """
@ -47,6 +67,15 @@ class CreateStockItemForm(HelperForm):
serial_numbers = forms.CharField(label='Serial numbers', required=False, help_text=_('Enter unique serial numbers (or leave blank)'))
def __init__(self, *args, **kwargs):
self.field_prefix = {
'serial_numbers': 'fa-hashtag',
'link': 'fa-link',
}
super().__init__(*args, **kwargs)
class Meta:
model = StockItem
fields = [
@ -69,6 +98,7 @@ class CreateStockItemForm(HelperForm):
return
self.cleaned_data = {}
# If the form is permitted to be empty, and none of the form data has
# changed from the initial data, short circuit any validation.
if self.empty_permitted and not self.has_changed():
@ -79,7 +109,7 @@ class CreateStockItemForm(HelperForm):
self._clean_form()
class SerializeStockForm(forms.ModelForm):
class SerializeStockForm(HelperForm):
""" Form for serializing a StockItem. """
destination = TreeNodeChoiceField(queryset=StockLocation.objects.all(), label='Destination', required=True, help_text='Destination for serialized stock (by default, will remain in current location)')
@ -88,6 +118,18 @@ class SerializeStockForm(forms.ModelForm):
note = forms.CharField(label='Notes', required=False, help_text='Add transaction note (optional)')
quantity = RoundingDecimalFormField(max_digits=10, decimal_places=5)
def __init__(self, *args, **kwargs):
# Extract the stock item
item = kwargs.pop('item', None)
if item:
self.field_placeholder['serial_numbers'] = item.part.getSerialNumberString(item.quantity)
super().__init__(*args, **kwargs)
class Meta:
model = StockItem

View File

@ -0,0 +1,18 @@
# Generated by Django 3.0.5 on 2020-05-13 00:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('stock', '0038_stockitemattachment_upload_date'),
]
operations = [
migrations.AlterField(
model_name='stockitemattachment',
name='comment',
field=models.CharField(blank=True, help_text='File comment', max_length=100),
),
]

View File

@ -0,0 +1,29 @@
# Generated by Django 3.0.5 on 2020-05-16 09:55
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('stock', '0039_auto_20200513_0016'),
]
operations = [
migrations.CreateModel(
name='StockItemTestResult',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('test', models.CharField(help_text='Test name', max_length=100, verbose_name='Test')),
('result', models.BooleanField(default=False, help_text='Test result', verbose_name='Result')),
('value', models.CharField(blank=True, help_text='Test output value', max_length=500, verbose_name='Value')),
('date', models.DateTimeField(auto_now_add=True)),
('attachment', models.ForeignKey(blank=True, help_text='Test result attachment', null=True, on_delete=django.db.models.deletion.SET_NULL, to='stock.StockItemAttachment', verbose_name='Attachment')),
('stock_item', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='test_results', to='stock.StockItem')),
('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL)),
],
),
]

View File

@ -0,0 +1,18 @@
# Generated by Django 3.0.5 on 2020-05-16 10:14
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('stock', '0040_stockitemtestresult'),
]
operations = [
migrations.AddField(
model_name='stockitemtestresult',
name='notes',
field=models.CharField(blank=True, help_text='Test notes', max_length=500, verbose_name='Notes'),
),
]

View File

@ -142,9 +142,21 @@ class StockItem(MPTTModel):
)
def save(self, *args, **kwargs):
"""
Save this StockItem to the database. Performs a number of checks:
- Unique serial number requirement
- Adds a transaction note when the item is first created.
"""
self.validate_unique()
self.clean()
if not self.pk:
# StockItem has not yet been saved
add_note = True
else:
# StockItem has already been saved
add_note = False
user = kwargs.pop('user', None)
@ -172,59 +184,26 @@ class StockItem(MPTTModel):
""" Return True if this StockItem is serialized """
return self.serial is not None and self.quantity == 1
@classmethod
def check_serial_number(cls, part, serial_number):
""" Check if a new stock item can be created with the provided part_id
Args:
part: The part to be checked
def validate_unique(self, exclude=None):
"""
Test that this StockItem is "unique".
If the StockItem is serialized, the same serial number.
cannot exist for the same part (or part tree).
"""
if not part.trackable:
return False
# Return False if an invalid serial number is supplied
try:
serial_number = int(serial_number)
except ValueError:
return False
items = StockItem.objects.filter(serial=serial_number)
# Is this part a variant? If so, check S/N across all sibling variants
if part.variant_of is not None:
items = items.filter(part__variant_of=part.variant_of)
else:
items = items.filter(part=part)
# An existing serial number exists
if items.exists():
return False
return True
def validate_unique(self, exclude=None):
super(StockItem, self).validate_unique(exclude)
# If the Part object is a variant (of a template part),
# ensure that the serial number is unique
# across all variants of the same template part
if self.serial is not None:
# Query to look for duplicate serial numbers
parts = PartModels.Part.objects.filter(tree_id=self.part.tree_id)
stock = StockItem.objects.filter(part__in=parts, serial=self.serial)
try:
if self.serial is not None:
# This is a variant part (check S/N across all sibling variants)
if self.part.variant_of is not None:
if StockItem.objects.filter(part__variant_of=self.part.variant_of, serial=self.serial).exclude(id=self.id).exists():
raise ValidationError({
'serial': _('A stock item with this serial number already exists for template part {part}'.format(part=self.part.variant_of))
})
else:
if StockItem.objects.filter(part=self.part, serial=self.serial).exclude(id=self.id).exists():
raise ValidationError({
'serial': _('A stock item with this serial number already exists')
})
except PartModels.Part.DoesNotExist:
pass
# Exclude myself from the search
if self.pk is not None:
stock = stock.exclude(pk=self.pk)
if stock.exists():
raise ValidationError({"serial": _("StockItem with this serial number already exists")})
def clean(self):
""" Validate the StockItem object (separate to field validation)
@ -236,6 +215,8 @@ class StockItem(MPTTModel):
- Quantity must be 1 if the StockItem has a serial number
"""
super().clean()
if self.status == StockStatus.SHIPPED and self.sales_order is None:
raise ValidationError({
'sales_order': "SalesOrder must be specified as status is marked as SHIPPED",
@ -248,6 +229,24 @@ class StockItem(MPTTModel):
'status': 'Status cannot be marked as ASSIGNED_TO_OTHER_ITEM if the belongs_to field is not set',
})
try:
if self.part.trackable:
# Trackable parts must have integer values for quantity field!
if not self.quantity == int(self.quantity):
raise ValidationError({
'quantity': _('Quantity must be integer value for trackable parts')
})
except PartModels.Part.DoesNotExist:
# For some reason the 'clean' process sometimes throws errors because self.part does not exist
# It *seems* that this only occurs in unit testing, though.
# Probably should investigate this at some point.
pass
if self.quantity < 0:
raise ValidationError({
'quantity': _('Quantity must be greater than zero')
})
# The 'supplier_part' field must point to the same part!
try:
if self.supplier_part is not None:
@ -599,6 +598,9 @@ class StockItem(MPTTModel):
if self.serialized:
return
if not self.part.trackable:
raise ValidationError({"part": _("Part is not set as trackable")})
# Quantity must be a valid integer value
try:
quantity = int(quantity)
@ -624,7 +626,7 @@ class StockItem(MPTTModel):
existing = []
for serial in serials:
if not StockItem.check_serial_number(self.part, serial):
if self.part.checkIfSerialNumberExists(serial):
existing.append(serial)
if len(existing) > 0:
@ -919,6 +921,51 @@ class StockItem(MPTTModel):
return s
def getTestResults(self, test=None, result=None, user=None):
"""
Return all test results associated with this StockItem.
Optionally can filter results by:
- Test name
- Test result
- User
"""
results = self.test_results
if test:
# Filter by test name
results = results.filter(test=test)
if result is not None:
# Filter by test status
results = results.filter(result=result)
if user:
# Filter by user
results = results.filter(user=user)
return results
def testResultMap(self, **kwargs):
"""
Return a map of test-results using the test name as the key.
Where multiple test results exist for a given name,
the *most recent* test is used.
This map is useful for rendering to a template (e.g. a test report),
as all named tests are accessible.
"""
results = self.getTestResults(**kwargs).order_by('-date')
result_map = {}
for result in results:
result_map[result.test] = result
return result_map
@receiver(pre_delete, sender=StockItem, dispatch_uid='stock_item_pre_delete_log')
def before_delete_stock_item(sender, instance, using, **kwargs):
@ -991,3 +1038,86 @@ class StockItemTracking(models.Model):
# TODO
# file = models.FileField()
class StockItemTestResult(models.Model):
"""
A StockItemTestResult records results of custom tests against individual StockItem objects.
This is useful for tracking unit acceptance tests, and particularly useful when integrated
with automated testing setups.
Multiple results can be recorded against any given test, allowing tests to be run many times.
Attributes:
stock_item: Link to StockItem
test: Test name (simple string matching)
result: Test result value (pass / fail / etc)
value: Recorded test output value (optional)
attachment: Link to StockItem attachment (optional)
notes: Extra user notes related to the test (optional)
user: User who uploaded the test result
date: Date the test result was recorded
"""
def clean(self):
super().clean()
# If an attachment is linked to this result, the attachment must also point to the item
try:
if self.attachment:
if not self.attachment.stock_item == self.stock_item:
raise ValidationError({
'attachment': _("Test result attachment must be linked to the same StockItem"),
})
except (StockItem.DoesNotExist, StockItemAttachment.DoesNotExist):
pass
stock_item = models.ForeignKey(
StockItem,
on_delete=models.CASCADE,
related_name='test_results'
)
test = models.CharField(
blank=False, max_length=100,
verbose_name=_('Test'),
help_text=_('Test name')
)
result = models.BooleanField(
default=False,
verbose_name=_('Result'),
help_text=_('Test result')
)
value = models.CharField(
blank=True, max_length=500,
verbose_name=_('Value'),
help_text=_('Test output value')
)
attachment = models.ForeignKey(
StockItemAttachment,
on_delete=models.SET_NULL,
blank=True, null=True,
verbose_name=_('Attachment'),
help_text=_('Test result attachment'),
)
notes = models.CharField(
blank=True, max_length=500,
verbose_name=_('Notes'),
help_text=_("Test notes"),
)
user = models.ForeignKey(
User,
on_delete=models.SET_NULL,
blank=True, null=True
)
date = models.DateTimeField(
auto_now_add=True,
editable=False
)

View File

@ -7,6 +7,7 @@ from rest_framework import serializers
from .models import StockItem, StockLocation
from .models import StockItemTracking
from .models import StockItemAttachment
from .models import StockItemTestResult
from django.db.models import Sum, Count
from django.db.models.functions import Coalesce
@ -193,7 +194,7 @@ class LocationSerializer(InvenTreeModelSerializer):
class StockItemAttachmentSerializer(InvenTreeModelSerializer):
""" Serializer for StockItemAttachment model """
def __init_(self, *args, **kwargs):
def __init__(self, *args, **kwargs):
user_detail = kwargs.pop('user_detail', False)
super().__init__(*args, **kwargs)
@ -211,11 +212,55 @@ class StockItemAttachmentSerializer(InvenTreeModelSerializer):
'stock_item',
'attachment',
'comment',
'upload_date',
'user',
'user_detail',
]
class StockItemTestResultSerializer(InvenTreeModelSerializer):
""" Serializer for the StockItemTestResult model """
user_detail = UserSerializerBrief(source='user', read_only=True)
attachment_detail = StockItemAttachmentSerializer(source='attachment', read_only=True)
def __init__(self, *args, **kwargs):
user_detail = kwargs.pop('user_detail', False)
attachment_detail = kwargs.pop('attachment_detail', False)
super().__init__(*args, **kwargs)
if user_detail is not True:
self.fields.pop('user_detail')
if attachment_detail is not True:
self.fields.pop('attachment_detail')
class Meta:
model = StockItemTestResult
fields = [
'pk',
'stock_item',
'test',
'result',
'value',
'attachment',
'attachment_detail',
'notes',
'user',
'user_detail',
'date'
]
read_only_fields = [
'pk',
'attachment',
'user',
'date',
]
class StockTrackingSerializer(InvenTreeModelSerializer):
""" Serializer for StockItemTracking model """

View File

@ -8,8 +8,9 @@
{% include "stock/tabs.html" with tab="tracking" %}
<hr>
<h4>{% trans "Stock Tracking Information" %}</h4>
<hr>
<div id='table-toolbar'>
<div class='btn-group'>
<button class='btn btn-success' type='button' title='New tracking entry' id='new-entry'>New Entry</button>

View File

@ -7,8 +7,8 @@
{% include "stock/tabs.html" with tab='attachments' %}
<hr>
<h4>{% trans "Stock Item Attachments" %}</h4>
<hr>
{% include "attachment_table.html" with attachments=item.attachments.all %}
@ -17,6 +17,20 @@
{% block js_ready %}
{{ block.super }}
enableDragAndDrop(
'#attachment-dropzone',
"{% url 'stock-item-attachment-create' %}",
{
data: {
stock_item: {{ item.id }},
},
label: 'attachment',
success: function(data, status, xhr) {
location.reload();
}
}
);
$("#new-attachment").click(function() {
launchModalForm("{% url 'stock-item-attachment-create' %}?item={{ item.id }}",
{

View File

@ -10,6 +10,7 @@
{% include "stock/tabs.html" with tab="notes" %}
{% if editing %}
<h4>{% trans "Stock Item Notes" %}</h4>
<hr>

View File

@ -0,0 +1,76 @@
{% extends "stock/item_base.html" %}
{% load static %}
{% load i18n %}
{% block details %}
{% include "stock/tabs.html" with tab='tests' %}
<h4>{% trans "Test Results" %}</h4>
<hr>
<div id='button-toolbar'>
<div class='button-toolbar container-fluid' style="float: right;">
<div class='btn-group' role='group'>
<button type='button' class='btn btn-success' id='add-test-result'>{% trans "Add Test Result" %}</button>
</div>
<div class='filter-list' id='filter-list-stocktests'>
<!-- Empty div -->
</div>
</div>
</div>
<table class='table table-striped table-condensed' data-toolbar='#button-toolbar' id='test-result-table'></table>
{% endblock %}
{% block js_ready %}
{{ block.super }}
loadStockTestResultsTable(
$("#test-result-table"), {
params: {
stock_item: {{ item.id }},
user_detail: true,
attachment_detail: true,
},
}
);
function reloadTable() {
$("#test-result-table").bootstrapTable("refresh");
}
$("#add-test-result").click(function() {
launchModalForm(
"{% url 'stock-item-test-create' %}", {
data: {
stock_item: {{ item.id }},
},
success: reloadTable,
}
);
});
$("#test-result-table").on('click', '.button-test-edit', function() {
var button = $(this);
var url = `/stock/item/test/${button.attr('pk')}/edit/`;
launchModalForm(url, {
success: reloadTable,
});
});
$("#test-result-table").on('click', '.button-test-delete', function() {
var button = $(this);
var url = `/stock/item/test/${button.attr('pk')}/delete/`;
launchModalForm(url, {
success: reloadTable,
});
});
{% endblock %}

View File

@ -1,15 +1,20 @@
{% load i18n %}
<ul class='nav nav-tabs'>
<li{% ifequal tab 'children' %} class='active'{% endifequal %}>
<a href="{% url 'stock-item-children' item.id %}">{% trans "Children" %}{% if item.child_count > 0 %}<span class='badge'>{{ item.child_count }}</span>{% endif %}</a>
</li>
<li{% ifequal tab 'tracking' %} class='active'{% endifequal %}>
<a href="{% url 'stock-item-detail' item.id %}">
{% trans "Tracking" %}
{% if item.tracking_info.count > 0 %}<span class='badge'>{{ item.tracking_info.count }}</span>{% endif %}
</a>
</li>
{% if item.part.trackable %}
<li{% if tab == 'tests' %} class='active'{% endif %}>
<a href="{% url 'stock-item-test-results' item.id %}">
{% trans "Test Results" %}
{% if item.test_results.count > 0 %}<span class='badge'>{{ item.test_results.count }}</span>{% endif %}
</a>
</li>
{% endif %}
{% if 0 %}
<!-- These tabs are to be implemented in the future -->
<li{% ifequal tab 'builds' %} class='active'{% endifequal %}>
@ -28,4 +33,9 @@
{% if item.attachments.count > 0 %}<span class='badge'>{{ item.attachments.count }}</span>{% endif %}
</a>
</li>
{% if item.child_count > 0 %}
<li{% ifequal tab 'children' %} class='active'{% endifequal %}>
<a href="{% url 'stock-item-children' item.id %}">{% trans "Children" %}{% if item.child_count > 0 %}<span class='badge'>{{ item.child_count }}</span>{% endif %}</a>
</li>
{% endif %}
</ul>

View File

@ -6,11 +6,17 @@ from django.contrib.auth import get_user_model
from .models import StockLocation
class StockLocationTest(APITestCase):
"""
Series of API tests for the StockLocation API
"""
list_url = reverse('api-location-list')
class StockAPITestCase(APITestCase):
fixtures = [
'category',
'part',
'company',
'location',
'supplier_part',
'stock',
'stock_tests',
]
def setUp(self):
# Create a user for auth
@ -18,6 +24,21 @@ class StockLocationTest(APITestCase):
User.objects.create_user('testuser', 'test@testing.com', 'password')
self.client.login(username='testuser', password='password')
def doPost(self, url, data={}):
response = self.client.post(url, data=data, format='json')
return response
class StockLocationTest(StockAPITestCase):
"""
Series of API tests for the StockLocation API
"""
list_url = reverse('api-location-list')
def setUp(self):
super().setUp()
# Add some stock locations
StockLocation.objects.create(name='top', description='top category')
@ -38,7 +59,7 @@ class StockLocationTest(APITestCase):
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
class StockItemTest(APITestCase):
class StockItemTest(StockAPITestCase):
"""
Series of API tests for the StockItem API
"""
@ -49,11 +70,7 @@ class StockItemTest(APITestCase):
return reverse('api-stock-detail', kwargs={'pk': pk})
def setUp(self):
# Create a user for auth
User = get_user_model()
User.objects.create_user('testuser', 'test@testing.com', 'password')
self.client.login(username='testuser', password='password')
super().setUp()
# Create some stock locations
top = StockLocation.objects.create(name='A', description='top')
@ -65,30 +82,11 @@ class StockItemTest(APITestCase):
self.assertEqual(response.status_code, status.HTTP_200_OK)
class StocktakeTest(APITestCase):
class StocktakeTest(StockAPITestCase):
"""
Series of tests for the Stocktake API
"""
fixtures = [
'category',
'part',
'company',
'location',
'supplier_part',
'stock',
]
def setUp(self):
User = get_user_model()
User.objects.create_user('testuser', 'test@testing.com', 'password')
self.client.login(username='testuser', password='password')
def doPost(self, url, data={}):
response = self.client.post(url, data=data, format='json')
return response
def test_action(self):
"""
Test each stocktake action endpoint,
@ -179,3 +177,82 @@ class StocktakeTest(APITestCase):
response = self.doPost(url, data)
self.assertContains(response, 'Valid location must be specified', status_code=status.HTTP_400_BAD_REQUEST)
class StockTestResultTest(StockAPITestCase):
def get_url(self):
return reverse('api-stock-test-result-list')
def test_list(self):
url = self.get_url()
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertGreaterEqual(len(response.data), 4)
response = self.client.get(url, data={'stock_item': 105})
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertGreaterEqual(len(response.data), 4)
def test_post_fail(self):
# Attempt to post a new test result without specifying required data
url = self.get_url()
response = self.client.post(
url,
data={
'test': 'A test',
'result': True,
},
format='json'
)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
# This one should pass!
response = self.client.post(
url,
data={
'test': 'A test',
'stock_item': 105,
'result': True,
},
format='json'
)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
def test_post(self):
# Test creation of a new test result
url = self.get_url()
response = self.client.get(url)
n = len(response.data)
data = {
'stock_item': 105,
'test': 'Checked Steam Valve',
'result': False,
'value': '150kPa',
'notes': 'I guess there was just too much pressure?',
}
response = self.client.post(url, data, format='json')
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
response = self.client.get(url)
self.assertEqual(len(response.data), n + 1)
# And read out again
response = self.client.get(url, data={'test': 'Checked Steam Valve'})
self.assertEqual(len(response.data), 1)
test = response.data[0]
self.assertEqual(test['value'], '150kPa')
self.assertEqual(test['user'], 1)

View File

@ -17,6 +17,7 @@ class StockTest(TestCase):
'part',
'location',
'stock',
'stock_tests',
]
def setUp(self):
@ -38,6 +39,10 @@ class StockTest(TestCase):
self.user = User.objects.get(username='username')
# Ensure the MPTT objects are correctly rebuild
Part.objects.rebuild()
StockItem.objects.rebuild()
def test_loc_count(self):
self.assertEqual(StockLocation.objects.count(), 7)
@ -91,17 +96,20 @@ class StockTest(TestCase):
self.assertFalse(self.drawer2.has_items())
# Drawer 3 should have three stock items
self.assertEqual(self.drawer3.stock_items.count(), 3)
self.assertEqual(self.drawer3.item_count, 3)
self.assertEqual(self.drawer3.stock_items.count(), 16)
self.assertEqual(self.drawer3.item_count, 16)
def test_stock_count(self):
part = Part.objects.get(pk=1)
entries = part.stock_entries()
# There should be 5000 screws in stock
self.assertEqual(entries.count(), 2)
# There should be 9000 screws in stock
self.assertEqual(part.total_stock, 9000)
# There should be 18 widgets in stock
self.assertEqual(StockItem.objects.filter(part=25).aggregate(Sum('quantity'))['quantity__sum'], 18)
self.assertEqual(StockItem.objects.filter(part=25).aggregate(Sum('quantity'))['quantity__sum'], 19)
def test_delete_location(self):
@ -161,12 +169,12 @@ class StockTest(TestCase):
self.assertEqual(w1.quantity, 4)
# There should also be a new object still in drawer3
self.assertEqual(StockItem.objects.filter(part=25).count(), 4)
self.assertEqual(StockItem.objects.filter(part=25).count(), 5)
widget = StockItem.objects.get(location=self.drawer3.id, part=25, quantity=4)
# Try to move negative units
self.assertFalse(widget.move(self.bathroom, 'Test', None, quantity=-100))
self.assertEqual(StockItem.objects.filter(part=25).count(), 4)
self.assertEqual(StockItem.objects.filter(part=25).count(), 5)
# Try to move to a blank location
self.assertFalse(widget.move(None, 'null', None))
@ -327,3 +335,99 @@ class StockTest(TestCase):
# Serialize the remainder of the stock
item.serializeStock(2, [99, 100], self.user)
class VariantTest(StockTest):
"""
Tests for calculation stock counts against templates / variants
"""
def test_variant_stock(self):
# Check the 'Chair' variant
chair = Part.objects.get(pk=10000)
# No stock items for the variant part itself
self.assertEqual(chair.stock_entries(include_variants=False).count(), 0)
self.assertEqual(chair.stock_entries().count(), 12)
green = Part.objects.get(pk=10003)
self.assertEqual(green.stock_entries(include_variants=False).count(), 0)
self.assertEqual(green.stock_entries().count(), 3)
def test_serial_numbers(self):
# Test serial number functionality for variant / template parts
chair = Part.objects.get(pk=10000)
# Operations on the top-level object
self.assertTrue(chair.checkIfSerialNumberExists(1))
self.assertTrue(chair.checkIfSerialNumberExists(2))
self.assertTrue(chair.checkIfSerialNumberExists(3))
self.assertTrue(chair.checkIfSerialNumberExists(4))
self.assertTrue(chair.checkIfSerialNumberExists(5))
self.assertTrue(chair.checkIfSerialNumberExists(20))
self.assertTrue(chair.checkIfSerialNumberExists(21))
self.assertTrue(chair.checkIfSerialNumberExists(22))
self.assertFalse(chair.checkIfSerialNumberExists(30))
self.assertEqual(chair.getNextSerialNumber(), 23)
# Same operations on a sub-item
variant = Part.objects.get(pk=10003)
self.assertEqual(variant.getNextSerialNumber(), 23)
# Create a new serial number
n = variant.getHighestSerialNumber()
item = StockItem(
part=variant,
quantity=1,
serial=n
)
# This should fail
with self.assertRaises(ValidationError):
item.save()
# This should pass
item.serial = n + 1
item.save()
# Attempt to create the same serial number but for a variant (should fail!)
item.pk = None
item.part = Part.objects.get(pk=10004)
with self.assertRaises(ValidationError):
item.save()
item.serial += 1
item.save()
class TestResultTest(StockTest):
"""
Tests for the StockItemTestResult model.
"""
def test_test_count(self):
item = StockItem.objects.get(pk=105)
tests = item.test_results
self.assertEqual(tests.count(), 4)
results = item.getTestResults(test="Temperature Test")
self.assertEqual(results.count(), 2)
# Passing tests
self.assertEqual(item.getTestResults(result=True).count(), 3)
self.assertEqual(item.getTestResults(result=False).count(), 1)
# Result map
result_map = item.testResultMap()
self.assertEqual(len(result_map), 3)
for test in ['Firmware Version', 'Settings Checksum', 'Temperature Test']:
self.assertIn(test, result_map.keys())

View File

@ -24,6 +24,7 @@ stock_item_detail_urls = [
url(r'^add_tracking/', views.StockItemTrackingCreate.as_view(), name='stock-tracking-create'),
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'),
url(r'^attachments/', views.StockItemDetail.as_view(template_name='stock/item_attachments.html'), name='stock-item-attachments'),
url(r'^notes/', views.StockItemNotes.as_view(), name='stock-item-notes'),
@ -51,12 +52,20 @@ stock_urls = [
url(r'^item/new/?', views.StockItemCreate.as_view(), name='stock-item-create'),
# URLs for StockItem attachments
url(r'^item/attachment/', include([
url(r'^new/', views.StockItemAttachmentCreate.as_view(), name='stock-item-attachment-create'),
url(r'^(?P<pk>\d+)/edit/', views.StockItemAttachmentEdit.as_view(), name='stock-item-attachment-edit'),
url(r'^(?P<pk>\d+)/delete/', views.StockItemAttachmentDelete.as_view(), name='stock-item-attachment-delete'),
])),
# URLs for StockItem tests
url(r'^item/test/', include([
url(r'^new/', views.StockItemTestResultCreate.as_view(), name='stock-item-test-create'),
url(r'^(?P<pk>\d+)/edit/', views.StockItemTestResultEdit.as_view(), name='stock-item-test-edit'),
url(r'^(?P<pk>\d+)/delete/', views.StockItemTestResultDelete.as_view(), name='stock-item-test-delete'),
])),
url(r'^track/', include(stock_tracking_urls)),
url(r'^adjust/?', views.StockAdjust.as_view(), name='stock-adjust'),

View File

@ -26,7 +26,7 @@ from datetime import datetime
from company.models import Company, SupplierPart
from part.models import Part
from .models import StockItem, StockLocation, StockItemTracking, StockItemAttachment
from .models import StockItem, StockLocation, StockItemTracking, StockItemAttachment, StockItemTestResult
from .admin import StockItemResource
@ -38,6 +38,7 @@ from .forms import TrackingEntryForm
from .forms import SerializeStockForm
from .forms import ExportOptionsForm
from .forms import EditStockItemAttachmentForm
from .forms import EditStockItemTestResultForm
class StockIndex(ListView):
@ -228,6 +229,69 @@ class StockItemAttachmentDelete(AjaxDeleteView):
}
class StockItemTestResultCreate(AjaxCreateView):
"""
View for adding a new StockItemTestResult
"""
model = StockItemTestResult
form_class = EditStockItemTestResultForm
ajax_form_title = _("Add Test Result")
def post_save(self, **kwargs):
""" Record the user that uploaded the test result """
self.object.user = self.request.user
self.object.save()
def get_initial(self):
initials = super().get_initial()
try:
stock_id = self.request.GET.get('stock_item', None)
initials['stock_item'] = StockItem.objects.get(pk=stock_id)
except (ValueError, StockItem.DoesNotExist):
pass
return initials
def get_form(self):
form = super().get_form()
form.fields['stock_item'].widget = HiddenInput()
return form
class StockItemTestResultEdit(AjaxUpdateView):
"""
View for editing a StockItemTestResult
"""
model = StockItemTestResult
form_class = EditStockItemTestResultForm
ajax_form_title = _("Edit Test Result")
def get_form(self):
form = super().get_form()
form.fields['stock_item'].widget = HiddenInput()
return form
class StockItemTestResultDelete(AjaxDeleteView):
"""
View for deleting a StockItemTestResult
"""
model = StockItemTestResult
ajax_form_title = _("Delete Test Result")
context_object_name = "result"
class StockExportOptions(AjaxView):
""" Form for selecting StockExport options """
@ -717,7 +781,7 @@ class StockItemEdit(AjaxUpdateView):
query = query.filter(part=item.part.id)
form.fields['supplier_part'].queryset = query
if not item.part.trackable:
if not item.part.trackable or not item.serialized:
form.fields.pop('serial')
return form
@ -757,6 +821,17 @@ class StockItemSerialize(AjaxUpdateView):
ajax_form_title = _('Serialize Stock')
form_class = SerializeStockForm
def get_form(self):
context = self.get_form_kwargs()
# Pass the StockItem object through to the form
context['item'] = self.get_object()
form = SerializeStockForm(**context)
return form
def get_initial(self):
initials = super().get_initial().copy()
@ -764,6 +839,7 @@ class StockItemSerialize(AjaxUpdateView):
item = self.get_object()
initials['quantity'] = item.quantity
initials['serial_numbers'] = item.part.getSerialNumberString(item.quantity)
initials['destination'] = item.location.pk
return initials
@ -844,6 +920,8 @@ class StockItemCreate(AjaxCreateView):
form = super().get_form()
part = None
# If the user has selected a Part, limit choices for SupplierPart
if form['part'].value():
part_id = form['part'].value()
@ -851,6 +929,11 @@ class StockItemCreate(AjaxCreateView):
try:
part = Part.objects.get(id=part_id)
sn = part.getNextSerialNumber()
form.field_placeholder['serial_numbers'] = _('Next available serial number is') + ' ' + str(sn)
form.rebuild_layout()
# Hide the 'part' field (as a valid part is selected)
form.fields['part'].widget = HiddenInput()
@ -873,6 +956,7 @@ class StockItemCreate(AjaxCreateView):
# If there is one (and only one) supplier part available, pre-select it
all_parts = parts.all()
if len(all_parts) == 1:
# TODO - This does NOT work for some reason? Ref build.views.BuildItemCreate
@ -884,7 +968,7 @@ class StockItemCreate(AjaxCreateView):
# Otherwise if the user has selected a SupplierPart, we know what Part they meant!
elif form['supplier_part'].value() is not None:
pass
return form
def get_initial(self):
@ -917,6 +1001,7 @@ class StockItemCreate(AjaxCreateView):
if part_id:
try:
part = Part.objects.get(pk=part_id)
# Check that the supplied part is 'valid'
if not part.is_template and part.active and not part.virtual:
initials['part'] = part
@ -954,6 +1039,8 @@ class StockItemCreate(AjaxCreateView):
- Manage serial-number valdiation for tracked parts
"""
part = None
form = self.get_form()
data = {}
@ -965,12 +1052,22 @@ class StockItemCreate(AjaxCreateView):
try:
part = Part.objects.get(id=part_id)
quantity = Decimal(form['quantity'].value())
sn = part.getNextSerialNumber()
form.field_placeholder['serial_numbers'] = _("Next available serial number is") + " " + str(sn)
form.rebuild_layout()
except (Part.DoesNotExist, ValueError, InvalidOperation):
part = None
quantity = 1
valid = False
form.errors['quantity'] = [_('Invalid quantity')]
if quantity <= 0:
form.errors['quantity'] = [_('Quantity must be greater than zero')]
valid = False
if part is None:
form.errors['part'] = [_('Invalid part selection')]
else:
@ -988,7 +1085,7 @@ class StockItemCreate(AjaxCreateView):
existing = []
for serial in serials:
if not StockItem.check_serial_number(part, serial):
if part.checkIfSerialNumberExists(serial):
existing.append(serial)
if len(existing) > 0:
@ -1003,24 +1100,26 @@ class StockItemCreate(AjaxCreateView):
form_data = form.cleaned_data
for serial in serials:
# Create a new stock item for each serial number
item = StockItem(
part=part,
quantity=1,
serial=serial,
supplier_part=form_data.get('supplier_part'),
location=form_data.get('location'),
batch=form_data.get('batch'),
delete_on_deplete=False,
status=form_data.get('status'),
link=form_data.get('link'),
)
if form.is_valid():
item.save(user=request.user)
for serial in serials:
# Create a new stock item for each serial number
item = StockItem(
part=part,
quantity=1,
serial=serial,
supplier_part=form_data.get('supplier_part'),
location=form_data.get('location'),
batch=form_data.get('batch'),
delete_on_deplete=False,
status=form_data.get('status'),
link=form_data.get('link'),
)
data['success'] = _('Created {n} new stock items'.format(n=len(serials)))
valid = True
item.save(user=request.user)
data['success'] = _('Created {n} new stock items'.format(n=len(serials)))
valid = True
except ValidationError as e:
form.errors['serial_numbers'] = e.messages
@ -1031,6 +1130,24 @@ class StockItemCreate(AjaxCreateView):
form.clean()
form._post_clean()
if form.is_valid():
item = form.save(commit=False)
item.save(user=request.user)
data['pk'] = item.pk
data['url'] = item.get_absolute_url()
data['success'] = _("Created new stock item")
valid = True
else: # Referenced Part object is not marked as "trackable"
# For non-serialized items, simply save the form.
# We need to call _post_clean() here because it is prevented in the form implementation
form.clean()
form._post_clean()
if form.is_valid:
item = form.save(commit=False)
item.save(user=request.user)
@ -1038,20 +1155,9 @@ class StockItemCreate(AjaxCreateView):
data['url'] = item.get_absolute_url()
data['success'] = _("Created new stock item")
else: # Referenced Part object is not marked as "trackable"
# For non-serialized items, simply save the form.
# We need to call _post_clean() here because it is prevented in the form implementation
form.clean()
form._post_clean()
item = form.save(commit=False)
item.save(user=request.user)
valid = True
data['pk'] = item.pk
data['url'] = item.get_absolute_url()
data['success'] = _("Created new stock item")
data['form_valid'] = valid
data['form_valid'] = valid and form.is_valid()
return self.renderJsonResponse(request, form, data=data)