Spaces:
Running
Running
File size: 1,829 Bytes
03a907a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | import json
import os
def process_inventory_data(filepath: str, update_threshold: int) -> dict:
"""
Process an inventory JSON file and return statistics.
Expected JSON format:
{
"store_id": "ST-001",
"items": [
{"id": "A1", "name": "Widget", "stock": 50, "price": 10.99, "category": "tools"},
{"id": "A2", "name": "Gadget", "stock": 10, "price": 25.50, "category": "electronics"}
]
}
Returns a dict with:
- 'total_value': total value of all stock
- 'low_stock_items': list of item names with stock < update_threshold
- 'categories': dict mapping category to total stock
"""
# BUG 1: File descriptor leak, no context manager
f = open(filepath, 'r')
try:
data = json.loads(f.read())
except ValueError:
# BUG 2: Broad exception catch that swallows the error, returns incorrect default
return None
total_value = 0
low_stock = []
categories = {}
# BUG 3: Not checking if 'items' key exists, could crash
for item in data['items']:
# BUG 4: Type mismatch risk if stock or price are strings in JSON
stock = item.get('stock', 0)
price = item.get('price', 0.0)
total_value += stock * price
if stock < update_threshold:
low_stock.append(item['name'])
cat = item.get('category', 'uncategorized')
# BUG 5: using setdefault improperly, overrides value
categories.setdefault(cat, 0)
categories[cat] = stock # Overwrites instead of adding
f.close()
return {
'total_value': total_value,
'low_stock_items': low_stock,
'categories': categories
}
|