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
« 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
3from django.db import migrations
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.
11 Then, assign *that* purchase price to original StockItem.
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.
16 Current InvenTree version (as of 2021-06-21) copy this information across correctly,
17 so this one-time data migration should suffice.
18 """
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')
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)
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")
32 update_count = 0
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
36 part_id = item.part
38 po = item.purchase_order
40 # Look for a matching PurchaseOrderLineItem (with a price)
41 lines = PurchaseOrderLineItem.objects.filter(part__part=part_id, order=po)
43 if lines.exists():
45 for line in lines:
46 if getattr(line, 'purchase_price', None) is not None:
48 # Copy pricing information across
49 item.purchase_price = line.purchase_price
50 item.purchases_price_currency = line.purchase_price_currency
52 print(f"- Updating supplier price for {item.part.name} - {item.purchase_price} {item.purchase_price_currency}")
54 update_count += 1
56 item.save()
58 break
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")
64class Migration(migrations.Migration):
66 dependencies = [
67 ('stock', '0063_auto_20210511_2343'),
68 ]
70 operations = [
71 migrations.RunPython(extract_purchase_price, reverse_code=migrations.RunPython.noop)
72 ]