inventory-calculator 1.0.0
A simple Python library for inventory stock calculations
Requires Python: >=3.7
Keywords: inventory stock calculator warehouse management

# Inventory Calculator

A simple, lightweight Python library for inventory stock calculations. Perfect for e-commerce, warehouse management, and inventory tracking applications.

## Features

- **Low Stock Detection** - Instantly check if items need reordering
- **Reorder Calculations** - Smart recommendations for restocking
- **Stock Validation** - Prevent negative stock and invalid transactions
- **Stock Status** - Get clear status: OUT_OF_STOCK, LOW_STOCK, NORMAL, OVERSTOCKED
- **Transaction Simulation** - Preview transaction effects before committing
- **Zero Dependencies** - Pure Python, no external packages required

## Installation

### From Source (Local Development)

```bash
cd inventory-calculator
pip install -e .
```

### From PyPI (After Publishing)

```bash
pip install inventory-calculator
```

## Quick Start

### Basic Usage

```python
from inventory_calculator import is_low_stock, calculate_reorder_quantity

# Check if stock is low
if is_low_stock(current_quantity=5, min_stock_level=10):
    print("Stock is low!")

# Calculate reorder quantity
reorder = calculate_reorder_quantity(
    current_quantity=5,
    min_stock_level=20,
    max_stock_level=100
)
print(f"Reorder {reorder} units")
```

### Using the StockCalculator Class

```python
from inventory_calculator import StockCalculator

# Create calculator instance
calculator = StockCalculator(
    current_quantity=50,
    min_stock_level=10,
    max_stock_level=200,
    unit_price=25.99
)

# Check stock status
if calculator.is_low_stock():
    print("Time to reorder!")
    print(f"Order quantity: {calculator.calculate_reorder_quantity()}")

# Get detailed status
print(f"Status: {calculator.get_stock_status()}")
print(f"Stock value: ${calculator.calculate_stock_value():.2f}")
print(f"Stock level: {calculator.get_stock_percentage():.1f}%")

# Get all info as dictionary
info = calculator.to_dict()
print(info)
```

### Transaction Validation

```python
from inventory_calculator import validate_transaction, StockValidationError

try:
    # This will raise an error - trying to remove more than available
    validate_transaction(
        transaction_type='OUT',
        quantity=100,
        current_stock=50
    )
except StockValidationError as e:
    print(f"Transaction error: {e}")
```

### Simulating Transactions

```python
from inventory_calculator import StockCalculator

calculator = StockCalculator(current_quantity=50, min_stock_level=10)

# Simulate removing 45 units
result = calculator.simulate_transaction('OUT', 45)

print(f"Original: {result['original_quantity']}")
print(f"After transaction: {result['new_quantity']}")
print(f"Will be low stock: {result['will_be_low_stock']}")
print(f"Can execute: {result['can_execute']}")
```

## API Reference

### Functions

#### `is_low_stock(current_quantity, min_stock_level)`
Check if stock is at or below minimum level.

**Returns:** `bool`

#### `calculate_reorder_quantity(current_quantity, min_stock_level, max_stock_level=None, safety_factor=1.5)`
Calculate recommended reorder quantity.

**Returns:** `int`

#### `calculate_stock_value(quantity, unit_price)`
Calculate total value of stock.

**Returns:** `float`

#### `get_stock_status(current_quantity, min_stock_level, max_stock_level=None)`
Get stock status as string.

**Returns:** `str` - One of: 'OUT_OF_STOCK', 'LOW_STOCK', 'NORMAL', 'OVERSTOCKED'

#### `validate_transaction(transaction_type, quantity, current_stock, field_name='quantity')`
Validate a stock transaction.

**Raises:** `StockValidationError` if invalid

### StockCalculator Class

#### Methods

- `is_low_stock()` - Check if stock is low
- `is_out_of_stock()` - Check if completely out of stock
- `is_overstocked()` - Check if exceeds maximum
- `get_stock_status()` - Get status string
- `calculate_reorder_quantity(safety_factor=1.5)` - Calculate reorder amount
- `calculate_stock_value()` - Get total stock value
- `can_fulfill_order(quantity)` - Check if order can be fulfilled
- `get_stock_percentage()` - Get stock as percentage of max
- `simulate_transaction(type, quantity)` - Preview transaction effects
- `to_dict()` - Get all data as dictionary

## Real-World Examples

### Django Model Integration

```python
from django.db import models
from inventory_calculator import is_low_stock, validate_transaction, StockValidationError

class Product(models.Model):
    name = models.CharField(max_length=200)
    quantity = models.IntegerField(default=0)
    min_stock_level = models.IntegerField(default=10)

    @property
    def is_low_stock(self):
        return is_low_stock(self.quantity, self.min_stock_level)

class Transaction(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    transaction_type = models.CharField(max_length=3)  # IN or OUT
    quantity = models.IntegerField()

    def clean(self):
        try:
            validate_transaction(
                self.transaction_type,
                self.quantity,
                self.product.quantity
            )
        except StockValidationError as e:
            from django.core.exceptions import ValidationError
            raise ValidationError({'quantity': str(e)})
```

### Flask API

```python
from flask import Flask, jsonify
from inventory_calculator import StockCalculator

app = Flask(__name__)

@app.route('/api/products/<int:product_id>/stock-info')
def get_stock_info(product_id):
    # Get product from database
    product = get_product_from_db(product_id)

    # Use calculator
    calculator = StockCalculator(
        current_quantity=product.quantity,
        min_stock_level=product.min_stock,
        unit_price=product.price
    )

    return jsonify(calculator.to_dict())
```

### Automated Reorder System

```python
from inventory_calculator import StockCalculator

def check_and_create_purchase_orders():
    products = Product.objects.all()

    for product in products:
        calculator = StockCalculator(
            current_quantity=product.quantity,
            min_stock_level=product.min_stock_level,
            max_stock_level=product.max_stock_level
        )

        if calculator.is_low_stock():
            reorder_qty = calculator.calculate_reorder_quantity()

            # Create purchase order
            PurchaseOrder.objects.create(
                product=product,
                quantity=reorder_qty,
                status='PENDING'
            )

            print(f"Created PO for {product.name}: {reorder_qty} units")
```

## Use Cases

- **E-commerce platforms** - Monitor product availability
- **Warehouse management** - Track inventory levels
- **POS systems** - Real-time stock validation
- **Manufacturing** - Raw material tracking
- **Retail** - Multi-location inventory
- **Supply chain** - Automated reordering

## Why This Library?

This library was extracted from a production Django inventory management system to provide a reusable, framework-agnostic solution for common inventory calculations.

**Benefits:**
- No framework dependencies
- Battle-tested logic
- Simple API
- Well documented
- Fully tested
- Type hints included

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

## License

MIT License - see LICENSE file for details

## Author

Your Name - [GitHub](https://github.com/yourusername)

## Changelog

### 1.0.0 (2024)
- Initial release
- Core stock calculation features
- Transaction validation
- Stock status detection