[bug] Prevent editing stock attributes via API (#13384)

* [bug] Prevent editing stock attributes via API

Some stock attributes should not be editable after creation - instead follow the expected business logic / workflows

* Fix playwright test

* fix broken playwright test

* test fix
This commit is contained in:
Oliver authored and GitHub committed 2026-11-30 16:03:31 +11:00
1 parent 83cf4770f7
commit cf71d8aa63
8 files changed
+227 -27

No files matched your search

@@ -496,6 +496,55 @@ class StockItemSerializer(
return part
# Fields which may be set when a StockItem is created,
# but may only be changed afterwards via dedicated stock operations.
# These operations perform the required validation and stock tracking,
# which would otherwise be bypassed by a direct update.
UPDATE_PROTECTED_FIELDS = {
'part': _('Part cannot be changed - use the "convert" stock action'),
'quantity': _(
'Quantity cannot be changed directly - use the "count", "add" or "remove" stock actions'
),
'location': _(
'Location cannot be changed directly - use the "transfer" stock action'
),
'belongs_to': _(
'Installed item cannot be changed directly - use the "install" or "uninstall" stock actions'
),
'customer': _(
'Customer cannot be changed directly - use the "assign" stock action or a sales order'
),
'sales_order': _(
'Sales order cannot be changed directly - stock is assigned via sales order shipments'
),
'purchase_order': _(
'Purchase order cannot be changed directly - it is set when stock is received'
),
'consumed_by': _(
'Consuming build order cannot be changed directly - it is set when stock is consumed by a build order'
),
}
def validate(self, data):
"""Prevent changes to protected fields when updating an existing StockItem.
Values matching the existing values are accepted (e.g. a client sending
the complete object back), but any change to a protected field is rejected.
"""
data = super().validate(data)
if self.instance is not None and isinstance(self.instance, StockItem):
errors = {}
for field, message in self.UPDATE_PROTECTED_FIELDS.items():
if field in data and data[field] != getattr(self.instance, field):
errors[field] = message
if errors:
raise ValidationError(errors)
return data
def update(self, instance, validated_data):
"""Custom update method to pass the user information through to the instance."""
instance._user = self.context.get('user', None)
+95
View File
@@ -2483,6 +2483,101 @@ class StockItemTest(StockAPITestCase):
)
self.assertEqual(trackable_part.get_stock_count(), 10)
def test_protected_fields(self):
"""Fields managed by stock operations cannot be changed via a direct update."""
location = StockLocation.objects.first()
item = StockItem.objects.create(
part=Part.objects.filter(virtual=False, trackable=False).first(),
quantity=10,
location=location,
)
url = reverse('api-stock-detail', kwargs={'pk': item.pk})
other_part = Part.objects.filter(virtual=False).exclude(pk=item.part.pk).first()
other_location = StockLocation.objects.exclude(pk=location.pk).first()
other_item = StockItem.objects.exclude(pk=item.pk).first()
customer = company.models.Company.objects.filter(is_customer=True).first()
supplier = company.models.Company.objects.filter(is_supplier=True).first()
assembly = Part.objects.filter(assembly=True).first()
sales_order = order.models.SalesOrder.objects.create(
reference='SO-9901', customer=customer
)
purchase_order = order.models.PurchaseOrder.objects.create(
reference='PO-9901', supplier=supplier
)
build_order = build.models.Build.objects.create(
reference='BO-9901', part=assembly, quantity=1, title='Test build'
)
new_values = {
'part': other_part.pk,
'quantity': 5,
'location': other_location.pk,
'belongs_to': other_item.pk,
'customer': customer.pk,
'sales_order': sales_order.pk,
'purchase_order': purchase_order.pk,
'consumed_by': build_order.pk,
}
for field, value in new_values.items():
response = self.patch(url, {field: value}, expected_code=400)
self.assertIn(field, response.data)
# Changing several protected fields at once reports each of them
response = self.patch(
url, {'location': other_location.pk, 'quantity': 3}, expected_code=400
)
self.assertIn('location', response.data)
self.assertIn('quantity', response.data)
# Nothing was changed
item.refresh_from_db()
self.assertEqual(item.part, Part.objects.get(pk=item.part.pk))
self.assertEqual(item.quantity, 10)
self.assertEqual(item.location, location)
self.assertIsNone(item.belongs_to)
self.assertIsNone(item.customer)
self.assertIsNone(item.sales_order)
self.assertIsNone(item.purchase_order)
self.assertIsNone(item.consumed_by)
# Sending the existing values back is allowed (e.g. a full object update)
self.patch(
url,
{
'part': item.part.pk,
'quantity': '10.00000',
'location': location.pk,
'belongs_to': None,
'customer': None,
'batch': 'B-123',
},
expected_code=200,
)
item.refresh_from_db()
self.assertEqual(item.batch, 'B-123')
# Protected fields can still be set when a stock item is created
response = self.post(
self.list_url,
{'part': item.part.pk, 'quantity': 3, 'location': other_location.pk},
expected_code=201,
)
self.assertEqual(response.data[0]['location'], other_location.pk)
# ... and changed via the dedicated stock operations
self.post(
reverse('api-stock-transfer'),
{'items': [{'pk': item.pk, 'quantity': 10}], 'location': other_location.pk},
expected_code=201,
)
item.refresh_from_db()
self.assertEqual(item.location, other_location)
def test_edit_serial(self):
"""Test that we can edit serial numbers via the API."""
item = StockItem.objects.create(
+3
View File
@@ -244,6 +244,7 @@ export function useStockFields({
location: {
// Cannot adjust location for existing stock items
hidden: !create,
exclude: !create,
value: location,
onValueChange: (value) => {
setLocation(value);
@@ -254,7 +255,9 @@ export function useStockFields({
}
},
quantity: {
// Cannot adjust quantity for existing stock items
hidden: !create,
exclude: !create,
description: t`Enter initial quantity for this stock item`,
onValueChange: (value) => {
batchGenerator.update({ quantity: value });
+4 -2
View File
@@ -69,7 +69,8 @@ test('Core - User Profile', async ({ browser }) => {
await setSettingState({
setting: 'ENABLE_PREVIEW_PANEL',
value: true,
type: 'user'
type: 'user',
user: stevenuser
});
// Reload the page (to fetch the updated user setting)
@@ -86,7 +87,8 @@ test('Core - User Profile', async ({ browser }) => {
await setSettingState({
setting: 'ENABLE_PREVIEW_PANEL',
value: false,
type: 'user'
type: 'user',
user: stevenuser
});
// Disable the display of profile information
@@ -886,6 +886,14 @@ test('Parts - Pricing (Nothing, BOM)', async ({ browser }) => {
user: adminuser
});
// Ensure preview panel is enabled for this user
await setSettingState({
setting: 'ENABLE_PREVIEW_PANEL',
value: true,
type: 'user',
user: adminuser
});
await page.getByText('Small plastic enclosure, black').waitFor();
await loadTab(page, 'Part Pricing');
await page.getByLabel('Part Pricing').getByText('Part Pricing').waitFor();
@@ -14,6 +14,7 @@ for (const savedFilter of [false, true]) {
const buildIds: number[] = [];
let locationId: number | undefined;
let partId: number | undefined;
let assemblyId: number | undefined;
const create = async (url: string, data: object) => {
const response = await api.post(url, { data });
@@ -23,19 +24,29 @@ for (const savedFilter of [false, true]) {
};
try {
const suffix = generateUUID().slice(0, 8);
const part = await create('part/', {
name: `Consumed reference ${generateUUID().slice(0, 8)}`,
assembly: true,
name: `Consumed reference ${suffix}`,
component: true
});
partId = part.pk;
const assembly = await create('part/', {
name: `Consumed reference assembly ${suffix}`,
assembly: true
});
assemblyId = assembly.pk;
await create('bom/', {
part: assemblyId,
sub_part: partId,
quantity: 1
});
const parent = await create('stock/', { part: partId, quantity: 10 });
stockIds.push(parent.pk);
const builds = [];
for (let index = 0; index < 2; index++) {
const build = await create('build/', {
part: partId,
part: assemblyId,
quantity: 1,
title: `Reference test ${index}`
});
@@ -67,13 +78,39 @@ for (const savedFilter of [false, true]) {
expect(child).toBeTruthy();
stockIds.push(child.pk);
const patch = await api.patch(`stock/${child.pk}/`, {
data: {
batch: `Reference-${generateUUID().slice(0, 8)}`,
consumed_by: build?.pk ?? null
}
data: { batch: `Reference-${generateUUID().slice(0, 8)}` }
});
expect(patch.ok(), await patch.text()).toBeTruthy();
children.push(await patch.json());
if (build) {
// consumed_by is read-only: allocate the child to the build and consume it.
const lines = await (
await api.get('build/line/', { params: { build: build.pk } })
).json();
expect(lines.length).toBe(1);
const allocate = await api.post(`build/${build.pk}/allocate/`, {
data: {
items: [
{ build_line: lines[0].pk, stock_item: child.pk, quantity: 1 }
]
}
});
expect(allocate.ok(), await allocate.text()).toBeTruthy();
const consume = await api.post(`build/${build.pk}/consume/`, {
data: { lines: [{ build_line: lines[0].pk }] }
});
expect(consume.ok(), await consume.text()).toBeTruthy();
// Consumption runs in the worker; wait for its committed state.
await expect
.poll(
async () =>
(await (await api.get(`stock/${child.pk}/`)).json())
.consumed_by,
{ timeout: 15000 }
)
.toBe(build.pk);
}
}
const unconsumedChild = children[builds.length];
@@ -213,11 +250,12 @@ for (const savedFilter of [false, true]) {
await cleanup(await api.delete(`build/${pk}/`));
}
if (partId) {
for (const pk of [assemblyId, partId]) {
if (!pk) continue;
await cleanup(
await api.patch(`part/${partId}/`, { data: { active: false } })
await api.patch(`part/${pk}/`, { data: { active: false } })
);
await cleanup(await api.delete(`part/${partId}/`));
await cleanup(await api.delete(`part/${pk}/`));
}
if (locationId)
+7 -12
View File
@@ -25,12 +25,17 @@ test('Exporting - Orders', async ({ browser }) => {
user: stevenuser,
url: 'purchasing/index/purchase-orders'
});
// Ensure preview panel is disabled for this user
await setSettingState({
setting: 'ENABLE_PREVIEW_PANEL',
value: true,
type: 'user'
value: false,
type: 'user',
user: stevenuser
});
await page.reload();
await openExportDialog(page);
// // Select export format
@@ -50,16 +55,6 @@ test('Exporting - Orders', async ({ browser }) => {
await tableSearch(page, 'PO0014');
await page.getByRole('cell', { name: 'PO0014' }).click();
// Click through to the PurchaseOrder from the detail tab
await page
.getByLabel('Purchase Order PO0014 (PCBWOY)')
.getByRole('cell', { name: 'Ordering some PCBs' })
.waitFor();
await page
.getByRole('link', { name: 'details-purchaseorder-14' })
.first()
.click();
await loadTab(page, 'Line Items');
await openExportDialog(page);
await waitForDataOutput(page, () =>
+13 -3
View File
@@ -1,22 +1,32 @@
import { expect } from 'playwright/test';
import { createApi } from './api';
import type { UserType } from './defaults';
/*
* Set the value of a global setting in the database
* Set the value of a setting in the database
*
* Note: For 'user' settings, the setting is applied to the user
* whose credentials are used for the API request (default = admin).
* Pass the 'user' argument to modify the setting for a different user.
*/
export const setSettingState = async ({
setting,
value,
type = 'global',
plugin
plugin,
user
}: {
setting: string;
value: any;
type?: 'global' | 'user' | 'plugin';
plugin?: string;
user?: UserType;
}) => {
const api = await createApi({});
const api = await createApi({
username: user?.username,
password: user?.testcred
});
const url =
type === 'global'
? `settings/global/${setting}/`