diff --git a/PyRIGS/tests/pages.py b/PyRIGS/tests/pages.py
index 4bf34a6d..27d00a52 100644
--- a/PyRIGS/tests/pages.py
+++ b/PyRIGS/tests/pages.py
@@ -2,6 +2,7 @@ from pypom import Page, Region
from selenium.webdriver.common.by import By
from selenium.webdriver import Chrome
from selenium.common.exceptions import NoSuchElementException
+from PyRIGS.tests import regions
class BasePage(Page):
@@ -34,37 +35,19 @@ class FormPage(BasePage):
self.driver.execute_script("Array.from(document.getElementsByTagName(\"input\")).forEach(function (el, ind, arr) { el.removeAttribute(\"required\")});")
self.driver.execute_script("Array.from(document.getElementsByTagName(\"select\")).forEach(function (el, ind, arr) { el.removeAttribute(\"required\")});")
+ def submit(self):
+ previous_errors = self.errors
+ self.find_element(*self._submit_locator).click()
+ self.wait.until(lambda x: self.errors != previous_errors or self.success)
+
@property
def errors(self):
try:
- error_page = self.ErrorPage(self, self.find_element(*self._errors_selector))
+ error_page = regions.ErrorPage(self, self.find_element(*self._errors_selector))
return error_page.errors
except NoSuchElementException:
return None
- class ErrorPage(Region):
- _error_item_selector = (By.CSS_SELECTOR, "dl>span")
-
- class ErrorItem(Region):
- _field_selector = (By.CSS_SELECTOR, "dt")
- _error_selector = (By.CSS_SELECTOR, "dd>ul>li")
-
- @property
- def field_name(self):
- return self.find_element(*self._field_selector).text
-
- @property
- def errors(self):
- return [x.text for x in self.find_elements(*self._error_selector)]
-
- @property
- def errors(self):
- error_items = [self.ErrorItem(self, x) for x in self.find_elements(*self._error_item_selector)]
- errors = {}
- for error in error_items:
- errors[error.field_name] = error.errors
- return errors
-
class LoginPage(BasePage):
URL_TEMPLATE = '/user/login'
diff --git a/PyRIGS/tests/regions.py b/PyRIGS/tests/regions.py
index 5dd364ff..562976b5 100644
--- a/PyRIGS/tests/regions.py
+++ b/PyRIGS/tests/regions.py
@@ -131,3 +131,27 @@ class SingleSelectPicker(Region):
def set_value(self, value):
picker = Select(self.root)
picker.select_by_visible_text(value)
+
+
+class ErrorPage(Region):
+ _error_item_selector = (By.CSS_SELECTOR, "dl>span")
+
+ class ErrorItem(Region):
+ _field_selector = (By.CSS_SELECTOR, "dt")
+ _error_selector = (By.CSS_SELECTOR, "dd>ul>li")
+
+ @property
+ def field_name(self):
+ return self.find_element(*self._field_selector).text
+
+ @property
+ def errors(self):
+ return [x.text for x in self.find_elements(*self._error_selector)]
+
+ @property
+ def errors(self):
+ error_items = [self.ErrorItem(self, x) for x in self.find_elements(*self._error_item_selector)]
+ errors = {}
+ for error in error_items:
+ errors[error.field_name] = error.errors
+ return errors
diff --git a/README.md b/README.md
index 50bf51d4..8c0adcbe 100644
--- a/README.md
+++ b/README.md
@@ -1,6 +1,6 @@
# TEC PA & Lighting - PyRIGS #
-[](https://travis-ci.org/nottinghamtec/PyRIGS)
-[](https://coveralls.io/github/nottinghamtec/PyRIGS)
+[](https://travis-ci.org/nottinghamtec/PyRIGS)
+[](https://coveralls.io/github/nottinghamtec/PyRIGS)
Welcome to TEC PA & Lightings PyRIGS program. This is a reimplementation of the existing Rig Information Gathering System (RIGS) that was developed using Ruby on Rails.
diff --git a/assets/forms.py b/assets/forms.py
index 8fd07179..580a5f2e 100644
--- a/assets/forms.py
+++ b/assets/forms.py
@@ -13,7 +13,7 @@ class AssetForm(forms.ModelForm):
class Meta:
model = models.Asset
fields = '__all__'
- exclude = ['asset_id_prefix', 'asset_id_number']
+ exclude = ['asset_id_prefix', 'asset_id_number', 'last_audited_at', 'last_audited_by']
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@@ -21,6 +21,13 @@ class AssetForm(forms.ModelForm):
self.fields['date_acquired'].widget.format = '%Y-%m-%d'
+class AssetAuditForm(AssetForm):
+ class Meta(AssetForm.Meta):
+ # Prevents assets losing existing data that isn't included in the audit form
+ exclude = ['asset_id_prefix', 'asset_id_number', 'last_audited_at', 'last_audited_by',
+ 'parent', 'purchased_from', 'purchase_price', 'comments']
+
+
class AssetSearchForm(forms.Form):
query = forms.CharField(required=False)
category = forms.ModelMultipleChoiceField(models.AssetCategory.objects.all(), required=False)
diff --git a/assets/management/commands/generateSampleAssetsData.py b/assets/management/commands/generateSampleAssetsData.py
index 67b8cc9d..a7ddd404 100644
--- a/assets/management/commands/generateSampleAssetsData.py
+++ b/assets/management/commands/generateSampleAssetsData.py
@@ -1,7 +1,9 @@
import random
from django.core.management.base import BaseCommand, CommandError
from django.utils import timezone
+from reversion import revisions as reversion
from assets import models
+from RIGS import models as rigsmodels
class Command(BaseCommand):
@@ -15,6 +17,7 @@ class Command(BaseCommand):
random.seed('Some object to see the random number generator')
+ self.create_profile()
self.create_categories()
self.create_statuses()
self.create_suppliers()
@@ -22,6 +25,13 @@ class Command(BaseCommand):
self.create_connectors()
self.create_cables()
+ # Make sure that there's at least one profile if this command is run standalone
+ def create_profile(self):
+ name = "Fred Johnson"
+ models.Profile.objects.create(username=name.replace(" ", ""), first_name=name.split(" ")[0], last_name=name.split(" ")[-1],
+ email=name.replace(" ", "") + "@example.com",
+ initials="".join([j[0].upper() for j in name.split()]))
+
def create_categories(self):
categories = ['Case', 'Video', 'General', 'Sound', 'Lighting', 'Rigging']
@@ -29,17 +39,19 @@ class Command(BaseCommand):
models.AssetCategory.objects.create(name=cat)
def create_statuses(self):
- statuses = [('In Service', True), ('Lost', False), ('Binned', False), ('Sold', False), ('Broken', False)]
+ statuses = [('In Service', True, 'success'), ('Lost', False, 'warning'), ('Binned', False, 'danger'), ('Sold', False, 'danger'), ('Broken', False, 'warning')]
for stat in statuses:
- models.AssetStatus.objects.create(name=stat[0], should_show=stat[1])
+ models.AssetStatus.objects.create(name=stat[0], should_show=stat[1], display_class=stat[2])
def create_suppliers(self):
suppliers = ["Acme, inc.", "Widget Corp", "123 Warehousing", "Demo Company", "Smith and Co.", "Foo Bars", "ABC Telecom", "Fake Brothers", "QWERTY Logistics", "Demo, inc.", "Sample Company", "Sample, inc", "Acme Corp", "Allied Biscuit", "Ankh-Sto Associates", "Extensive Enterprise", "Galaxy Corp", "Globo-Chem", "Mr. Sparkle", "Globex Corporation", "LexCorp", "LuthorCorp", "North Central Positronics", "Omni Consimer Products", "Praxis Corporation", "Sombra Corporation", "Sto Plains Holdings", "Tessier-Ashpool", "Wayne Enterprises", "Wentworth Industries", "ZiffCorp", "Bluth Company", "Strickland Propane", "Thatherton Fuels", "Three Waters", "Water and Power", "Western Gas & Electric", "Mammoth Pictures", "Mooby Corp", "Gringotts", "Thrift Bank", "Flowers By Irene", "The Legitimate Businessmens Club", "Osato Chemicals", "Transworld Consortium", "Universal Export", "United Fried Chicken", "Virtucon", "Kumatsu Motors", "Keedsler Motors", "Powell Motors", "Industrial Automation", "Sirius Cybernetics Corporation", "U.S. Robotics and Mechanical Men", "Colonial Movers", "Corellian Engineering Corporation", "Incom Corporation", "General Products", "Leeding Engines Ltd.", "Blammo", # noqa
"Input, Inc.", "Mainway Toys", "Videlectrix", "Zevo Toys", "Ajax", "Axis Chemical Co.", "Barrytron", "Carrys Candles", "Cogswell Cogs", "Spacely Sprockets", "General Forge and Foundry", "Duff Brewing Company", "Dunder Mifflin", "General Services Corporation", "Monarch Playing Card Co.", "Krustyco", "Initech", "Roboto Industries", "Primatech", "Sonky Rubber Goods", "St. Anky Beer", "Stay Puft Corporation", "Vandelay Industries", "Wernham Hogg", "Gadgetron", "Burleigh and Stronginthearm", "BLAND Corporation", "Nordyne Defense Dynamics", "Petrox Oil Company", "Roxxon", "McMahon and Tate", "Sixty Second Avenue", "Charles Townsend Agency", "Spade and Archer", "Megadodo Publications", "Rouster and Sideways", "C.H. Lavatory and Sons", "Globo Gym American Corp", "The New Firm", "SpringShield", "Compuglobalhypermeganet", "Data Systems", "Gizmonic Institute", "Initrode", "Taggart Transcontinental", "Atlantic Northern", "Niagular", "Plow King", "Big Kahuna Burger", "Big T Burgers and Fries", "Chez Quis", "Chotchkies", "The Frying Dutchman", "Klimpys", "The Krusty Krab", "Monks Diner", "Milliways", "Minuteman Cafe", "Taco Grande", "Tip Top Cafe", "Moes Tavern", "Central Perk", "Chasers"] # noqa
- for supplier in suppliers:
- models.Supplier.objects.create(name=supplier)
+ with reversion.create_revision():
+ for supplier in suppliers:
+ reversion.set_user(random.choice(rigsmodels.Profile.objects.all()))
+ models.Supplier.objects.create(name=supplier)
def create_assets(self):
asset_description = ['Large cable', 'Shiny thing', 'New lights', 'Really expensive microphone', 'Box of fuse flaps', 'Expensive tool we didn\'t agree to buy', 'Cable drums', 'Boring amount of tape', 'Video stuff no one knows how to use', 'More amplifiers', 'Heatshrink']
@@ -48,22 +60,24 @@ class Command(BaseCommand):
statuses = models.AssetStatus.objects.all()
suppliers = models.Supplier.objects.all()
- for i in range(100):
- asset = models.Asset(
- asset_id='{}'.format(models.Asset.get_available_asset_id()),
- description=random.choice(asset_description),
- category=random.choice(categories),
- status=random.choice(statuses),
- date_acquired=timezone.now().date()
- )
+ with reversion.create_revision():
+ for i in range(100):
+ reversion.set_user(random.choice(rigsmodels.Profile.objects.all()))
+ asset = models.Asset(
+ asset_id='{}'.format(models.Asset.get_available_asset_id()),
+ description=random.choice(asset_description),
+ category=random.choice(categories),
+ status=random.choice(statuses),
+ date_acquired=timezone.now().date()
+ )
- if i % 4 == 0:
- asset.parent = models.Asset.objects.order_by('?').first()
+ if i % 4 == 0:
+ asset.parent = models.Asset.objects.order_by('?').first()
- if i % 3 == 0:
- asset.purchased_from = random.choice(suppliers)
- asset.clean()
- asset.save()
+ if i % 3 == 0:
+ asset.purchased_from = random.choice(suppliers)
+ asset.clean()
+ asset.save()
def create_cables(self):
asset_description = ['The worm', 'Harting without a cap', 'Heavy cable', 'Extension lead', 'IEC cable that we should remember to prep']
diff --git a/assets/migrations/0017_add_audit.py b/assets/migrations/0017_add_audit.py
new file mode 100644
index 00000000..7fb0564a
--- /dev/null
+++ b/assets/migrations/0017_add_audit.py
@@ -0,0 +1,31 @@
+# Generated by Django 3.0.3 on 2020-04-13 00:06
+
+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),
+ ('assets', '0016_auto_20200413_1632'),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name='asset',
+ name='last_audited_at',
+ field=models.DateTimeField(blank=True, null=True),
+ ),
+ migrations.AddField(
+ model_name='asset',
+ name='last_audited_by',
+ field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='audited_by', to=settings.AUTH_USER_MODEL),
+ ),
+ migrations.AlterField(
+ model_name='asset',
+ name='csa',
+ field=models.DecimalField(blank=True, decimal_places=2, help_text='mm²', max_digits=10, null=True),
+ ),
+ ]
diff --git a/assets/models.py b/assets/models.py
index 9a314a63..6cf41eee 100644
--- a/assets/models.py
+++ b/assets/models.py
@@ -9,7 +9,7 @@ from django.dispatch.dispatcher import receiver
from reversion import revisions as reversion
from reversion.models import Version
-from RIGS.models import RevisionMixin
+from RIGS.models import RevisionMixin, Profile
class AssetCategory(models.Model):
@@ -104,13 +104,17 @@ class Asset(models.Model, RevisionMixin):
salvage_value = models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=10)
comments = models.TextField(blank=True)
+ # Audit
+ last_audited_at = models.DateTimeField(blank=True, null=True)
+ last_audited_by = models.ForeignKey(Profile, on_delete=models.SET_NULL, related_name='audited_by', blank=True, null=True)
+
# Cable assets
is_cable = models.BooleanField(default=False)
cable_type = models.ForeignKey(to=CableType, blank=True, null=True, on_delete=models.SET_NULL)
length = models.DecimalField(decimal_places=1, max_digits=10,
blank=True, null=True, help_text='m')
csa = models.DecimalField(decimal_places=2, max_digits=10,
- blank=True, null=True, help_text='mm^2')
+ blank=True, null=True, help_text='mm²')
# Hidden asset_id components
# For example, if asset_id was "C1001" then asset_id_prefix would be "C" and number "1001"
diff --git a/assets/templates/asset_audit.html b/assets/templates/asset_audit.html
new file mode 100644
index 00000000..2ed26c88
--- /dev/null
+++ b/assets/templates/asset_audit.html
@@ -0,0 +1,142 @@
+{% extends request.is_ajax|yesno:'base_ajax.html,base_assets.html' %}
+{% load widget_tweaks %}
+{% block title %}Audit Asset {{ object.asset_id }}{% endblock %}
+
+{% block content %}
+
+
+{% endblock %}
+
+{% block footer %}
+
+
+
+{% endblock %}
diff --git a/assets/templates/asset_audit_list.html b/assets/templates/asset_audit_list.html
new file mode 100644
index 00000000..5117bbed
--- /dev/null
+++ b/assets/templates/asset_audit_list.html
@@ -0,0 +1,87 @@
+{% extends 'base_assets.html' %}
+{% block title %}Asset Audit List{% endblock %}
+{% load static %}
+{% load paginator from filters %}
+{% load widget_tweaks %}
+
+{% block js %}
+
+
+
+
+{% endblock %}
+
+{% block content %}
+
+
+
+
+ Asset with that ID does not exist!
+
+
+Audit Asset:
+
+
+Assets Requiring Audit:
+
+
+
+ | Asset ID |
+ Description |
+ Category |
+ Status |
+ |
+
+
+
+ {% include 'partials/asset_list_table_body.html' with audit="true" %}
+
+
+
+{% if is_paginated %}
+
+ {% paginator %}
+
+{% endif %}
+{% endblock %}
diff --git a/assets/templates/asset_update.html b/assets/templates/asset_update.html
index 4f576130..cd781de5 100644
--- a/assets/templates/asset_update.html
+++ b/assets/templates/asset_update.html
@@ -1,4 +1,4 @@
-{% extends 'base_assets.html' %}
+{% extends request.is_ajax|yesno:'base_ajax.html,base_assets.html' %}
{% load widget_tweaks %}
{% block title %}Asset {{ object.asset_id }}{% endblock %}
@@ -23,18 +23,23 @@
- {% if perms.assets.asset_finance %}
-
- {% include 'partials/purchasedetails_form.html' %}
-
- {%endif%}
-
{% include 'partials/cable_form.html' %}
+ {% if perms.assets.asset_finance %}
+
+ {% include 'partials/purchasedetails_form.html' %}
+
+ {%endif%}
{% include 'partials/parent_form.html' %}
+ {% if not edit %}
+
+ {% include 'partials/audit_details.html' %}
+
+ {% endif %}
diff --git a/assets/templates/partials/asset_buttons.html b/assets/templates/partials/asset_buttons.html
index 3c99225f..d947e57b 100644
--- a/assets/templates/partials/asset_buttons.html
+++ b/assets/templates/partials/asset_buttons.html
@@ -1,25 +1,28 @@
-{% if edit and object %}
-
-
-
Duplicate
-{% elif duplicate %}
-
-
-{% elif create %}
-
-
-{% else %}
-
-
-{% endif %}
-{% if create or edit or duplicate %}
-
-
+{% if perms.assets.change_asset %}
+ {% if edit and object %}
+
+
+
Duplicate
+ {% elif duplicate %}
+
+
+ {% elif create %}
+
+
+ {% else %}
+
+
+ {% endif %}
+ {% if create or edit or duplicate %}
+
+
+ {% endif %}
{% endif %}
diff --git a/assets/templates/partials/asset_list_table_body.html b/assets/templates/partials/asset_list_table_body.html
index 352d15db..64526d08 100644
--- a/assets/templates/partials/asset_list_table_body.html
+++ b/assets/templates/partials/asset_list_table_body.html
@@ -1,19 +1,21 @@
{% for item in object_list %}
- {#
{{ item.asset_id }} - {{ item.description }}#}
-
-
+
| {{ item.asset_id }} |
{{ item.description }} |
{{ item.category }} |
{{ item.status }} |
+ {% endif %}
|
{% endfor %}
diff --git a/assets/templates/partials/audit_details.html b/assets/templates/partials/audit_details.html
new file mode 100644
index 00000000..8edc2d80
--- /dev/null
+++ b/assets/templates/partials/audit_details.html
@@ -0,0 +1,8 @@
+
+
+ Audit Details
+
+
+
Audited at {{ object.last_audited_at|default_if_none:'-' }} by {{ object.last_audited_by|default_if_none:'-' }}
+
+
diff --git a/assets/tests/pages.py b/assets/tests/pages.py
index c68d2568..f505c116 100644
--- a/assets/tests/pages.py
+++ b/assets/tests/pages.py
@@ -6,7 +6,7 @@ from selenium.webdriver import Chrome
from django.urls import reverse
from PyRIGS.tests import regions
from PyRIGS.tests.pages import BasePage, FormPage
-import pdb
+from selenium.common.exceptions import NoSuchElementException
class AssetList(BasePage):
@@ -95,11 +95,6 @@ class AssetForm(FormPage):
def parent_selector(self):
return regions.BootstrapSelectElement(self, self.find_element(*self._parent_select_locator))
- def submit(self):
- previous_errors = self.errors
- self.find_element(*self._submit_locator).click()
- self.wait.until(lambda x: self.errors != previous_errors or self.success)
-
class AssetEdit(AssetForm):
URL_TEMPLATE = '/assets/asset/id/{asset_id}/edit/'
@@ -162,11 +157,6 @@ class SupplierForm(FormPage):
'name': (regions.TextBox, (By.ID, 'id_name')),
}
- def submit(self):
- previous_errors = self.errors
- self.find_element(*self._submit_locator).click()
- self.wait.until(lambda x: self.errors != previous_errors or self.success)
-
class SupplierCreate(SupplierForm):
URL_TEMPLATE = reverse('supplier_create')
@@ -183,3 +173,90 @@ class SupplierEdit(SupplierForm):
@property
def success(self):
return '/edit' not in self.driver.current_url
+
+
+class AssetAuditList(AssetList):
+ URL_TEMPLATE = reverse('asset_audit_list')
+
+ _search_text_locator = (By.ID, 'id_query')
+ _go_button_locator = (By.ID, 'searchButton')
+ _modal_locator = (By.ID, 'modal')
+ _errors_selector = (By.CLASS_NAME, "alert-danger")
+
+ @property
+ def modal(self):
+ return self.AssetAuditModal(self, self.find_element(*self._modal_locator))
+
+ @property
+ def query(self):
+ return self.find_element(*self._search_text_locator).text
+
+ def set_query(self, queryString):
+ element = self.find_element(*self._search_text_locator)
+ element.clear()
+ element.send_keys(queryString)
+
+ def search(self):
+ self.find_element(*self._go_button_locator).click()
+
+ @property
+ def error(self):
+ try:
+ return self.find_element(*self._errors_selector)
+ except NoSuchElementException:
+ return None
+
+ class AssetAuditModal(Region):
+ _errors_selector = (By.CLASS_NAME, "alert-danger")
+ # Don't use the usual success selector - that tries and fails to hit the '10m long cable' helper button...
+ _submit_locator = (By.ID, "id_mark_audited")
+ form_items = {
+ 'asset_id': (regions.TextBox, (By.ID, 'id_asset_id')),
+ 'description': (regions.TextBox, (By.ID, 'id_description')),
+ 'is_cable': (regions.CheckBox, (By.ID, 'id_is_cable')),
+ 'serial_number': (regions.TextBox, (By.ID, 'id_serial_number')),
+ 'salvage_value': (regions.TextBox, (By.ID, 'id_salvage_value')),
+ 'date_acquired': (regions.DatePicker, (By.ID, 'id_date_acquired')),
+ 'category': (regions.SingleSelectPicker, (By.ID, 'id_category')),
+ 'status': (regions.SingleSelectPicker, (By.ID, 'id_status')),
+
+ 'plug': (regions.SingleSelectPicker, (By.ID, 'id_plug')),
+ 'socket': (regions.SingleSelectPicker, (By.ID, 'id_socket')),
+ 'length': (regions.TextBox, (By.ID, 'id_length')),
+ 'csa': (regions.TextBox, (By.ID, 'id_csa')),
+ 'circuits': (regions.TextBox, (By.ID, 'id_circuits')),
+ 'cores': (regions.TextBox, (By.ID, 'id_cores'))
+ }
+
+ @property
+ def errors(self):
+ try:
+ error_page = regions.ErrorPage(self, self.find_element(*self._errors_selector))
+ return error_page.errors
+ except NoSuchElementException:
+ return None
+
+ def submit(self):
+ previous_errors = self.errors
+ self.root.find_element(*self._submit_locator).click()
+ # self.wait.until(lambda x: not self.is_displayed) TODO
+
+ def remove_all_required(self):
+ self.driver.execute_script("Array.from(document.getElementsByTagName(\"input\")).forEach(function (el, ind, arr) { el.removeAttribute(\"required\")});")
+ self.driver.execute_script("Array.from(document.getElementsByTagName(\"select\")).forEach(function (el, ind, arr) { el.removeAttribute(\"required\")});")
+
+ def __getattr__(self, name):
+ if name in self.form_items:
+ element = self.form_items[name]
+ form_element = element[0](self, self.find_element(*element[1]))
+ return form_element.value
+ else:
+ return super().__getattribute__(name)
+
+ def __setattr__(self, name, value):
+ if name in self.form_items:
+ element = self.form_items[name]
+ form_element = element[0](self, self.find_element(*element[1]))
+ form_element.set_value(value)
+ else:
+ self.__dict__[name] = value
diff --git a/assets/tests/test_assets.py b/assets/tests/test_assets.py
index 06d35701..2647d0f3 100644
--- a/assets/tests/test_assets.py
+++ b/assets/tests/test_assets.py
@@ -9,8 +9,13 @@ from RIGS import models as rigsmodels
from PyRIGS.tests.base import BaseTest, AutoLoginTest
from assets import models, urls
from reversion import revisions as reversion
+from selenium.webdriver.support import expected_conditions as EC
+from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
+from selenium.webdriver.support.ui import WebDriverWait
+from RIGS.test_functional import animation_is_finished
import datetime
+from django.utils import timezone
class TestAssetList(AutoLoginTest):
@@ -255,6 +260,76 @@ class TestSupplierCreateAndEdit(AutoLoginTest):
self.assertTrue(self.page.success)
+class TestAssetAudit(AutoLoginTest):
+ def setUp(self):
+ super().setUp()
+ self.category = models.AssetCategory.objects.create(name="Haulage")
+ self.status = models.AssetStatus.objects.create(name="Probably Fine", should_show=True)
+ self.supplier = models.Supplier.objects.create(name="The Bazaar")
+ self.connector = models.Connector.objects.create(description="Trailer Socket", current_rating=1, voltage_rating=40, num_pins=13)
+ models.Asset.objects.create(asset_id="1", description="Trailer Cable", status=self.status, category=self.category, date_acquired=datetime.date(2020, 2, 1))
+ models.Asset.objects.create(asset_id="11", description="Trailerboard", status=self.status, category=self.category, date_acquired=datetime.date(2020, 2, 1))
+ models.Asset.objects.create(asset_id="111", description="Erms", status=self.status, category=self.category, date_acquired=datetime.date(2020, 2, 1))
+ models.Asset.objects.create(asset_id="1111", description="A hammer", status=self.status, category=self.category, date_acquired=datetime.date(2020, 2, 1))
+ self.page = pages.AssetAuditList(self.driver, self.live_server_url).open()
+ self.wait = WebDriverWait(self.driver, 5)
+
+ def test_audit_process(self):
+ asset_id = "1111"
+ self.page.set_query(asset_id)
+ self.page.search()
+ mdl = self.page.modal
+ self.wait.until(EC.visibility_of_element_located((By.ID, 'modal')))
+ # Do it wrong on purpose to check error display
+ mdl.remove_all_required()
+ mdl.description = ""
+ mdl.submit()
+ # self.wait.until(EC.visibility_of_element_located((By.ID, 'modal')))
+ self.wait.until(animation_is_finished())
+ # self.assertTrue(self.driver.find_element_by_id('modal').is_displayed())
+ self.assertIn("This field is required.", mdl.errors["Description"])
+ # Now do it properly
+ new_desc = "A BIG hammer"
+ mdl.description = new_desc
+ mdl.submit()
+ self.wait.until(animation_is_finished())
+ self.assertFalse(self.driver.find_element_by_id('modal').is_displayed())
+
+ # Check data is correct
+ audited = models.Asset.objects.get(asset_id="1111")
+ self.assertEqual(audited.description, new_desc)
+ # Make sure audit 'log' was filled out
+ self.assertEqual(self.profile.initials, audited.last_audited_by.initials)
+ self.assertEqual(timezone.now().date(), audited.last_audited_at.date())
+ self.assertEqual(timezone.now().hour, audited.last_audited_at.hour)
+ self.assertEqual(timezone.now().minute, audited.last_audited_at.minute)
+ # Check we've removed it from the 'needing audit' list
+ self.assertNotIn(asset_id, self.page.assets)
+
+ def test_audit_list(self):
+ self.assertEqual(len(models.Asset.objects.filter(last_audited_at=None)), len(self.page.assets))
+
+ assetRow = self.page.assets[0]
+ assetRow.find_element(By.CSS_SELECTOR, "td:nth-child(5) > div:nth-child(1) > a:nth-child(1)").click()
+ self.wait.until(EC.visibility_of_element_located((By.ID, 'modal')))
+ self.assertEqual(self.page.modal.asset_id, assetRow.id)
+
+ # First close button is for the not found error
+ self.page.find_element(By.XPATH, '(//button[@class="close"])[2]').click()
+ self.wait.until(animation_is_finished())
+ self.assertFalse(self.driver.find_element_by_id('modal').is_displayed())
+ # Make sure audit log was NOT filled out
+ audited = models.Asset.objects.get(asset_id=assetRow.id)
+ self.assertEqual(None, audited.last_audited_by)
+
+ # Check that a failed search works
+ self.page.set_query("NOTFOUND")
+ self.page.search()
+ self.wait.until(animation_is_finished())
+ self.assertFalse(self.driver.find_element_by_id('modal').is_displayed())
+ self.assertIn("Asset with that ID does not exist!", self.page.error.text)
+
+
class TestSupplierValidation(TestCase):
@classmethod
def setUpTestData(cls):
diff --git a/assets/urls.py b/assets/urls.py
index 8bc3c2a0..dc76ecbe 100644
--- a/assets/urls.py
+++ b/assets/urls.py
@@ -36,6 +36,9 @@ urlpatterns = [
views.AssetOembed.as_view(),
name='asset_oembed'),
+ path('asset/audit/', permission_required_with_403('assets.change_asset')(views.AssetAuditList.as_view()), name='asset_audit_list'),
+ path('asset/id/
/audit/', permission_required_with_403('assets.change_asset')(views.AssetAudit.as_view()), name='asset_audit'),
+
path('supplier/list', views.SupplierList.as_view(), name='supplier_list'),
path('supplier/', views.SupplierDetail.as_view(), name='supplier_detail'),
path('supplier/create', permission_required_with_403('assets.add_supplier')
diff --git a/assets/views.py b/assets/views.py
index 29e86872..c748fa05 100644
--- a/assets/views.py
+++ b/assets/views.py
@@ -4,13 +4,17 @@ from django.http import HttpResponse, Http404
from django.views import generic
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
-from django.urls import reverse
+from django.urls import reverse_lazy, reverse
from django.db.models import Q
from django.shortcuts import get_object_or_404
+from django.core import serializers
+from django.contrib import messages
from assets import models, forms
from RIGS import versioning
import simplejson
+import datetime
+from django.utils import timezone
@method_decorator(csrf_exempt, name='dispatch')
@@ -109,7 +113,14 @@ class AssetEdit(LoginRequiredMixin, AssetIDUrlMixin, generic.UpdateView):
return context
def get_success_url(self):
- return reverse("asset_detail", kwargs={"pk": self.object.asset_id})
+ if self.request.is_ajax():
+ url = reverse_lazy('closemodal')
+ update_url = str(reverse_lazy('asset_update', kwargs={'pk': self.object.pk}))
+ messages.info(self.request, "modalobject=" + serializers.serialize("json", [self.object]))
+ messages.info(self.request, "modalobject[0]['update_url']='" + update_url + "'")
+ else:
+ url = reverse_lazy('asset_detail', kwargs={'pk': self.object.asset_id, })
+ return url
class AssetCreate(LoginRequiredMixin, generic.CreateView):
@@ -173,6 +184,30 @@ class AssetEmbed(AssetDetail):
template_name = 'asset_embed.html'
+@method_decorator(csrf_exempt, name='dispatch')
+class AssetAuditList(AssetList):
+ template_name = 'asset_audit_list.html'
+ hide_hidden_status = False
+
+ # TODO Refresh this when the modal is submitted
+ def get_queryset(self):
+ self.form = forms.AssetSearchForm(data={})
+ return self.model.objects.filter(Q(last_audited_at__isnull=True))
+
+
+class AssetAudit(AssetEdit):
+ template_name = 'asset_audit.html'
+ form_class = forms.AssetAuditForm
+
+ def get_success_url(self):
+ # TODO For some reason this doesn't stick when done in form_valid??
+ asset = self.get_object()
+ asset.last_audited_by = self.request.user
+ asset.last_audited_at = timezone.now()
+ asset.save()
+ return super().get_success_url()
+
+
class SupplierList(generic.ListView):
model = models.Supplier
template_name = 'supplier_list.html'
diff --git a/templates/base_assets.html b/templates/base_assets.html
index 7f226963..1dc36e08 100644
--- a/templates/base_assets.html
+++ b/templates/base_assets.html
@@ -37,5 +37,6 @@
{% if perms.assets.view_asset %}
Recent Changes
+ Audit
{% endif %}
{% endblock %}