from django.db import transaction from .models import Item, StockLocation, StockLedger class StockMovementType: ISSUE = "ISSUE" # going out (consume, dispense, use) RECEIPT = "RECEIPT" # coming in (receive) ADJUSTMENT = "ADJUSTMENT" TRANSFER = "TRANSFER" @transaction.atomic def record_stock_movement(*, tenant, item_id, location_id, qty: float, movement_type: str, reference=None, performed_by=None, note:str=""): item = Item.objects.select_for_update().get(id=item_id, tenant=tenant) loc = StockLocation.objects.select_for_update().get(id=location_id, tenant=tenant) # Update on-hand (you likely store per-location balances; adjust to your schema) if movement_type == StockMovementType.ISSUE: loc.on_hand = (loc.on_hand or 0) - qty elif movement_type == StockMovementType.RECEIPT: loc.on_hand = (loc.on_hand or 0) + qty # ADJUSTMENT or TRANSFER handled similarly (or with from/to locations) loc.save(update_fields=["on_hand"]) StockLedger.objects.create( tenant=tenant, item=item, location=loc, qty=qty, movement_type=movement_type, reference=str(reference) if reference else "", note=note, performed_by=performed_by ) return loc.on_hand