Coverage for src/backend/InvenTree/stock/migrations/0064_auto_20210621_1724.py: 42%

28 statements  

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

1# Generated by Django 3.2.4 on 2021-06-21 07:24 

2 

3from django.db import migrations 

4 

5 

6def extract_purchase_price(apps, schema_editor): 

7 """ 

8 Find instances of StockItem which do *not* have a purchase price set, 

9 but which point to a PurchaseOrder where there *is* a purchase price set. 

10 

11 Then, assign *that* purchase price to original StockItem. 

12 

13 This is to address an issue where older versions of InvenTree 

14 did not correctly copy purchase price information cross to the StockItem objects. 

15 

16 Current InvenTree version (as of 2021-06-21) copy this information across correctly, 

17 so this one-time data migration should suffice. 

18 """ 

19 

20 # Required database models 

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

22 PurchaseOrder = apps.get_model('order', 'purchaseorder') 

23 PurchaseOrderLineItem = apps.get_model('order', 'purchaseorderlineitem') 

24 Part = apps.get_model('part', 'part') 

25 

26 # Find all the StockItem objects without a purchase_price which point to a PurchaseOrder 

27 items = StockItem.objects.filter(purchase_price=None).exclude(purchase_order=None) 

28 

29 if items.count() > 0: # pragma: no cover 29 ↛ 30line 29 didn't jump to line 30 because the condition on line 29 was never true

30 print(f"Found {items.count()} stock items with missing purchase price information") 

31 

32 update_count = 0 

33 

34 for item in items: # pragma: no cover 34 ↛ 36line 34 didn't jump to line 36 because the loop on line 34 never started

35 

36 part_id = item.part 

37 

38 po = item.purchase_order 

39 

40 # Look for a matching PurchaseOrderLineItem (with a price) 

41 lines = PurchaseOrderLineItem.objects.filter(part__part=part_id, order=po) 

42 

43 if lines.exists(): 

44 

45 for line in lines: 

46 if getattr(line, 'purchase_price', None) is not None: 

47 

48 # Copy pricing information across 

49 item.purchase_price = line.purchase_price 

50 item.purchases_price_currency = line.purchase_price_currency 

51 

52 print(f"- Updating supplier price for {item.part.name} - {item.purchase_price} {item.purchase_price_currency}") 

53 

54 update_count += 1 

55 

56 item.save() 

57 

58 break 

59 

60 if update_count > 0: # pragma: no cover 60 ↛ 61line 60 didn't jump to line 61 because the condition on line 60 was never true

61 print(f"Updated pricing for {update_count} stock items") 

62 

63 

64class Migration(migrations.Migration): 

65 

66 dependencies = [ 

67 ('stock', '0063_auto_20210511_2343'), 

68 ] 

69 

70 operations = [ 

71 migrations.RunPython(extract_purchase_price, reverse_code=migrations.RunPython.noop) 

72 ]