2
0
mirror of https://github.com/inventree/InvenTree.git synced 2025-06-18 04:55:44 +00:00
Files
InvenTree/InvenTree/company/test_api.py
Oliver 06266b48af Part pricing cache (#3710)
* Create new model for storing Part pricing data

Currently this model does not "do" anything but will be used for caching pre-calculated pricing information

* Define function for accessing pricing information for a specific part

* Adds admin site support for new PartPricing model

* Specify role for PartPricing model

* Allow blank values for PartPricing model fields

* Add some TODO entries

* Update migration files to sync with latest master

* Expose API endpoint for viewing part pricing information

* Update migration file

* Improvements:

- Updated model with new fields
- Code for calculating BOM price
- Code for calculating internal price
- Code for calculating supplier price
- Updated unit testing

* Fix (and test) for API serializer

* Including min/max pricing data in part serializer

* Bump API version

* Add pricing overview information in part table

- Adds helper function for formatting currency data
- No longer pre-render "price strings" on the server

* Overhaul of BOM API

- Pricing data no longer calculated "on the fly"
- Remove expensive annotation operations
- Display cached price range information in BOM table

* Filter BOM items by "has pricing"

* Part API endpoint can be filtered by price range

* Updpated API version notes

* Improvements for price caching calculations

- Handle null price values
- Handle case where conversion rates are missing
- Allow manual update via API

* Button to manually refresh pricing

* Improve rendering of price-break table

* Update supplier part pricing table

* Updated js functions

* Adds background task to update assembly pricing whenever a part price cache is changed

* Updates for task offloading

* HTML tweaks

* Implement calculation of historical purchase cost

- take supplier part pack size into account
- improve unit tests

* Improvements for pricing tab rendering

* Refactor of pricing page

- Move javascript functions out into separate files
- Change price-break tables to use bar graphs
- Display part pricing history table and chart
- Remove server-side rendering for price history data
- Fix rendering of supplier pricing table
- Adds extra filtering options to the SupplierPriceBreak API endpoint

* Refactor BOM pricing chart / table

- Display as bar chart with min/max pricing
- Display simplified BOM table

* Update page anchors

* Improvements for BOM pricing table display

* Refactoring sales data tables

- Add extra data and filter options to sales order API endpoints
- Display sales order history table and chart

* Add extra fields to PartPricing model:

- sale_price_min
- sale_price_max
- sale_history_min
- sale_history_max

* Calculate and cache sale price data

* Update part pricing when PurchaseOrder is completed

* Update part pricing when sales order is completed

* Signals for updating part pricing cache

- Whenever an internal price break is created / edited / deleted
- Whenever a sale price break is created / edited / deleted

* Also trigger part pricing update when BomItem is created  / edited / deleted

* Update part pricing whenever a supplier price break is updated

* Remove has_complete_bom_pricing method

* Export min/max pricing data in BOM file

* Fix pricing data in BOM export

- Calculate total line cost
- Use more than two digits

* Add pricing information to part export

Also some improvements to part exporting

* Allow download of part category table

* Allow export of stock location data to file

* Improved exporting of StockItem data

* Add cached variant pricing data

- New fields in part pricing model
- Display variant pricing overview in "pricing" tab

* Remove outdated "PART_SHOW_PRICE_HISTORY" setting

* Adds scheduled background task to periodically update part pricing

* Internal prices can optionally override other pricing

* Update js file checks

* Update price breaks to use 6 decimal places

* Fix for InvenTreeMoneySerializer class

- Allow 6 decimal places through the API

* Update for supplier price break table

* javascript linting fix

* Further js fixes

* Unit test updates

* Improve rendering of currency in templates

- Do not artificially limit to 2 decimal places

* Unit test fixes

* Add pricing information to part "details" tab

* Tweak for money formatting

* Enable sort-by-price in BOM table

* More unit test tweaks

* Update BOM exporting

* Fixes for background worker process

- To determine if worker is running, look for *any* successful task, not just heartbeat
- Heartbeat rate increased to 5 minute intervals
- Small adjustments to django_q settings

Ref: https://github.com/inventree/InvenTree/issues/3921
(cherry picked from commit cb26003b92)

* Force background processing of heartbeat task when server is started

- Removes the ~5 minute window in which the server "thinks" that the worker is not actually running

* Adjust strategy for preventing recursion

- Rather than looking for duplicate parts, simply increment a counter
- Add a "scheduled_for_update" flag to prevent multiple updates being scheduled
- Consolidate migration files

* Adds helper function for rendering a range of prices

* Include variant cost in calculations

* Fixes for "has_pricing" API filters

* Ensure part pricing status flags are reset when the server restarts

* Bug fix for BOM API filter

* Include BOM quantity in BOM pricing chart

* Small tweaks to pricing tab

* Prevent caching when looking up settings in background worker

- Caching across mnultiple processes causes issues
- Need to move to something like redis to solve this
- Ref: https://github.com/inventree/InvenTree/issues/3921

* Fixes for /part/pricing/ detail API endpoint

* Update pricing tab

- Consistent naming

* Unit test fixes

* Prevent pricing updates when loading test fixtures

* Fix for Part.pricing

* Updates for "check_missing_pricing"

* Change to pie chart for BOM pricing

* Unit test fix

* Updates

- Sort BOM pie chart correctly
- Simplify PartPricing.is_valid
- Pass "limit" through to check_missing_pricing
- Improved logic for update scheduling

* Add option for changing how many decimals to use when displaying pricing data

* remove old unused setting

* Consolidate settings tabs for pricing and currencies

* Fix CI after changing settings page

* Fix rendering for "Supplier Pricing"

- Take unit pricing / pack size into account

* Extra filtering / ordering options for the SupplierPriceBreak API endpoint

* Fix for purchase price history graph

- Use unit pricing (take pack size into account)

* JS fixes
2022-11-14 15:58:22 +11:00

352 lines
10 KiB
Python

"""Unit testing for the company app API functions"""
from django.urls import reverse
from rest_framework import status
from InvenTree.api_tester import InvenTreeAPITestCase
from .models import Company, SupplierPart
class CompanyTest(InvenTreeAPITestCase):
"""Series of tests for the Company DRF API."""
roles = [
'purchase_order.add',
'purchase_order.change',
]
def setUp(self):
"""Perform initialization for the unit test class"""
super().setUp()
self.acme = Company.objects.create(name='ACME', description='Supplier', is_customer=False, is_supplier=True)
Company.objects.create(name='Drippy Cup Co.', description='Customer', is_customer=True, is_supplier=False)
Company.objects.create(name='Sippy Cup Emporium', description='Another supplier')
def test_company_list(self):
"""Test the list API endpoint for the Company model"""
url = reverse('api-company-list')
# There should be three companies
response = self.get(url)
self.assertEqual(len(response.data), 3)
data = {'is_customer': True}
# There should only be one customer
response = self.get(url, data)
self.assertEqual(len(response.data), 1)
data = {'is_supplier': True}
# There should be two suppliers
response = self.get(url, data)
self.assertEqual(len(response.data), 2)
def test_company_detail(self):
"""Tests for the Company detail endpoint."""
url = reverse('api-company-detail', kwargs={'pk': self.acme.pk})
response = self.get(url)
self.assertEqual(response.data['name'], 'ACME')
# Change the name of the company
# Note we should not have the correct permissions (yet)
data = response.data
response = self.client.patch(url, data, format='json', expected_code=400)
self.assignRole('company.change')
# Update the name and set the currency to a valid value
data['name'] = 'ACMOO'
data['currency'] = 'NZD'
response = self.client.patch(url, data, format='json', expected_code=200)
self.assertEqual(response.data['name'], 'ACMOO')
self.assertEqual(response.data['currency'], 'NZD')
def test_company_search(self):
"""Test search functionality in company list."""
url = reverse('api-company-list')
data = {'search': 'cup'}
response = self.get(url, data)
self.assertEqual(len(response.data), 2)
def test_company_create(self):
"""Test that we can create a company via the API!"""
url = reverse('api-company-list')
# Name is required
response = self.post(
url,
{
'description': 'A description!',
},
expected_code=400
)
# Minimal example, checking default values
response = self.post(
url,
{
'name': 'My API Company',
'description': 'A company created via the API',
},
expected_code=201
)
self.assertTrue(response.data['is_supplier'])
self.assertFalse(response.data['is_customer'])
self.assertFalse(response.data['is_manufacturer'])
self.assertEqual(response.data['currency'], 'USD')
# Maximal example, specify values
response = self.post(
url,
{
'name': "Another Company",
'description': "Also created via the API!",
'currency': 'AUD',
'is_supplier': False,
'is_manufacturer': True,
'is_customer': True,
},
expected_code=201
)
self.assertEqual(response.data['currency'], 'AUD')
self.assertFalse(response.data['is_supplier'])
self.assertTrue(response.data['is_customer'])
self.assertTrue(response.data['is_manufacturer'])
# Attempt to create with invalid currency
response = self.post(
url,
{
'name': "A name",
'description': 'A description',
'currency': 'POQD',
},
expected_code=400
)
self.assertTrue('currency' in response.data)
class ManufacturerTest(InvenTreeAPITestCase):
"""Series of tests for the Manufacturer DRF API."""
fixtures = [
'category',
'part',
'location',
'company',
'manufacturer_part',
'supplier_part',
]
roles = [
'part.add',
'part.change',
]
def test_manufacturer_part_list(self):
"""Test the ManufacturerPart API list functionality"""
url = reverse('api-manufacturer-part-list')
# There should be three manufacturer parts
response = self.get(url)
self.assertEqual(len(response.data), 3)
# Create manufacturer part
data = {
'part': 1,
'manufacturer': 7,
'MPN': 'MPN_TEST',
}
response = self.client.post(url, data, format='json')
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(response.data['MPN'], 'MPN_TEST')
# Filter by manufacturer
data = {'manufacturer': 7}
response = self.get(url, data)
self.assertEqual(len(response.data), 3)
# Filter by part
data = {'part': 5}
response = self.get(url, data)
self.assertEqual(len(response.data), 2)
def test_manufacturer_part_detail(self):
"""Tests for the ManufacturerPart detail endpoint."""
url = reverse('api-manufacturer-part-detail', kwargs={'pk': 1})
response = self.get(url)
self.assertEqual(response.data['MPN'], 'MPN123')
# Change the MPN
data = {
'MPN': 'MPN-TEST-123',
}
response = self.client.patch(url, data, format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data['MPN'], 'MPN-TEST-123')
def test_manufacturer_part_search(self):
"""Test search functionality in manufacturer list"""
url = reverse('api-manufacturer-part-list')
data = {'search': 'MPN'}
response = self.get(url, data)
self.assertEqual(len(response.data), 3)
def test_supplier_part_create(self):
"""Test a SupplierPart can be created via the API"""
url = reverse('api-supplier-part-list')
# Create a manufacturer part
response = self.post(
reverse('api-manufacturer-part-list'),
{
'part': 1,
'manufacturer': 7,
'MPN': 'PART_NUMBER',
'link': 'https://www.axel-larsson.se/Exego.aspx?p_id=341&ArtNr=0804020E',
},
expected_code=201
)
pk = response.data['pk']
# Create a supplier part (associated with the new manufacturer part)
data = {
'part': 1,
'supplier': 1,
'SKU': 'SKU_TEST',
'manufacturer_part': pk,
'link': 'https://www.axel-larsson.se/Exego.aspx?p_id=341&ArtNr=0804020E',
}
response = self.client.post(url, data, format='json')
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
# Check link is not modified
self.assertEqual(response.data['link'], 'https://www.axel-larsson.se/Exego.aspx?p_id=341&ArtNr=0804020E')
# Check link is not modified
self.assertEqual(response.data['link'], 'https://www.axel-larsson.se/Exego.aspx?p_id=341&ArtNr=0804020E')
class SupplierPartTest(InvenTreeAPITestCase):
"""Unit tests for the SupplierPart API endpoints"""
fixtures = [
'category',
'part',
'location',
'company',
'manufacturer_part',
'supplier_part',
]
roles = [
'part.add',
'part.change',
'part.add',
'purchase_order.change',
]
def test_supplier_part_list(self):
"""Test the SupplierPart API list functionality"""
url = reverse('api-supplier-part-list')
# Return *all* SupplierParts
response = self.get(url, {}, expected_code=200)
self.assertEqual(len(response.data), SupplierPart.objects.count())
# Filter by Supplier reference
for supplier in Company.objects.filter(is_supplier=True):
response = self.get(url, {'supplier': supplier.pk}, expected_code=200)
self.assertEqual(len(response.data), supplier.supplied_parts.count())
# Filter by Part reference
expected = {
1: 4,
25: 2,
}
for pk, n in expected.items():
response = self.get(url, {'part': pk}, expected_code=200)
self.assertEqual(len(response.data), n)
def test_available(self):
"""Tests for updating the 'available' field"""
url = reverse('api-supplier-part-list')
# Should fail when sending an invalid 'available' field
response = self.post(
url,
{
'part': 1,
'supplier': 2,
'SKU': 'QQ',
'available': 'not a number',
},
expected_code=400,
)
self.assertIn('A valid number is required', str(response.data))
# Create a SupplierPart without specifying available quantity
response = self.post(
url,
{
'part': 1,
'supplier': 2,
'SKU': 'QQ',
},
expected_code=201
)
sp = SupplierPart.objects.get(pk=response.data['pk'])
self.assertIsNone(sp.availability_updated)
self.assertEqual(sp.available, 0)
# Now, *update* the availabile quantity via the API
self.patch(
reverse('api-supplier-part-detail', kwargs={'pk': sp.pk}),
{
'available': 1234,
},
expected_code=200,
)
sp.refresh_from_db()
self.assertIsNotNone(sp.availability_updated)
self.assertEqual(sp.available, 1234)
# We should also be able to create a SupplierPart with initial 'available' quantity
response = self.post(
url,
{
'part': 1,
'supplier': 2,
'SKU': 'QQQ',
'available': 999,
},
expected_code=201,
)
sp = SupplierPart.objects.get(pk=response.data['pk'])
self.assertEqual(sp.available, 999)
self.assertIsNotNone(sp.availability_updated)