#!/usr/bin/env python """ Test script to verify WriteOff form validation prevents over-listing. This tests that WriteOffForm.clean() prevents creating WriteOff with quantity > batch.quantity """ import os import sys import django # Setup Django sys.path.insert(0, 'myproject') os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') django.setup() from inventory.forms import WriteOffForm from inventory.models import WriteOff, StockBatch, Warehouse, Product from django.core.exceptions import ValidationError print("=" * 70) print("Testing WriteOff Validation") print("=" * 70) # Create test data warehouse = Warehouse.objects.filter(is_active=True).first() if not warehouse: print("ERROR: No active warehouse found. Please create one first.") sys.exit(1) product = Product.objects.filter(tenant=warehouse.tenant).first() if not product: print("ERROR: No product found. Please create one first.") sys.exit(1) # Create a batch with 2 items batch = StockBatch.objects.create( product=product, warehouse=warehouse, quantity=2, cost_price=100.0, is_active=True ) print(f"\n✓ Created StockBatch with quantity=2") print(f" Product: {product.name}") print(f" Warehouse: {warehouse.name}") print(f" Batch ID: {batch.id}") # Test 1: Valid WriteOff (quantity = batch.quantity) print("\n" + "=" * 70) print("Test 1: Valid WriteOff with quantity=2 (equal to batch quantity)") print("=" * 70) form_data = { 'batch': batch.id, 'quantity': 2, 'reason': 'damage', 'document_number': 'DOC001', 'notes': 'Test valid writeoff' } form = WriteOffForm(data=form_data) if form.is_valid(): print("✓ PASS: Form is valid (quantity <= batch.quantity)") else: print(f"✗ FAIL: Form should be valid but has errors: {form.errors}") # Test 2: Invalid WriteOff (quantity > batch.quantity) print("\n" + "=" * 70) print("Test 2: Invalid WriteOff with quantity=3 (exceeds batch quantity=2)") print("=" * 70) form_data = { 'batch': batch.id, 'quantity': 3, 'reason': 'damage', 'document_number': 'DOC002', 'notes': 'Test invalid writeoff - should be rejected' } form = WriteOffForm(data=form_data) if not form.is_valid(): print("✓ PASS: Form validation correctly rejects over-listing") for field, errors in form.errors.items(): for error in errors: print(f" Error: {error}") else: print("✗ FAIL: Form should reject quantity > batch.quantity") # Test 3: Invalid WriteOff (quantity = 0) print("\n" + "=" * 70) print("Test 3: Invalid WriteOff with quantity=0 (should be > 0)") print("=" * 70) form_data = { 'batch': batch.id, 'quantity': 0, 'reason': 'damage', 'document_number': 'DOC003', 'notes': 'Test zero quantity' } form = WriteOffForm(data=form_data) if not form.is_valid(): print("✓ PASS: Form validation correctly rejects zero quantity") for field, errors in form.errors.items(): for error in errors: print(f" Error: {error}") else: print("✗ FAIL: Form should reject quantity <= 0") # Cleanup batch.delete() print("\n" + "=" * 70) print("Test completed successfully!") print("=" * 70)