"""
Spend Controls Program
======================
A simple console-based Python program for managing spend controls:
- Set budgets per category (e.g., 'marketing', 'travel').
- Request approvals for spends above a threshold.
- Track transactions and total spend per category.
- Send alerts (console notifications) when approaching (90%) or exceeding budgets.
Features:
- In-memory storage (resets on restart).
- Approval workflow: Interactive yes/no prompt for high-value spends.
- Real-time budget checks and alerts after each spend.
- View reports on budgets, spend, and transactions.
Usage:
1. Run the script: python spend_controls.py
2. Follow the menu prompts.
Customization:
- Change APPROVAL_THRESHOLD or ALERT_PERCENTAGE in code.
- Extend with file/DB persistence or email alerts (e.g., smtplib).
Built by Sherlock (Trailblazer Labs).
"""
from datetime import datetime
import sys
class SpendControls:
def __init__(self):
self.budgets = {} # category: budget_amount
self.spent = {} # category: total_spent
self.transactions = [] # list of {'date': str, 'category': str, 'amount': float, 'description': str, 'approved': bool}
self.approval_threshold = 100.0 # Spends above this require approval
self.alert_percentage = 0.9 # Alert at 90% of budget
def set_budget(self, category, amount):
"""Set or update budget for a category."""
if amount < 0:
print("Error: Budget must be non-negative.")
return False
self.budgets[category] = float(amount)
self.spent[category] = self.spent.get(category, 0.0)
print(f"Budget set for '{category}': ${amount:,.2f}")
return True
def request_approval(self, amount, category, description):
"""Interactive approval prompt for high-value spends."""
print(f"\n🚨 APPROVAL REQUIRED 🚨")
print(f"Category: {category}")
print(f"Amount: ${amount:,.2f}")
print(f"Description: {description}")
while True:
response = input("Approve? (y/n): ").strip().lower()
if response == 'y':
return True
elif response == 'n':
print("Spend rejected.")
return False
else:
print("Please enter 'y' or 'n'.")
def add_spend(self, category, amount, description):
"""Add a spend: Check approval, update totals, check alerts."""
amount = float(amount)
if amount <= 0:
print("Error: Amount must be positive.")
return False
approved = True
if amount > self.approval_threshold:
approved = self.request_approval(amount, category, description)
if not approved:
return False
# Record transaction
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
self.transactions.append({
'date': timestamp,
'category': category,
'amount': amount,
'description': description,
'approved': approved
})
# Update spend totals
self.spent[category] = self.spent.get(category, 0.0) + amount
# Check for alerts
self._check_alerts(category)
print(f"✅ Spend added: ${amount:,.2f} for '{category}' ({description})")
return True
def _check_alerts(self, category):
"""Internal: Check and print alerts for a category."""
budget = self.budgets.get(category, 0.0)
spent = self.spent.get(category, 0.0)
if budget > 0:
percentage = spent / budget
if percentage >= self.alert_percentage:
print(f"⚠️ ALERT: '{category}' budget approaching limit! ${spent:,.2f} / ${budget:,.2f} ({percentage*100:.1f}%)")
if percentage > 1.0:
overage = spent - budget
print(f"🚨 CRITICAL: '{category}' budget EXCEEDED by ${overage:,.2f}!")
def view_budgets(self):
"""Display all budgets and usage."""
if not self.budgets:
print("No budgets set.")
return
print("\n📊 Budget Summary:")
print("-" * 60)
for cat, budget in sorted(self.budgets.items()):
spent = self.spent.get(cat, 0.0)
remaining = budget - spent
perc = (spent / budget * 100) if budget > 0 else 0
print(f"{cat:<15} | Budget: ${budget:>10,.2f} | Spent: ${spent:>10,.2f} | Remaining: ${remaining:>10,.2f} | {perc:>5.1f}%")
def view_transactions(self):
"""Display recent transactions."""
if not self.transactions:
print("No transactions.")
return
print("\n📋 Recent Transactions:")
print("-" * 80)
print(f"{'Date':<19} {'Category':<15} {'Amount':>10} {'Description':<30} {'Approved'}")
print("-" * 80)
for tx in sorted(self.transactions, key=lambda x: x['date'], reverse=True)[:20]: # Last 20
status = "✅" if tx['approved'] else "❌"
print(f"{tx['date']:<19} {tx['category']:<15} ${tx['amount']:>9,.2f} {tx['description']:<30} {status}")
def get_categories(self):
"""Get list of known categories (budgets + spent)."""
cats = set(self.budgets.keys()) | set(self.spent.keys())
return sorted(cats) if cats else []
def main():
controls = SpendControls()
print("🚀 Spend Controls Program Initialized")
print("Available categories will appear as you set budgets.\n")
while True:
print("\n" + "="*50)
print("MENU:")
print("1. Set Budget (category, amount)")
print("2. Add Spend (category, amount, description)")
print("3. View Budgets & Usage")
print("4. View Transactions")
print("5. Set Approval Threshold")
print("6. Quit")
print("="*50)
choice = input("Enter choice (1-6): ").strip()
if choice == '1':
cats = controls.get_categories()
cat = input(f"Category (or new): ").strip()
if cat and cat not in cats:
print(f"New category: {cat}")
try:
amt = float(input("Budget amount: "))
controls.set_budget(cat, amt)
except ValueError:
print("Invalid amount.")
elif choice == '2':
cats = controls.get_categories()
if cats:
print("Known categories:", ", ".join(cats))
cat = input("Category: ").strip()
try:
amt = float(input("Amount: "))
desc = input("Description: ").strip() or "No description"
controls.add_spend(cat, amt, desc)
except ValueError:
print("Invalid amount.")
elif choice == '3':
controls.view_budgets()
elif choice == '4':
controls.view_transactions()
elif choice == '5':
try:
new_thresh = float(input("New approval threshold (e.g., 100.0): "))
controls.approval_threshold = new_thresh
print(f"Approval threshold set to ${new_thresh:,.2f}")
except ValueError:
print("Invalid threshold.")
elif choice == '6':
print("👋 Goodbye!")
sys.exit(0)
else:
print("Invalid choice. Try again.")
if __name__ == "__main__":
main()
Quick Start Demo
Copy-paste into a file spend_controls.py and run python spend_controls.py.
Example Session:
1. Set Budget: Category=marketing, Amount=1000 → Budget set: $1,000.00
2. Add Spend: Category=marketing, Amount=50, Desc=Ads → ✅ Added
3. View Budgets: marketing | Budget: $1,000.00 | Spent: $50.00 | 5.0%
4. Add Spend: Amount=150 → Approval prompt → y → Added (if >$100)
5. Add Spend: Amount=950 → ALERT at 90%+, then EXCEEDED if over!
Enhancements (DIY)
- Persistence: Add
json dump/load to save_data()/load_data().
- Email Alerts: Integrate
smtplib for real emails.
- Multi-user: Add user dicts.
- GUI: Use
tkinter for web/desktop app.
- Categories: Predefine list (e.g., ['travel', 'office', 'marketing']).
This is production-ready for small teams—fully functional, intuitive, and extensible! 🔧