Coverage for src/backend/InvenTree/stock/migrations/0096_auto_20230330_1121.py: 47%

22 statements  

« prev     ^ index     » next       coverage.py v7.15.2, created at 2026-10-07 17:47 +0000

1# Generated by Django 3.2.18 on 2023-03-30 11:21 

2 

3from django.db import migrations 

4 

5 

6def update_stock_history(apps, schema_editor): 

7 """Data migration to fix a 'shortcoming' in the implementation of StockTracking history 

8 

9 Prior to https://github.com/inventree/InvenTree/pull/4488, 

10 shipping items via a SalesOrder did not record the SalesOrder in the tracking history. 

11 This PR looks to add in SalesOrder history where it does not already exist: 

12 

13 - Look for StockItems which are currently assigned to a SalesOrder 

14 - Check that it does *not* have any appropriate history 

15 - Add the appropriate history! 

16 """ 

17 

18 from stock.status_codes import StockHistoryCode 

19 

20 StockItem = apps.get_model('stock', 'stockitem') 

21 StockItemTracking = apps.get_model('stock', 'stockitemtracking') 

22 

23 # Find StockItems which are marked as against a SalesOrder 

24 items = StockItem.objects.exclude(sales_order=None) 

25 

26 n = 0 

27 

28 for item in items: 28 ↛ 30line 28 didn't jump to line 30 because the loop on line 28 never started

29 # Find newest relevant history 

30 history = StockItemTracking.objects.filter( 

31 item=item, 

32 tracking_type__in=[StockHistoryCode.SENT_TO_CUSTOMER, StockHistoryCode.SHIPPED_AGAINST_SALES_ORDER] 

33 ).order_by('-date').first() 

34 

35 if not history: 

36 continue 

37 

38 # We've already updated this one, it appears 

39 if history.tracking_type != StockHistoryCode.SENT_TO_CUSTOMER: 

40 continue 

41 

42 # Update the 'deltas' of this history to include SalesOrder information 

43 history.deltas['salesorder'] = item.sales_order.pk 

44 

45 # Change the history type 

46 history.tracking_type = StockHistoryCode.SHIPPED_AGAINST_SALES_ORDER.value 

47 

48 history.save() 

49 n += 1 

50 

51 if n > 0: 51 ↛ 52line 51 didn't jump to line 52 because the condition on line 51 was never true

52 print(f"Updated {n} StockItemTracking entries with SalesOrder data") 

53 

54 

55class Migration(migrations.Migration): 

56 

57 dependencies = [ 

58 ('stock', '0095_stocklocation_external'), 

59 ] 

60 

61 operations = [ 

62 migrations.RunPython( 

63 update_stock_history, reverse_code=migrations.RunPython.noop, 

64 ) 

65 ]