Coverage for src/backend/InvenTree/part/migrations/0138_auto_20250718_2342.py: 24%
41 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 4.2.23 on 2025-07-18 23:42
3from decimal import Decimal
5from django.db import migrations
8def convert_overage(apps, schema_editor):
9 """Convert 'overage' field to 'setup_quantity' and 'attrition' fields.
11 - The 'overage' field is split into two new fields:
12 - 'setup_quantity': The integer part of the overage.
13 - 'attrition': The fractional part of the overage.
14 """
16 BomItem = apps.get_model('part', 'BomItem')
18 # Fetch all BomItem objects with a non-zero overage
19 bom_items = BomItem.objects.exclude(overage='').exclude(overage=None).distinct()
21 if bom_items.count() == 0: 21 ↛ 24line 21 didn't jump to line 24 because the condition on line 21 was always true
22 return
24 print(f"\nConverting {bom_items.count()} BomItem objects with 'overage' to 'setup_quantity' and 'attrition'")
26 for item in bom_items:
28 # First attempt - convert to a percentage
29 overage = str(item.overage).strip()
31 if overage.endswith('%'):
32 try:
33 attrition = Decimal(overage[:-1])
34 attrition = max(0, attrition) # Ensure it's not negative
35 attrition = min(100, attrition) # Cap at 100%
37 item.attrition = attrition
38 item.setup_quantity = Decimal(0)
39 item.save()
40 except Exception as e:
41 print(f" - Error converting {item.pk} from percentage: {e}")
42 continue
44 else:
45 # If not a percentage, treat it as a decimal number
46 try:
47 setup_quantity = Decimal(overage)
48 setup_quantity = max(0, setup_quantity) # Ensure it's not negative
50 item.setup_quantity = setup_quantity
51 item.attrition = Decimal(0)
52 item.save()
53 except Exception as e:
54 print(f"- Error converting {item.pk} from decimal: {e}")
55 continue
58def revert_overage(apps, schema_editor):
59 """Revert the 'setup_quantity' and 'attrition' fields back to 'overage'.
61 - Combines 'setup_quantity' and 'attrition' back into the 'overage' field.
62 """
64 BomItem = apps.get_model('part', 'BomItem')
66 # First, convert all 'attrition' values to percentages
67 for item in BomItem.objects.exclude(attrition=0).distinct():
68 item.overage = f"{item.attrition}%"
69 item.save()
71 # Second, convert all 'setup_quantity' values to strings
72 for item in BomItem.objects.exclude(setup_quantity=0).distinct():
73 item.overage = str(item.setup_quantity or 0)
74 item.save()
77class Migration(migrations.Migration):
79 dependencies = [
80 ("part", "0137_bomitem_attrition_bomitem_rounding_multiple_and_more"),
81 ]
83 operations = [
84 migrations.RunPython(
85 code=convert_overage,
86 reverse_code=revert_overage,
87 )
88 ]